agentix-cli 0.206.1 → 0.207.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-IEUOKINQ.js → App-64NXDO3Q.js} +2 -2
- package/dist/{ChatApp-CCDBG6YZ.js → ChatApp-LZSQ4233.js} +2 -2
- package/dist/{absorb-eval-IIF7CY3Q.js → absorb-eval-XG6QUTN6.js} +2 -2
- package/dist/{adapter-LTHULD3D.js → adapter-SDLSX2ZH.js} +2 -2
- package/dist/{agent-TZ3GGNS5.js → agent-TYURILCF.js} +2 -2
- package/dist/{board-dashboard-JS6OJDH6.js → board-dashboard-MLNL4EZ7.js} +21 -6
- package/dist/board-dashboard-MLNL4EZ7.js.map +1 -0
- package/dist/{chunk-E2MW5OCE.js → chunk-2GAMPUOB.js} +2 -2
- package/dist/{chunk-6U34GZ7U.js → chunk-2W23ZJCP.js} +2 -2
- package/dist/{chunk-Z6J3RTYJ.js → chunk-3ALELN73.js} +2 -2
- package/dist/{chunk-JDU4CXGC.js → chunk-3FUW6RXU.js} +2 -2
- package/dist/{chunk-KXMC7Z5X.js → chunk-3MUWPMC2.js} +2 -2
- package/dist/{chunk-I4753XPP.js → chunk-5YJ5GQCJ.js} +2 -2
- package/dist/{chunk-M37WJANA.js → chunk-6TZQZGRI.js} +65 -65
- package/dist/chunk-6TZQZGRI.js.map +1 -0
- package/dist/{chunk-K435U2FC.js → chunk-7MRDQLOS.js} +2 -2
- package/dist/{chunk-ZOK6VMEP.js → chunk-AECUZTRB.js} +2 -2
- package/dist/{chunk-U3OJO7B7.js → chunk-B34OLAAC.js} +36 -36
- package/dist/chunk-B34OLAAC.js.map +1 -0
- package/dist/{chunk-WI7J22NL.js → chunk-BBMGXNHU.js} +2 -2
- package/dist/{chunk-UN7D7HWU.js → chunk-CRSHJYZQ.js} +2 -2
- package/dist/{chunk-I74PTSUQ.js → chunk-DH7Z3HRC.js} +2 -2
- package/dist/{chunk-RRLQTU3X.js → chunk-EOQNFLFJ.js} +2 -2
- package/dist/{chunk-GCBFLU64.js → chunk-LTLH2CHG.js} +12 -6
- package/dist/chunk-LTLH2CHG.js.map +1 -0
- package/dist/{chunk-7JHB3X5N.js → chunk-NKSQNQ5V.js} +60 -60
- package/dist/chunk-NKSQNQ5V.js.map +1 -0
- package/dist/{chunk-WTCMJZW3.js → chunk-PSLSU6HC.js} +2 -2
- package/dist/{chunk-VALKXSXZ.js → chunk-RHXBLKBW.js} +2 -2
- package/dist/{chunk-R6XJWFMC.js → chunk-RWZGW2GQ.js} +2 -2
- package/dist/{chunk-7GD5GTWC.js → chunk-TYKEHZZA.js} +2 -2
- package/dist/{chunk-37EABHYL.js → chunk-UF3D5LFH.js} +2 -2
- package/dist/{chunk-XTIPWYW5.js → chunk-VIWN3CXS.js} +3 -3
- package/dist/chunk-VIWN3CXS.js.map +1 -0
- package/dist/{chunk-RPL2P7EP.js → chunk-VKEL4XNO.js} +2 -2
- package/dist/{chunk-FXA2WIIP.js → chunk-XEMW37IV.js} +2 -2
- package/dist/{chunk-6ZVVAGTR.js → chunk-XGCSWSVD.js} +2 -2
- package/dist/{chunk-CARVBJB7.js → chunk-YLKEUO6K.js} +2 -2
- package/dist/{chunk-CARVBJB7.js.map → chunk-YLKEUO6K.js.map} +1 -1
- package/dist/{chunk-TLRTJV2U.js → chunk-ZEJ2ZG6K.js} +290 -290
- package/dist/chunk-ZEJ2ZG6K.js.map +1 -0
- package/dist/{chunk-A2K6C6W3.js → chunk-ZJXJN6GM.js} +3 -3
- package/dist/{chunk-B35GIWMR.js → chunk-ZT32DUC7.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-NPC2JAWL.js → client-HC5UIRHC.js} +2 -2
- package/dist/{config-TIMTRSFH.js → config-FUB5TUCM.js} +2 -2
- package/dist/{config-mutate-V3DRUCK4.js → config-mutate-5WSQJAJO.js} +2 -2
- package/dist/{config-mutator-HOYYIPNW.js → config-mutator-RALUVF77.js} +2 -2
- package/dist/{contributions-TYVRQG7F.js → contributions-SSQ2H2H6.js} +2 -2
- package/dist/{doctor-TNQ4Q2OS.js → doctor-FAC34AQ6.js} +2 -2
- package/dist/{follow-up-tool-3P2YCRBL.js → follow-up-tool-JCJSBAJF.js} +2 -2
- package/dist/{hub-GVTRKPAU.js → hub-YAEE5GFW.js} +2 -2
- package/dist/index.d.ts +79 -1
- package/dist/index.js +1 -1
- package/dist/{org-tool-EKO7GCPL.js → org-tool-YP256FUE.js} +2 -2
- package/dist/{program-Y55FFHIJ.js → program-3I7GFFDP.js} +23 -23
- package/dist/{promote-JYYV44FK.js → promote-NJWI2KUT.js} +2 -2
- package/dist/{query-PUWWCFET.js → query-O5EWN3YT.js} +2 -2
- package/dist/{query-settings-IJPG3N6D.js → query-settings-VKOJGJGC.js} +2 -2
- package/dist/{registry-QJGTPSK2.js → registry-W77Q7ZGZ.js} +2 -2
- package/dist/{request-planner-HHJXCWCG.js → request-planner-UY46HBKG.js} +2 -2
- package/dist/{review-candidates-XZUQELL5.js → review-candidates-A4BTJYML.js} +2 -2
- package/dist/{routing-HWZHJ4LZ.js → routing-THT4U4KK.js} +2 -2
- package/dist/schedule-tool-FVBUHIDC.js +2 -0
- package/dist/{scheduler-WG3KXJIH.js → scheduler-MHTDA3ZS.js} +2 -2
- package/dist/{seat-5BOBWKBX.js → seat-NW3JTDGK.js} +2 -2
- package/dist/{select-FIHHBFNR.js → select-4DILJ2XW.js} +2 -2
- package/dist/{set-enabled-K7OM7PSO.js → set-enabled-DKQTH2PC.js} +2 -2
- package/dist/{sprint-tool-O6TTSWJN.js → sprint-tool-43TSRPK4.js} +2 -2
- package/dist/{tool-HTUSCV22.js → tool-7MI3GK2K.js} +2 -2
- package/dist/{tool-BYU6EZKM.js → tool-JYSRWVNB.js} +2 -2
- package/dist/{tool-HVCLZGYE.js → tool-NA7ZOWD5.js} +2 -2
- package/dist/{tool-4KVS2JWC.js → tool-PQZ7NURW.js} +2 -2
- package/dist/{wiki-ZMEMGR7R.js → wiki-NR2KS3AT.js} +2 -2
- package/dist/wiki-enrich-EB2EOVDJ.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-JS6OJDH6.js.map +0 -1
- package/dist/chunk-7JHB3X5N.js.map +0 -1
- package/dist/chunk-GCBFLU64.js.map +0 -1
- package/dist/chunk-M37WJANA.js.map +0 -1
- package/dist/chunk-TLRTJV2U.js.map +0 -1
- package/dist/chunk-U3OJO7B7.js.map +0 -1
- package/dist/chunk-XTIPWYW5.js.map +0 -1
- package/dist/schedule-tool-7W5CRUN4.js +0 -2
- package/dist/wiki-enrich-QZHQV7VZ.js +0 -2
- /package/dist/{App-IEUOKINQ.js.map → App-64NXDO3Q.js.map} +0 -0
- /package/dist/{ChatApp-CCDBG6YZ.js.map → ChatApp-LZSQ4233.js.map} +0 -0
- /package/dist/{absorb-eval-IIF7CY3Q.js.map → absorb-eval-XG6QUTN6.js.map} +0 -0
- /package/dist/{adapter-LTHULD3D.js.map → adapter-SDLSX2ZH.js.map} +0 -0
- /package/dist/{agent-TZ3GGNS5.js.map → agent-TYURILCF.js.map} +0 -0
- /package/dist/{chunk-E2MW5OCE.js.map → chunk-2GAMPUOB.js.map} +0 -0
- /package/dist/{chunk-6U34GZ7U.js.map → chunk-2W23ZJCP.js.map} +0 -0
- /package/dist/{chunk-Z6J3RTYJ.js.map → chunk-3ALELN73.js.map} +0 -0
- /package/dist/{chunk-JDU4CXGC.js.map → chunk-3FUW6RXU.js.map} +0 -0
- /package/dist/{chunk-KXMC7Z5X.js.map → chunk-3MUWPMC2.js.map} +0 -0
- /package/dist/{chunk-I4753XPP.js.map → chunk-5YJ5GQCJ.js.map} +0 -0
- /package/dist/{chunk-K435U2FC.js.map → chunk-7MRDQLOS.js.map} +0 -0
- /package/dist/{chunk-ZOK6VMEP.js.map → chunk-AECUZTRB.js.map} +0 -0
- /package/dist/{chunk-WI7J22NL.js.map → chunk-BBMGXNHU.js.map} +0 -0
- /package/dist/{chunk-UN7D7HWU.js.map → chunk-CRSHJYZQ.js.map} +0 -0
- /package/dist/{chunk-I74PTSUQ.js.map → chunk-DH7Z3HRC.js.map} +0 -0
- /package/dist/{chunk-RRLQTU3X.js.map → chunk-EOQNFLFJ.js.map} +0 -0
- /package/dist/{chunk-WTCMJZW3.js.map → chunk-PSLSU6HC.js.map} +0 -0
- /package/dist/{chunk-VALKXSXZ.js.map → chunk-RHXBLKBW.js.map} +0 -0
- /package/dist/{chunk-R6XJWFMC.js.map → chunk-RWZGW2GQ.js.map} +0 -0
- /package/dist/{chunk-7GD5GTWC.js.map → chunk-TYKEHZZA.js.map} +0 -0
- /package/dist/{chunk-37EABHYL.js.map → chunk-UF3D5LFH.js.map} +0 -0
- /package/dist/{chunk-RPL2P7EP.js.map → chunk-VKEL4XNO.js.map} +0 -0
- /package/dist/{chunk-FXA2WIIP.js.map → chunk-XEMW37IV.js.map} +0 -0
- /package/dist/{chunk-6ZVVAGTR.js.map → chunk-XGCSWSVD.js.map} +0 -0
- /package/dist/{chunk-A2K6C6W3.js.map → chunk-ZJXJN6GM.js.map} +0 -0
- /package/dist/{chunk-B35GIWMR.js.map → chunk-ZT32DUC7.js.map} +0 -0
- /package/dist/{client-NPC2JAWL.js.map → client-HC5UIRHC.js.map} +0 -0
- /package/dist/{config-TIMTRSFH.js.map → config-FUB5TUCM.js.map} +0 -0
- /package/dist/{config-mutate-V3DRUCK4.js.map → config-mutate-5WSQJAJO.js.map} +0 -0
- /package/dist/{config-mutator-HOYYIPNW.js.map → config-mutator-RALUVF77.js.map} +0 -0
- /package/dist/{contributions-TYVRQG7F.js.map → contributions-SSQ2H2H6.js.map} +0 -0
- /package/dist/{doctor-TNQ4Q2OS.js.map → doctor-FAC34AQ6.js.map} +0 -0
- /package/dist/{follow-up-tool-3P2YCRBL.js.map → follow-up-tool-JCJSBAJF.js.map} +0 -0
- /package/dist/{hub-GVTRKPAU.js.map → hub-YAEE5GFW.js.map} +0 -0
- /package/dist/{org-tool-EKO7GCPL.js.map → org-tool-YP256FUE.js.map} +0 -0
- /package/dist/{program-Y55FFHIJ.js.map → program-3I7GFFDP.js.map} +0 -0
- /package/dist/{promote-JYYV44FK.js.map → promote-NJWI2KUT.js.map} +0 -0
- /package/dist/{query-PUWWCFET.js.map → query-O5EWN3YT.js.map} +0 -0
- /package/dist/{query-settings-IJPG3N6D.js.map → query-settings-VKOJGJGC.js.map} +0 -0
- /package/dist/{registry-QJGTPSK2.js.map → registry-W77Q7ZGZ.js.map} +0 -0
- /package/dist/{request-planner-HHJXCWCG.js.map → request-planner-UY46HBKG.js.map} +0 -0
- /package/dist/{review-candidates-XZUQELL5.js.map → review-candidates-A4BTJYML.js.map} +0 -0
- /package/dist/{routing-HWZHJ4LZ.js.map → routing-THT4U4KK.js.map} +0 -0
- /package/dist/{schedule-tool-7W5CRUN4.js.map → schedule-tool-FVBUHIDC.js.map} +0 -0
- /package/dist/{scheduler-WG3KXJIH.js.map → scheduler-MHTDA3ZS.js.map} +0 -0
- /package/dist/{seat-5BOBWKBX.js.map → seat-NW3JTDGK.js.map} +0 -0
- /package/dist/{select-FIHHBFNR.js.map → select-4DILJ2XW.js.map} +0 -0
- /package/dist/{set-enabled-K7OM7PSO.js.map → set-enabled-DKQTH2PC.js.map} +0 -0
- /package/dist/{sprint-tool-O6TTSWJN.js.map → sprint-tool-43TSRPK4.js.map} +0 -0
- /package/dist/{tool-HTUSCV22.js.map → tool-7MI3GK2K.js.map} +0 -0
- /package/dist/{tool-BYU6EZKM.js.map → tool-JYSRWVNB.js.map} +0 -0
- /package/dist/{tool-HVCLZGYE.js.map → tool-NA7ZOWD5.js.map} +0 -0
- /package/dist/{tool-4KVS2JWC.js.map → tool-PQZ7NURW.js.map} +0 -0
- /package/dist/{wiki-ZMEMGR7R.js.map → wiki-NR2KS3AT.js.map} +0 -0
- /package/dist/{wiki-enrich-QZHQV7VZ.js.map → wiki-enrich-EB2EOVDJ.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var
|
|
3
|
-
`),Ui(r,n)}function
|
|
4
|
-
`).pop()?.slice(0,300)||"no output";async function qr(t,e,n,r=
|
|
5
|
-
`,{mode:384}),
|
|
1
|
+
import{a as ft}from"./chunk-GTJIKXDB.js";import{H as vr,O as Rr,k as K}from"./chunk-XGCSWSVD.js";import{f as _r,g as $r,h as Tr,l as Ar}from"./chunk-2W23ZJCP.js";import{a as Er}from"./chunk-JSCVOB4G.js";import{b as Sr}from"./chunk-2VDO2HEK.js";import{t as xr,u as kr}from"./chunk-AECUZTRB.js";import{d as yr,e as wr}from"./chunk-AQASR6KR.js";import{h as pe,j as lr,l as cr,m as dr,n as ur}from"./chunk-RX5O5637.js";import{h as rr,i as or,j as sr,l as ir,m as ar}from"./chunk-2GAMPUOB.js";import{a as pr,c as gr,e as mr,f as ut,h as fr,j as hr,k as br,l as pt,m as gt,n as mt}from"./chunk-5ELIX7BQ.js";import{a as tr,c as nr}from"./chunk-KP7KDLZ2.js";import{c as Re,d as Zn,e as er}from"./chunk-XVV7ZZ77.js";import{Aa as ue,Ca as dt,b as at,f as zn,s as lt,u as ct,xa as Ae,ya as Qn,za as W}from"./chunk-B34OLAAC.js";import{a as $e,b as de,e as Kn}from"./chunk-7AB3QUGH.js";import{s as Jn}from"./chunk-VIWN3CXS.js";import{a as Gn,b as Te,e as Yn}from"./chunk-RHXBLKBW.js";import{b as ee}from"./chunk-5ONH4ITT.js";import{a as Xn,c as it}from"./chunk-ILEC3IAV.js";import{a as Mn}from"./chunk-QUFIUXMQ.js";import{a as Fn,i as qn,l as Hn,n as ot,o as st,r as ce,s as Z,u as Vn}from"./chunk-XL7UWG36.js";import{a as Un,b as Wn,d as jn,e as Bn}from"./chunk-MNG2AMKZ.js";import{E as _e,F as $n,G as Tn,Gb as On,H as ki,Hb as Ln,Rb as Pn,f as Ze,g as C,i as Ee,j as E,k as le,l as En,o as _n,p as et,ta as In,ua as Dn,wa as Cn,xa as Nn,xb as rt}from"./chunk-YLKEUO6K.js";import{a as tt,h as vi}from"./chunk-KEUW6YLL.js";import{j as nt,q as An,r as Rn}from"./chunk-UEEB3UTU.js";import{existsSync as Si,readdirSync as Ei,readFileSync as _i,statSync as $i}from"fs";import{resolve as Ti}from"path";function Ir(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var Ie=new Map;function Du(t,e=1e3){if(!Si(t))return[];let n=Ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ti(t,s);return{path:i,mtime:$i(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Ie.keys())r.has(s)||Ie.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Ie.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ai(s,i);Ie.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ai(t,e){try{let n=_i(t,"utf-8").split(`
|
|
2
|
+
`).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Dr=7,Ri={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Ii=(t,e,n)=>{try{return Jn(t,e,n)}catch{return null}},Cr=864e5;function Lu(t){let e=t.now??Date.now(),n={...Ri,...t.thresholds},r=t.nextFire??Ii,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,A.text),trigger:{schedule:F(a.schedule,A.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ht(a.nextRun)??ht(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Pi(p.status==="success"?void 0:p.errorSummary,A.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Nr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Dr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Or(u,c,a.schedule,l,null,e,n,r),o.push(Lr(u))}let s=new Map(Ir(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Ni(k.status)})),m=g[0],f=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:f?"schedule":"event",name:F(a.title||a.id,A.text),trigger:f?{schedule:F(w,A.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",A.text),filters:Li(l.filter,a)},agent:Oi(a),enabled:p,state:c,nextRunAt:f&&p&&w?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:Nr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Dr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Or(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Di(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Lr(b))}return o.sort(Ci).slice(0,A.routines)}function Nr(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 Or(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Mr(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function Di(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Mr(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 Mr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Cr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Cr)} days`:"Disabled and never ran"}}function Lr(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 Pr={critical:0,warning:1,info:2};function Ci(t,e){let n=t.attention?Pr[t.attention]:3,r=e.attention?Pr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Ni(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Oi(t){if(t.ownerAgent)return F(t.ownerAgent,A.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),A.text):null}function Li(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,A.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,A.filterValue))}return n.slice(0,A.filters)}function 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 Pi(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Mi,readFileSync as Fi,renameSync as Ui,writeFileSync as Wi}from"fs";import{resolve as ji}from"path";function Fr(t){return ji(st(t),"_state.json")}function N(t){try{let e=JSON.parse(Fi(Fr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function ge(t,e){Mi(st(t),{recursive:!0});let n=Fr(t),r=`${n}.${process.pid}.tmp`;Wi(r,JSON.stringify(e,null,2)+`
|
|
3
|
+
`),Ui(r,n)}function Ur(t,e,n,r=Date.now()){let o=N(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),ge(t,{...o,snoozed:s})}function Wu(t,e){ge(t,{...N(t),lastDigest:e})}function 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 Wr(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function ju(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as Bi,readFileSync as qi}from"fs";Pn();vi();function jr(t){let e=Gn(t),n={};if(Bi(e))try{n=On(JSON.parse(qi(e,"utf-8")))}catch{n={}}let r=rt.safeParse(n?.requests);return r.success?r.data:rt.parse(void 0)}async function zu(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 da,readFileSync as kt,statSync as ua}from"fs";import{dirname as ao,resolve as T}from"path";import{randomBytes as Hr}from"crypto";import{existsSync as Vi,mkdirSync as Xi,readdirSync as zi,readFileSync as Ki,renameSync as Vr,unlinkSync as Gi,writeFileSync as Yi}from"fs";import{resolve as Xr}from"path";function Br(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Hi=t=>t.trim().split(`
|
|
4
|
+
`).pop()?.slice(0,300)||"no output";async function qr(t,e,n,r=ft){let o=await r(t.bin,[...Br(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Hi(o.stderr||o.stdout)}`}}async function Yu(t,e,n,r,o=ft){return(await o(t.bin,[...Br(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Ji=2e3,Qi=t=>qr(t.wacli,t.to,t.text);function yt(t){return Xr(t,".agentx","whatsapp-triage","drafts")}var Zi=t=>/^[a-z0-9-]{8,64}$/.test(t),De=(t,e)=>Xr(yt(t),`${e}.json`);function zr(t,e){Xi(yt(t),{recursive:!0});let n=De(t,e.id),r=`${n}.${process.pid}.tmp`;Yi(r,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{mode:384}),Vr(r,n)}function np(t,e,n=Date.now()){let r=e.text.trim().slice(0,Ji);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${Hr(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return zr(t,o),o}function Ce(t,e){if(!Zi(e))return null;try{return JSON.parse(Ki(De(t,e),"utf-8"))}catch{return null}}function Kr(t,e){let n=yt(t);return Vi(n)?zi(n).filter(r=>r.endsWith(".json")).map(r=>Ce(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function Gr(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}.${Hr(3).toString("hex")}.claim`;try{Vr(De(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...o,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??Qi)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}zr(t,i);try{Gi(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as ea,writeFileSync as ta}from"fs";import{resolve as Jr}from"path";var Qr="ready",na="202510";function ra(t){let e=t.date??t.created_at.slice(0,10);return Jr(t.workspace,Qr,`${e}-${t.platform}-${t.id}.txt`)}function Yr(t){let e=ra(t);return ea(Jr(t.workspace,Qr),{recursive:!0}),ta(e,t.text.endsWith(`
|
|
6
6
|
`)?t.text:`${t.text}
|
|
7
|
-
`),e}function
|
|
7
|
+
`),e}function Zr(t,e,n){let r=Er(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 eo(t,e,n){return Zr(t,e,n)!==null}async function oa(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let o=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??na),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function sa(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function ia(t,e){let n=Zr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Yr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await oa(t.text,n,r):await sa(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Yr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function to(t){return e=>ia(e,t)}Rn();Nn();Nn();Rn();var up=["done","skipped"],aa=1e3;function la(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,
|
|
@@ -60,17 +60,17 @@ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as kr,O as Ar,k as K}from"./ch
|
|
|
60
60
|
told_at INTEGER,
|
|
61
61
|
PRIMARY KEY (goal_key, day)
|
|
62
62
|
);
|
|
63
|
-
`),
|
|
63
|
+
`),An(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]])}function ro(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function wt(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function no(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var ca={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at"},Ne=class{constructor(e){this.db=e;la(e)}create(e,n,r,o){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
|
|
64
64
|
to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
|
|
65
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,d)=>{let l=d===0,c=l&&a.agentId===n&&a.kind!=="message";i.run(e,d+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?o:null,o,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,o)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?
|
|
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(no)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?no(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=ca[i];!d||a===void 0||(o.push(`${d} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}o.length&&this.db.prepare(`UPDATE request_plan_steps SET ${o.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(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,aa))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
|
|
66
66
|
ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
|
|
67
|
-
told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},pp=Rn;var ao=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],pa=280;function O(t,e=pa){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return T(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function ga(t){return Z(t.root,"pending").map(ma)}function ma(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function fa(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(xt(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let d=i.timezone||"UTC",l=i.schedule?nr(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 ${or(rr(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function lo(t){let e=T(t,".agentx","memory");return H(e)?da(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ha(t){let e=lo(t.root);if(e.length===0)return[];let n=new it(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:O(s.content),more:`agentx memory facts held --agent ${o}`});return r}function ba(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function ya(t){return yr(V(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:O(`${ba(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var ro=new Map;function co(t,e){let n=ua(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=ro.get(t);if(o?.version===r)return o.value;let s=e();return ro.set(t,{version:r,value:s}),s}function wa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function xa(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new ee(n),"pending").find(o=>o.id===e);return r?wa(r):void 0}function ka(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=co(e,()=>Re(new ee(io(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function va(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function uo(t){let e=V(t),n=new st(e);if(!H(n.path))return[];let r=co(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:va(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Sa(t){return zr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function Ea(t){return _r(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:O(`Last try not sent: ${e.error}`)}:{}}))}function _a(t){let e=Object.entries(at(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Oe(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:O(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Oe(t){try{return JSON.parse(xt(te(t),"utf-8"))}catch{return{}}}function wt(t){let e={};try{e=Object.fromEntries(Pn(xt(T(io(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function $a(t){let e=cr(t.root,"pending");if(e.length===0)return[];let n=Oe(t),r=wt(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:Zr({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:O(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:ar(o.text)}})}function G(t){if(t.requests)return t.requests;if(T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e)return null;let n=oo.get(e);return!n&&!In(e)?null:(n||oo.set(e,n=new Dn(e)),n)}var oo=new WeakMap;function Wp(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e||!no(e))return null;let n=so.get(e);return n||so.set(e,n=new Ne(e)),n}var so=new WeakMap;function Ta(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var po={card:ga,schedule:fa,agent:_a,memory:ha,wiki:ya,fact:()=>[],question:uo,whatsapp:Sa,email:Ea,content:$a,request:Ta};function Aa(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function go(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??ao){if(d==="fact"){try{let c=ka(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=po[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Aa),{items:o,snoozed:a,errors:s,backlog:i}}function mo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!ao.includes(n)||!r?null:{kind:n,ref:r}}function Ra(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return br(V(t),n)?.status==="pending";case"whatsapp":return Ce(t.root,n)?.status==="pending";case"email":return Er(t.root,n)?.status==="pending";case"content":return lr(t.root,n)?.status==="pending";default:return!!fo(t,e,n)}}function fo(t,e,n){return e==="fact"?xa(t,n):po[e](t).find(r=>r.key===`${e}:${n}`)}async function ho(t,e,n,r={}){let o=n==="later"?null:mo(e),s;if(o)try{s=fo(t,o.kind,o.ref)}catch{s=void 0}let i=await Ia(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Mn(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ia(t,e,n,r){let o=mo(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!Ra(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return Fr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Hn(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?sr:ir)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(at(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return lt(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let c=[],p=await Te(u=>{Gn(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?(lt(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!lo(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new it(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?wr(c,i,{by:d,force:r.force,now:a}):xr(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Da(t,e,i,l,d,r);case"question":return Na(t,e,i,l,d,r);case"whatsapp":{let c=await Kr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Tr(Oe(t),wt(t)),p=await $r(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??eo({config:Oe(t),env:wt(t)}),p=await dr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Wr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a),{ok:!0,message:`${e}: dropped`})}}}function Da(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 Zn(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=Qn(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Ca(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function Na(t,e,n,r,o,s){let i=V(t),a=new st(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Vn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=uo(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Ca(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new 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 Oa=3,La=7,Pa=50,vt=120,Ma=280,kt=600,yo=36e5,Fa=24*yo;function Bp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Le=t=>new Date(t).toISOString();function Ua(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:ne(e.title,vt),...e.ask?{ask:ne(e.ask,kt)}:{},...e.detail?{facts:ne(e.detail,Ma)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var Wa={done:"Done",declined:"Declined",dropped:"Dropped"};function wo(t,e,n){let{record:r,links:o}=e,s=K(r,vt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,kt)}:{},agent:r.agentId,askedAt:Le(r.createdAt),changedAt:Le(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:ne(r.question,kt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??Oa)*yo;return{...i,column:a||d?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Le(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Wa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ja(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function qa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,vt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ja(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,bo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function St(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(Ua(o,s,o.node===t.node))}let r=xo(t,e);for(let o of t.requests??[]){let s=wo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function xo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Hp(t){let e=St(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,o=xo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=wo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??La)*Fa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(qa(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Pa),c=bo(n,"askedAt"),p=bo(i,"changedAt");return{ts:Le(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Ba(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Ha(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function Kp(t,e){let n=t.now??Date.now(),r=[],o=go(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=St({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ba)}],requests:a,deferred:i});return Ha(d,i.size,[...r,...l])}import{readFileSync as Va}from"fs";var Xa=1e4,ko=/^[0-9a-f]{7,64}$/i;function Jp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&ko.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(Xa)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&ko.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Qp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Va(n.tokenFile,"utf-8").trim().split(`
|
|
68
|
-
`)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var
|
|
67
|
+
told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},pp=In;var lo=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],pa=280;function O(t,e=pa){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return T(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function ga(t){return Z(t.root,"pending").map(ma)}function ma(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function fa(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(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?rr(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 ${sr(or(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function co(t){let e=T(t,".agentx","memory");return H(e)?da(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ha(t){let e=co(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 ba(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function ya(t){return wr(V(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:O(`${ba(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var oo=new Map;function uo(t,e){let n=ua(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=oo.get(t);if(o?.version===r)return o.value;let s=e();return oo.set(t,{version:r,value:s}),s}function wa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function xa(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new ee(n),"pending").find(o=>o.id===e);return r?wa(r):void 0}function ka(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=uo(e,()=>Re(new ee(ao(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function va(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function po(t){let e=V(t),n=new it(e);if(!H(n.path))return[];let r=uo(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:va(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Sa(t){return Kr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function Ea(t){return $r(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:O(`Last try not sent: ${e.error}`)}:{}}))}function _a(t){let e=Object.entries(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(Mn(kt(T(ao(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function $a(t){let e=dr(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:eo({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:lr(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=so.get(e);return!n&&!Dn(e)?null:(n||so.set(e,n=new Cn(e)),n)}var so=new WeakMap;function Wp(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=nt({quiet:!0});if(!e||!ro(e))return null;let n=io.get(e);return n||io.set(e,n=new Ne(e)),n}var io=new WeakMap;function Ta(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var go={card:ga,schedule:fa,agent:_a,memory:ha,wiki:ya,fact:()=>[],question:po,whatsapp:Sa,email:Ea,content:$a,request:Ta};function Aa(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function mo(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??lo){if(d==="fact"){try{let c=ka(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=go[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Aa),{items:o,snoozed:a,errors:s,backlog:i}}function fo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!lo.includes(n)||!r?null:{kind:n,ref:r}}function Ra(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return yr(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 cr(t.root,n)?.status==="pending";default:return!!ho(t,e,n)}}function ho(t,e,n){return e==="fact"?xa(t,n):go[e](t).find(r=>r.key===`${e}:${n}`)}async function bo(t,e,n,r={}){let o=n==="later"?null:fo(e),s;if(o)try{s=ho(t,o.kind,o.ref)}catch{s=void 0}let i=await Ia(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Fn(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ia(t,e,n,r){let o=fo(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),d=r.by??"operator";if(n==="later"){if(!Ra(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return Ur(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Vn(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?ir:ar)(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=>{Yn(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(!co(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?xr(c,i,{by:d,force:r.force,now:a}):kr(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Da(t,e,i,l,d,r);case"question":return Na(t,e,i,l,d,r);case"whatsapp":{let c=await Gr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Ar(Oe(t),xt(t)),p=await Tr(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??to({config:Oe(t),env:xt(t)}),p=await ur(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?jr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a),{ok:!0,message:`${e}: dropped`})}}}function Da(t,e,n,r,o,s){let i=new 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 er(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=Zn(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Ca(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function Na(t,e,n,r,o,s){let i=V(t),a=new it(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Xn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=po(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Ca(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new 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 Oa=3,La=7,Pa=50,St=120,Ma=280,vt=600,wo=36e5,Fa=24*wo;function qp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Le=t=>new Date(t).toISOString();function Ua(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:ne(e.title,St),...e.ask?{ask:ne(e.ask,vt)}:{},...e.detail?{facts:ne(e.detail,Ma)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var Wa={done:"Done",declined:"Declined",dropped:"Dropped"};function xo(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??Oa)*wo;return{...i,column:a||d?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Le(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Wa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ja(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function Ba(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:ja(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,yo=(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(Ua(o,s,o.node===t.node))}let r=ko(t,e);for(let o of t.requests??[]){let s=xo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function ko(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Hp(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=ko(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=xo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??La)*Fa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(Ba(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Pa),c=yo(n,"askedAt"),p=yo(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 qa(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Ha(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function Kp(t,e){let n=t.now??Date.now(),r=[],o=mo(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(qa)}],requests:a,deferred:i});return Ha(d,i.size,[...r,...l])}import{readFileSync as Va}from"fs";var Xa=1e4,vo=/^[0-9a-f]{7,64}$/i;function Jp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&vo.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(Xa)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&vo.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Qp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Va(n.tokenFile,"utf-8").trim().split(`
|
|
68
|
+
`)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var Pe=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function eg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/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 tg(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function ng(t){return Pe.has(t)}function rg(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 og(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 sg(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 ig(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let r of t.mesh?.peers||[])r.token&&n.add(r.token);return n}function ag(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function Me(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function za(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ka(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function cg(t,e=Ka()){let n=Me(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=za(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 dg(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var _t="/api/admin/pictures",Ga=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ya=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function Ja(t){let e={agent:{},person:{}};for(let n of pr)for(let[r,o]of Object.entries(fr(t,n)))e[n][r]=hr(n,r,o);return e}function gg(t,e,n,r,o){let s=n.match(Ga);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=br(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":gr,"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 mg(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,{...Ja(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Ya);if(!s)return _(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return _(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return _(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!mr.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 fg(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 So={};function yg(t){So=t}function wg(){return So}var xg=`<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>
|
|
72
72
|
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap" rel="stylesheet">
|
|
73
|
-
<script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,
|
|
73
|
+
<script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,kg=`
|
|
74
74
|
.ax-topbar{display:flex;align-items:center;justify-content:space-between;
|
|
75
75
|
padding:8px 18px;border-bottom:1px solid var(--ax-border);
|
|
76
76
|
background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}
|
|
@@ -151,7 +151,7 @@ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as kr,O as Ar,k as K}from"./ch
|
|
|
151
151
|
background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);
|
|
152
152
|
flex-wrap:wrap}
|
|
153
153
|
.ax-subheader > * {flex-shrink:0}
|
|
154
|
-
.ax-subheader .spacer{flex:1}`,
|
|
154
|
+
.ax-subheader .spacer{flex:1}`,vg=`<script>
|
|
155
155
|
(function(){
|
|
156
156
|
function wireTheme(){
|
|
157
157
|
var sw = document.querySelectorAll('[data-theme-opt]');
|
|
@@ -346,7 +346,7 @@ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as kr,O as Ar,k as K}from"./ch
|
|
|
346
346
|
document.addEventListener('DOMContentLoaded', wire);
|
|
347
347
|
} else { wire(); }
|
|
348
348
|
})();
|
|
349
|
-
</script>`;function
|
|
349
|
+
</script>`;function Sg(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var Qa='<span class="ax-build" hidden></span>';function Eg(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(l=>l.primary)?.id||e[0].id,r=e.find(l=>l.id===n)||e[0],o=e.map(l=>{let c=l.id===n,p=l.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",u=!!l.tokenScope&&!l.primary,g=u?"#":l.dashboardUrl?`${l.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",m=u?` data-peer-id="${j(l.id)}" data-peer-action="proxy"`:l.primary?' data-peer-id="primary" data-peer-action="proxy"':"",f=u?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':l.tokenScope?`<div class="url">${j(l.tokenScope)}</div>`:l.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${j(g)}" class="${c?"is-current":""}"${m}>
|
|
350
350
|
<div class="row"><span class="dot"></span><span>${j(l.name)}${p}</span></div>
|
|
351
351
|
${l.dashboardUrl?`<div class="url">${j(l.dashboardUrl)}</div>`:""}
|
|
352
352
|
${f}
|
|
@@ -355,7 +355,7 @@ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as kr,O as Ar,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:Kn},{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>
|
|
@@ -373,7 +373,7 @@ import{a as mt}from"./chunk-GTJIKXDB.js";import{H as kr,O as Ar,k as K}from"./ch
|
|
|
373
373
|
<button data-theme-opt="light">Light</button>
|
|
374
374
|
</div>
|
|
375
375
|
</div>
|
|
376
|
-
</header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}import{existsSync as Ko,mkdirSync as Tl,readFileSync as Al,renameSync as Rl,writeFileSync as Il}from"fs";import{homedir as Dl}from"os";import{dirname as Cl,join as Nl}from"path";import{execFile as cl,execFileSync as dl}from"child_process";import{execFileSync as Za}from"child_process";import{existsSync as _o,mkdirSync as el,readdirSync as tl,readFileSync as $o,renameSync as nl,writeFileSync as rl}from"fs";import{homedir as To}from"os";import{join as
|
|
376
|
+
</header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}import{existsSync as Ko,mkdirSync as Tl,readFileSync as Al,renameSync as Rl,writeFileSync as Il}from"fs";import{homedir as Dl}from"os";import{dirname as Cl,join as Nl}from"path";import{execFile as cl,execFileSync as dl}from"child_process";import{execFileSync as Za}from"child_process";import{existsSync as _o,mkdirSync as el,readdirSync as tl,readFileSync as $o,renameSync as nl,writeFileSync as rl}from"fs";import{homedir as To}from"os";import{join as Tt}from"path";var P="siri:",Ao="com.apple.ttsbundle.gryphon-neural_",Ro=t=>!!t&&t.startsWith(Ao),ol=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],sl=()=>{try{return Za("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},$t;function At(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&$t!==void 0)return $t;let{platform:n=process.platform,exists:r=_o,prefDomain:o=sl}=t,s=n==="darwin"&&ol.every(i=>r(i))&&o();return e||($t=s),s}var Io=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Do={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},Rt=t=>Do[t.toLowerCase()]??null;function Fe(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var il=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function al(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(il)){let i=`${r}-${o}`,a=`${Ao}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:Do[s]??null,siri:!0})}return[...e.values()]}function Ue(t=Io,e={}){if(!At(e))return[];let n=[];for(let r of t){let o;try{o=tl(r)}catch{continue}for(let s of o)try{n.push($o(Tt(r,s,"Info.plist"),"latin1"))}catch{}}return al(n)}var Eo=`#!/bin/sh
|
|
377
377
|
# Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
|
|
378
378
|
# siri-say.sh [voice] < text speak one line. A Siri voice id switches
|
|
379
379
|
# the OS default for it; any other id is
|
|
@@ -478,20 +478,20 @@ wait "$say_pid"
|
|
|
478
478
|
status=$?
|
|
479
479
|
say_pid=
|
|
480
480
|
finish $status
|
|
481
|
-
`,ll=(t=To())
|
|
481
|
+
`,ll=(t=To())=>Tt(t,".agentx","voice","siri-say.sh");function Co(t=To()){let e=ll(t);return _o(e)&&$o(e,"utf8")===Eo||(el(Tt(t,".agentx","voice"),{recursive:!0}),rl(`${e}.tmp`,Eo,{mode:493}),nl(`${e}.tmp`,e)),e}var No=`ObjC.import("AVFoundation")
|
|
482
482
|
const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
|
|
483
483
|
for (let i = 0; i < vs.count; i++) {
|
|
484
484
|
const v = vs.objectAtIndex(i)
|
|
485
485
|
out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
|
|
486
486
|
}
|
|
487
487
|
out.join("\\n")`,ul=new Set(["Fred","Kathy","Ralph","Junior"]),pl={Flo:"female",Sandy:"female",Shelley:"female",Grandma:"female",Kathy:"female",Eddy:"male",Reed:"male",Rocko:"male",Grandpa:"male",Fred:"male",Ralph:"male",Junior:"male"};function Oo(t){let e=[];for(let n of t.split(`
|
|
488
|
-
`)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!ul.has(o)||e.push({id:r,name:o,locale:s,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":pl[o]??null})}return e}var gl=10*60*1e3,
|
|
489
|
-
`)[0]}`),re={at:t,voices:
|
|
490
|
-
`),
|
|
491
|
-
${Xo(o,e.voice.introduce===!0&&!!r)}`}var Ol="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Go=(t=Dl())=>Nl(t,".agentx","voice","health.json");function Ll(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===
|
|
488
|
+
`)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!ul.has(o)||e.push({id:r,name:o,locale:s,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":pl[o]??null})}return e}var gl=10*60*1e3,Ng=60*1e3,re=null,It=!1;function Dt(t=Date.now(),e=gl){if(process.platform!=="darwin")return[];if(re)t-re.at>e&&!It&&(It=!0,cl("osascript",["-l","JavaScript","-e",No],{timeout:1e4},(n,r)=>{It=!1,n||(re={at:Date.now(),voices:[...Oo(String(r)),...Ue()]})}));else try{re={at:t,voices:[...Oo(dl("osascript",["-l","JavaScript","-e",No],{encoding:"utf8",timeout:1e4})),...Ue()]}}catch(n){Ct(`[voice] could not list system voices: ${String(n?.message??n).split(`
|
|
489
|
+
`)[0]}`),re={at:t,voices:Ue()}}return re.voices}var Ct=t=>process.stderr.write(t+`
|
|
490
|
+
`),We=new Set;function Og(t){Ct=t}function Y(t,e){We.has(t)||(We.add(t),Ct(e))}function Mo(t){for(let e of We)t(e)&&We.delete(e)}var Fo=()=>{};function Lg(t){Fo=t}function Uo(t){try{Fo(t)}catch(e){Y("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var ml={premium:3,enhanced:2,standard:1},fl=new Set(["Grandma","Grandpa"]);function Lo(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!fl.has(t.name)?1:0;return ml[t.quality]*10+e}var oe=t=>t.toLowerCase().split(/[-_]/)[0],Po=t=>t.id.startsWith("com.apple.voice.");function Nt(t,e,n,r=new Set){let o=me(t.filter(a=>!a.siri&&oe(a.locale)===oe(e)),e);if(o.some(Po)&&(o=o.filter(Po)),n==="female"||n==="male"){let a=o.filter(d=>d.gender===n);a.length&&(o=a)}if(!o.length)return null;let s=o.filter(a=>a.quality===o[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return s.find(a=>!i.has(a.name.toLowerCase()))??s[0]}function me(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=oe(e),o=t.filter(s=>oe(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Lo(i)-Lo(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function fe(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(l=>l.id===r);if(o)return o;if(r.toLowerCase().startsWith(P)){let l=r.slice(P.length).trim().toLowerCase(),c=me(e.filter(u=>u.siri&&u.name.toLowerCase()===l),n)[0];if(c||!l)return c??null;let p=fe(l,e.filter(u=>oe(u.locale)===oe(n)),n);return p&&Y(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${p.name} (${p.locale}) instead.`),p}e=e.filter(l=>!l.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=me(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function Wo(t,e,n=new Set){let r=new Map;if(!e.length)return r;let o=new Set([...n].map(i=>i.toLowerCase())),s="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",d=a?i.gender:s,l=e.filter(p=>!o.has(p.name.toLowerCase())),c=l.find(p=>p.gender===d)??(a?e.find(p=>p.gender===d):void 0)??l[0]??e[r.size%e.length];r.set(i.id,c),o.add(c.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}$n();var Ot="system",hl=t=>t.trim().toLowerCase()===Ot,bl="21m00Tcm4TlvDq8ikWAM";function Lt(t,e,n={},r=Dt()){let o=e[t],s=o?.name||t,i=o?.voice,a=Mt(e,n,r).get(t)??null,d=kl(t,i?.system,i?.gender,n,r);return{agentId:t,name:s,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?Be(a):null,systemByLanguage:d,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||Sl(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var Be=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function yl(t,e,n,r){if(!e||!n.length)return null;let o=fe(e,n,r);return o||(Y(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Uo(e)),o}function Ho(t,e){let n=t.trim();if(n.toLowerCase().startsWith(P))return{locale:e,gender:Rt(n.slice(P.length).trim())};let r=Fe(n);return r?{locale:r.locale,gender:Rt(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var Vo=t=>t.toLowerCase().split(/[-_]/)[0],jo=(t,e)=>typeof t=="string"?t:t?.[Vo(e)];function je(t,e,n,r){if(e!==void 0)return hl(e)?null:yl(t,e,n,r)??void 0}var Pt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function wl(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=je("voice.system",jo(e.system,o),n,o),d=()=>new Set([...r,...[...s.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let p=jo(c.system,o),u=je(c.id,p,n,o),g=u!==void 0?u:p!==void 0&&n.length?xl(c,p,o,a,n,d()):a!==void 0&&Pt(a,c.gender)?a:void 0;g!==void 0?s.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let l=d();for(let[c,p]of Wo(i,me(n.filter(u=>!u.siri),o),l))s.set(c,p);return s}function xl(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let d=je(`${t.id}.fallbacks`,a,o,n);if(d!==void 0)return d}if(r!==void 0&&Pt(r,t.gender))return r;let i=Ho(e,n);return Nt(o,i.locale,t.gender??i.gender,s)??void 0}function kl(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,d,l)=>{if(!(!d||typeof d=="string"))for(let[c,p]of Object.entries(d)){let u=je(`${a}.${c}`,p,o,c);u===void 0&&o.length&&(u=Nt(o,c,n??Ho(p,c).gender)??void 0),u!==void 0&&l(u)&&(s[Vo(c)]=u)}};return i("voice.system",r.system,a=>Pt(a,n)),i(t,e,()=>!0),s}function Wg(t,e){let n=e?_e(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?Be(r):null}}function Mt(t,e={},n=Dt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return wl(r,e,n)}function Ft(t,e){let n={provider:t.provider,elevenlabs:vl(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([o,s])=>[o,s?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function vl(t,e){return t||e||process.env.AGENTX_VOICE_ID||bl}function Sl(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let o=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[s,...i]=o.split(/,\s*/),a=i.join(", ");return a&&s.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(o)&&o.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${o}.`:`Hello, this is ${t}, ${o}.`}var El=8*60*60*1e3,_l=500,Bo=class{constructor(e=El){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(qo(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=qo(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>_l&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},qo=(t,e)=>`${t}\0${e}`;function Xo(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function jg(t,e,n,r={}){let o=e[t],s=Lt(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:Ft(s),persona:i||`You are ${s.name}.`,introLine:Xo(s,n)}}var $l="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function Bg(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=s=>typeof s=="string"?s.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),o={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${$l}
|
|
491
|
+
${Xo(o,e.voice.introduce===!0&&!!r)}`}var Ol="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Go=(t=Dl())=>Nl(t,".agentx","voice","health.json");function Ll(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Ot)return!0;if(r.toLowerCase().startsWith(P)){let o=r.slice(P.length).trim().toLowerCase();return e.some(s=>s.siri&&s.name.toLowerCase()===o)}return fe(r,e,n)!==null}function Pl(t){let e=t.voice?.locale??"en",n=[],r=(o,s)=>{if(typeof s=="string")n.push({owner:o,name:s,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(s??{}))n.push({owner:o,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[o,s]of Object.entries(t.agents))(s.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(o,s.voice?.system);return n}function Ml(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of Pl(t)){if(Ll(s,e,i))continue;r??=Mt(t.agents,t.voice,e);let d=n.get(s)??{voice:s,agents:[],speaksWith:{}};d.agents.includes(o)||d.agents.push(o);let l=r.get(o);o!=="voice.system"&&!a&&(d.speaksWith[o]=l?Be(l):"the OS default voice"),n.set(s,d)}return[...n.values()]}function Ut(t){let e=Fe(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(P)){let n=t.slice(P.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function Fl(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${Ut(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
|
|
492
492
|
`)}
|
|
493
493
|
Reinstall in ${Ol}. Agents switch back on their own once it is installed.`}}function Ul(t=Go()){if(!Ko(t))return null;try{let e=JSON.parse(Al(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Wl(t,e){Tl(Cl(t),{recursive:!0}),Il(`${t}.tmp`,JSON.stringify(e,null,2)+`
|
|
494
|
-
`),Rl(`${t}.tmp`,t)}var zo=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let o=this.deps.file??Go(),s=new Map((Ul(o)?.missing??[]).map(p=>[p.voice,p])),i=Ml(e,n),a=i.map(p=>({...p,since:s.get(p.voice)?.since??r.toISOString(),...s.get(p.voice)?.notifiedAt?{notifiedAt:s.get(p.voice).notifiedAt}:{}})),d=[...s.keys()].filter(p=>!i.some(u=>u.voice===p));for(let p of d)this.deps.log(`[voice] ${
|
|
494
|
+
`),Rl(`${t}.tmp`,t)}var zo=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let o=this.deps.file??Go(),s=new Map((Ul(o)?.missing??[]).map(p=>[p.voice,p])),i=Ml(e,n),a=i.map(p=>({...p,since:s.get(p.voice)?.since??r.toISOString(),...s.get(p.voice)?.notifiedAt?{notifiedAt:s.get(p.voice).notifiedAt}:{}})),d=[...s.keys()].filter(p=>!i.some(u=>u.voice===p));for(let p of d)this.deps.log(`[voice] ${Ut(p)} is installed again; its agents speak with it again`);d.length&&Mo(p=>d.some(u=>p===u||p.endsWith(`:${u}`)));let l=a.filter(p=>!p.notifiedAt);if(l.length){let{title:p,message:u}=Fl(l);try{await this.deps.notify(p,u);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>Ut(g.voice)).join(", ")} not installed`)}catch(g){this.deps.log(`[voice] could not send the missing-voice notice: ${g?.message??g}`)}}this.missingNow=a.length>0;let c={checkedAt:r.toISOString(),missing:a};return(!Ko(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&Wl(o,c),c}finally{this.running=!1}}};import{randomBytes as Yo}from"crypto";var J={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:W.perMessage},jl=/^[a-f0-9]{32}$/,Bl=/^c[a-z0-9]{8,32}$/,ql=/^#[0-9a-fA-F]{6}$/;function Wt(t){return Bl.test(t)}var Jo=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
|
|
495
495
|
id TEXT PRIMARY KEY, device_id TEXT NOT NULL, title TEXT NOT NULL,
|
|
496
496
|
node TEXT NOT NULL, node_name TEXT NOT NULL, agent TEXT NOT NULL, agent_name TEXT,
|
|
497
497
|
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
|
@@ -504,11 +504,11 @@ Reinstall in ${Ol}. Agents switch back on their own once it is installed.`}}func
|
|
|
504
504
|
id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, message_id INTEGER NOT NULL,
|
|
505
505
|
path TEXT NOT NULL, name TEXT NOT NULL, mime TEXT NOT NULL, kind TEXT NOT NULL, created_at INTEGER NOT NULL);
|
|
506
506
|
CREATE INDEX IF NOT EXISTS app_chat_files_conversation ON app_chat_files(conversation_id);`),e.prepare("PRAGMA table_info(app_chat_messages)").all().some(o=>o.name==="files")||e.exec("ALTER TABLE app_chat_messages ADD COLUMN files TEXT");let r=e.prepare("PRAGMA table_info(app_chat_conversations)").all();r.some(o=>o.name==="read_at")||e.transaction(()=>{e.prepare("PRAGMA table_info(app_chat_conversations)").all().some(s=>s.name==="read_at")||(e.exec("ALTER TABLE app_chat_conversations ADD COLUMN read_at INTEGER"),e.exec("UPDATE app_chat_conversations SET read_at = updated_at"))}).immediate(),r.some(o=>o.name==="color")||e.exec("ALTER TABLE app_chat_conversations ADD COLUMN color TEXT"),e.exec(`CREATE TABLE IF NOT EXISTS app_chat_delivered (
|
|
507
|
-
key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return
|
|
508
|
-
(id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!
|
|
507
|
+
key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Wt(e)?this.db.prepare("SELECT device_id FROM app_chat_conversations WHERE id = ?").get(e)?.device_id??null:null}appendOnce(e,n,r,o,s=[],i=Date.now()){return!r||r.length>200?null:this.db.transaction(()=>!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e)||this.db.prepare("INSERT OR IGNORE INTO app_chat_delivered (key, conversation_id, at) VALUES (?, ?, ?)").run(r,n,i).changes===0?null:(this.db.prepare("DELETE FROM app_chat_delivered WHERE at < ?").run(i-30*24*60*6e4),this.appendWithFiles(e,n,o,s))).immediate()}create(e,n,r,o=Date.now()){let s=`c${o.toString(36)}${Yo(4).toString("hex")}`,{color:i,...a}=n,d=i&&ql.test(i)?i:void 0,l={id:s,title:Zo(r),...a,...d?{color:d}:{},createdAt:o,updatedAt:o,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
|
|
508
|
+
(id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!Wt(n))return null;let r=this.db.prepare("SELECT * FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e);if(!r)return null;let o=this.db.prepare("SELECT * FROM app_chat_messages WHERE conversation_id = ? ORDER BY id").all(n).map(Hl);return{...Qo(r),messages:o}}list(e,n=J.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
|
|
509
509
|
(SELECT COUNT(*) FROM app_chat_messages m WHERE m.conversation_id = c.id) AS n,
|
|
510
510
|
(SELECT substr(m.content, 1, 240) FROM app_chat_messages m WHERE m.conversation_id = c.id ORDER BY m.id DESC LIMIT 1) AS last
|
|
511
|
-
FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...Qo(o),messages:o.n,...s?{last:s}:{}}})}markRead(e,n,r=Date.now()){
|
|
511
|
+
FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...Qo(o),messages:o.n,...s?{last:s}:{}}})}markRead(e,n,r=Date.now()){Wt(n)&&this.db.prepare("UPDATE app_chat_conversations SET read_at = MAX(COALESCE(read_at, 0), ?) WHERE id = ? AND device_id = ?").run(r,n,e)}latestWith(e,n){let r=this.db.prepare(`SELECT id, device_id FROM app_chat_conversations WHERE node = ? AND agent = ?
|
|
512
512
|
ORDER BY updated_at DESC, rowid DESC LIMIT 1`).get(e,n);return r?{id:r.id,deviceId:r.device_id}:null}latestDevice(){return this.db.prepare("SELECT device_id FROM app_chat_conversations ORDER BY updated_at DESC, rowid DESC LIMIT 1").get()?.device_id??null}unread(e,n){return this.db.prepare(`SELECT c.id, c.title, c.agent, c.agent_name, c.color,
|
|
513
513
|
substr(m.content, 1, 240) AS answer, m.status, m.at
|
|
514
514
|
FROM app_chat_conversations c
|
|
@@ -522,16 +522,16 @@ Reinstall in ${Ol}. Agents switch back on their own once it is installed.`}}func
|
|
|
522
522
|
(SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,J.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
|
|
523
523
|
(SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!jl.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
|
|
524
524
|
JOIN app_chat_conversations c ON c.id = f.conversation_id WHERE f.id = ? AND c.device_id = ?`).get(n,e);return r?{id:r.id,name:r.name,mime:r.mime,kind:r.kind,path:r.path,conversationId:r.conversation_id,node:r.node,agent:r.agent}:null}pruneDevice(e){let n=this.db.prepare(`SELECT id FROM app_chat_conversations WHERE device_id = ?
|
|
525
|
-
ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,J.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function Qo(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function Hl(t){let e=s=>{if(s)try{return JSON.parse(s)}catch{return}},n=e(t.ui),r=e(t.tools),o=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...o?{files:o}:{}}}function Zo(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return Zo(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as
|
|
525
|
+
ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,J.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function Qo(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function Hl(t){let e=s=>{if(s)try{return JSON.parse(s)}catch{return}},n=e(t.ui),r=e(t.tools),o=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...o?{files:o}:{}}}function Zo(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return Zo(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as Bt,writeFileSync as ss,existsSync as qt,readdirSync as ec,statSync as tc}from"fs";import{resolve as Ht,join as nc}from"path";import{existsSync as es,mkdirSync as Vl,readFileSync as Xl,writeFileSync as ts}from"fs";import{dirname as zl,resolve as ns}from"path";import{z as v}from"zod";var Kl=v.object({type:v.enum(["gitlab","github"]),host:v.string().optional(),project:v.string(),iid:v.number().int().positive(),url:v.string()}),Gl=v.object({id:v.string(),title:v.string(),description:v.string().optional(),assignee:v.string().optional(),labels:v.array(v.string()).default([]),milestone:v.string().optional(),status:v.enum(["todo","doing","blocked","done"]).default("todo"),priority:v.number().int().optional(),estimatedSeconds:v.number().int().optional(),source:Kl.optional(),importedAt:v.string().optional(),createdAt:v.string(),updatedAt:v.string(),blocker:v.string().optional(),doneNote:v.string().optional()}),Yl=v.object({version:v.literal(1),items:v.array(Gl).default([])}),qe=class{constructor(e){this.path=e}jsonPath(){return ns(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return ns(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return es(this.jsonPath())}load(){let e=this.jsonPath();if(!es(e))return{version:1,items:[]};let n=Xl(e,"utf-8");try{return Yl.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Vl(zl(n),{recursive:!0}),ts(n,JSON.stringify(e,null,2)+`
|
|
526
526
|
`),ts(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.items.some(s=>s.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),o={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(o),this.save(n),o}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),o=new Date().toISOString(),s=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??o,updatedAt:o};n.items.push(a),s.push(a),r.add(a.id)}return s.length&&this.save(n),s}update(e,n){let r=this.load(),o=r.items.findIndex(i=>i.id===e);if(o<0)throw new Error(`backlog item ${e} not found`);let s={...r.items[o],...n,id:r.items[o].id,createdAt:r.items[o].createdAt,updatedAt:new Date().toISOString()};return r.items[o]=s,this.save(r),s}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(o=>o.id!==e),n.items.length===r?!1:(this.save(n),!0)}toMarkdown(e){let n=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let s of e.items)r[s.status].push(s);let o=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[s,i]of o)if(r[s].length){n.push(`## ${i}`,"");for(let a of r[s]){let d=s==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",p=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${d}] ${l}${a.title}${c}${p}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
|
|
527
|
-
`)}};function
|
|
528
|
-
`):[]}writeMd(e){let n=
|
|
529
|
-
`))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match(
|
|
530
|
-
`);for(let i=0;i<s.length;i++){let a=s[i].match(
|
|
527
|
+
`)}};function rm(t){return`${t.type}:${t.project}:${t.iid}`}function rs(t,e,n){let r=[];if(e.type==="gitlab"){let o=n.channels.gitlab?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(s)}}else if(e.type==="github"){let o=n.channels.github?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(s)}}return r}async function jt(t,e,n,r=()=>{}){return t.source?Jl(t.source,e,n,r):{ok:!0,attempts:[]}}async function Jl(t,e,n,r=()=>{}){return t.type==="gitlab"?Ql(t,e,n,r):t.type==="github"?Zl(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Ql(t,e,n,r){let o=n.channels.gitlab,s=o?.token,i=o?.host||(t.host?`https://${t.host}`:void 0);if(!s||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],d=async(g,m={})=>fetch(`${i}/api/v4${g}`,{...m,headers:{"PRIVATE-TOKEN":s,"Content-Type":"application/json",...m.headers||{}}}),l=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async m=>{try{let f=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":s}});if(!f.ok)return null;let w=await f.json();return Array.isArray(w)&&w[0]?.id?w[0].id:null}catch{return null}}))).filter(m=>typeof m=="number"));let p;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")p=0;else try{let g=await d(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let m=await g.json();Array.isArray(m)&&m[0]?.id&&(p=m[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.description=e.description),e.labels!==void 0&&(u.labels=e.labels.join(",")),e.addLabels?.length&&(u.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(u.remove_labels=e.removeLabels.join(",")),c!==void 0&&(u.assignee_ids=c),p!==void 0&&(u.milestone_id=p),e.state&&(u.state_event=e.state==="closed"?"close":"reopen"),Object.keys(u).length)try{let g=await d(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(u)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let m=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${m.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await d(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function Zl(t,e,n,r){let s=n.channels.github?.token;if(!s)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(u,g={})=>fetch(`https://api.github.com${u}`,{...g,headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),d=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let u=await a(`/repos/${d}/milestones?state=all&per_page=100`);if(u.ok){let g=await u.json(),m=Array.isArray(g)?g.find(f=>f.title===e.milestoneTitle):null;m?.number&&(l=m.number)}}catch(u){r(`[backlog-sync] github milestone lookup failed: ${u.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let u=await a(`/repos/${d}/issues/${t.iid}`);if(u.ok){let g=await u.json(),m=Array.isArray(g.labels)?g.labels.map(w=>typeof w=="string"?w:w.name):[],f=new Set([...m,...e.addLabels??[]]);for(let w of e.removeLabels??[])f.delete(w);c=[...f]}}catch(u){r(`[backlog-sync] github label fetch failed: ${u.message}`)}if(c===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.body=e.description),c!==void 0&&(p.labels=c),e.assigneeUsernames!==void 0&&(p.assignees=e.assigneeUsernames),l!==void 0&&(p.milestone=l),e.state&&(p.state=e.state),Object.keys(p).length)try{let u=await a(`/repos/${d}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(p)});if(i.push({kind:"PATCH issue",ok:u.ok,status:u.status}),!u.ok){let g=await u.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${u.status}: ${g.slice(0,200)}`,url:t.url}}}catch(u){return i.push({kind:"PATCH issue",ok:!1,error:u.message}),{ok:!1,attempts:i,error:u.message,url:t.url}}if(e.note)try{let u=await a(`/repos/${d}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:u.ok,status:u.status})}catch(u){i.push({kind:"POST comment",ok:!1,error:u.message})}return{ok:i.every(u=>u.ok),attempts:i,url:t.url}}var Vt=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,He=/@([a-z0-9_-]+)/i,os=/\[time:\s*([0-9hm\s]+)\]/i;function rc(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var Xt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new qe(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=Ht(process.cwd(),this.path);return qt(e)?Bt(e,"utf-8").split(`
|
|
528
|
+
`):[]}writeMd(e){let n=Ht(process.cwd(),this.path);ss(n,e.join(`
|
|
529
|
+
`))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match(Vt);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],d=a.match(He);if(d&&d[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(os),c=a.replace(He,"").replace(os,"").trim();r.push({id:`backlog:${o}`,title:c||`Task at line ${o+1}`,assignee:d?d[1]:void 0,estimatedSeconds:l?rc(l[1]):void 0,priority:o})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let o=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(o.source&&this.daemon){let s=rs([o.assignee||e],o.source,this.daemon);jt(o,{assigneeUsernames:s,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let d=this.store.update(e,a);if(d.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&jt(d,l,this.daemon,this.log).catch(c=>this.log(`[backlog-sync] report failed for ${e}: ${c?.message??c}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),o=this.readMd(),s=o[r];if(!s)throw new Error(`backlog line ${r} missing`);if(!s.match(Vt))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){o[r]=s.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";o.splice(r+1,0,a)}else n.status==="blocked"?o.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&o.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(o)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},zt=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(qt(e))for(let r of ec(e)){let o=nc(e,r);tc(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(Ht(process.cwd(),this.root),n);let r=[];for(let o of n){let s=Bt(o,"utf-8").split(`
|
|
530
|
+
`);for(let i=0;i<s.length;i++){let a=s[i].match(Vt);if(!a||a[2].toLowerCase()==="x")continue;let d=a[3].match(He);!d||d[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace(He,"").trim(),assignee:d[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),o=parseInt(r[r.length-1],10),s=r.slice(1,-1).join(":");if(!qt(s))return;let i=Bt(s,"utf-8").split(`
|
|
531
531
|
`);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),ss(s,i.join(`
|
|
532
|
-
`)))}},zt=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),d=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function lm(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Vt(r.path,e,n);case"wiki":return new Xt(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new zt(o.host,o.token,i,s,n)}}}Ze();var Kt="unmapped";function Gt(t,e=[]){if(!t)return Kt;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function oc(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of le(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Gt(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function sc(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function um(t,e){let n=sc(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Gt(t.project,e.projects);if(t.agentId){let r=oc(e).get(t.agentId);if(r)return r}return Kt}function pm(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var ic=t=>t===Kt?"internal":"client";function ac(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??ic(t),respondWithinMinutes:lc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function gm(t){let e=new Set;for(let n of t.projects??[])e.add(Gt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>ac(n,t))}function lc(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as cc}from"crypto";var hm={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},dc=40,uc=20,bm=90,pc=2e3,is=36e5;function gc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
|
|
533
|
-
${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<dc?null:`text:${cc("sha256").update(r).digest("hex").slice(0,24)}`}function
|
|
534
|
-
`);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function
|
|
532
|
+
`)))}},Kt=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),d=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function dm(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Xt(r.path,e,n);case"wiki":return new zt(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new Kt(o.host,o.token,i,s,n)}}}et();var Gt="unmapped";function Yt(t,e=[]){if(!t)return Gt;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function oc(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of le(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Yt(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function sc(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function gm(t,e){let n=sc(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Yt(t.project,e.projects);if(t.agentId){let r=oc(e).get(t.agentId);if(r)return r}return Gt}function mm(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var ic=t=>t===Gt?"internal":"client";function ac(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??ic(t),respondWithinMinutes:lc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function fm(t){let e=new Set;for(let n of t.projects??[])e.add(Yt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>ac(n,t))}function lc(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as cc}from"crypto";var ym={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},dc=40,uc=20,wm=90,pc=2e3,is=36e5;function gc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
|
|
533
|
+
${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<dc?null:`text:${cc("sha256").update(r).digest("hex").slice(0,24)}`}function xm(t){let e=t.indexOf(`
|
|
534
|
+
`);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function Jt(t){t.exec(`
|
|
535
535
|
CREATE TABLE IF NOT EXISTS owner_told (
|
|
536
536
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
537
537
|
at INTEGER NOT NULL,
|
|
@@ -549,15 +549,15 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<dc?null:`text:${c
|
|
|
549
549
|
CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
|
|
550
550
|
CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
|
|
551
551
|
CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
|
|
552
|
-
`);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of mc)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(o){if(!/duplicate column/i.test(String(o?.message)))throw o}}var mc=[["urgent","INTEGER NOT NULL DEFAULT 0"],["seen_at","INTEGER"],["seen_via","TEXT"],["answered_at","INTEGER"],["answered_via","TEXT"],["escalated_at","INTEGER"],["escalation_of","INTEGER"]];function
|
|
553
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,pc),e.outcome,e.urgent?1:0,e.escalationOf??null).lastInsertRowid)}get(e){let n=this.db.prepare("SELECT * FROM owner_told WHERE id = ?").get(e);return n?
|
|
552
|
+
`);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of mc)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(o){if(!/duplicate column/i.test(String(o?.message)))throw o}}var mc=[["urgent","INTEGER NOT NULL DEFAULT 0"],["seen_at","INTEGER"],["seen_via","TEXT"],["answered_at","INTEGER"],["answered_via","TEXT"],["escalated_at","INTEGER"],["escalation_of","INTEGER"]];function Ve(t){return{id:t.id,at:t.at,key:t.item_key,requestId:t.request_id??null,kind:t.kind,channel:t.channel,chatId:t.chat_id,from:t.sender??null,title:t.title,text:t.text,outcome:t.outcome,digestedAt:t.digested_at??null,urgent:t.urgent===1,seenAt:t.seen_at??null,seenVia:t.seen_via??null,answeredAt:t.answered_at??null,answeredVia:t.answered_via??null,escalatedAt:t.escalated_at??null,escalationOf:t.escalation_of??null,state:t.answered_at!=null?"answered":t.seen_at!=null?"seen":"sent"}}var as=class{constructor(e){this.db=e;Jt(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
|
|
553
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,pc),e.outcome,e.urgent?1:0,e.escalationOf??null).lastInsertRowid)}get(e){let n=this.db.prepare("SELECT * FROM owner_told WHERE id = ?").get(e);return n?Ve(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let o=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return o?Ve(o):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(Ve)}waitingCount(){return this.db.prepare("SELECT COUNT(*) AS n FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL").get().n}markDigested(e,n){let r=this.db.prepare("UPDATE owner_told SET digested_at = ? WHERE id = ?");this.db.transaction(()=>{for(let o of e)r.run(n,o)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(Ve)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
|
|
554
554
|
SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
|
|
555
555
|
SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
|
|
556
|
-
FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},ls=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),o=this.now(),s=gc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,uc):r.repeatWindowHours)*is,d=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,d)?l="repeat":!n.urgent&&i==="nag"&&d&&(l="digest");let c=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:s,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:fc(e),ids:e.map(n=>n.id)}:null}markDigested(e){this.ledger.markDigested(e,this.now())}report(e,n=50){return{counts:this.ledger.counts(e),landed:this.ledger.states(e),waitingForDigest:this.ledger.waitingCount(),items:this.ledger.since(e,n)}}prune(e){return this.ledger.prune(this.now()-e*24*is)}};function
|
|
556
|
+
FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},ls=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),o=this.now(),s=gc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,uc):r.repeatWindowHours)*is,d=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,d)?l="repeat":!n.urgent&&i==="nag"&&d&&(l="digest");let c=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:s,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:fc(e),ids:e.map(n=>n.id)}:null}markDigested(e){this.ledger.markDigested(e,this.now())}report(e,n=50){return{counts:this.ledger.counts(e),landed:this.ledger.states(e),waitingForDigest:this.ledger.waitingCount(),items:this.ledger.since(e,n)}}prune(e){return this.ledger.prune(this.now()-e*24*is)}};function km(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,o=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,s=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...o?{kind:o}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...s?{from:s}:{}}}function fc(t,e=5,n=3){let r=new Map;for(let a of t){let[d,...l]=a.title.split(": "),c=l.join(": ").trim(),p=r.get(d.trim())??{count:0,names:[]};p.count++,c&&!p.names.includes(c)&&p.names.push(c),r.set(d.trim(),p)}let o=[...r.entries()].sort((a,d)=>d[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:d,names:l}])=>{let c=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${d>1?` \xD7${d}`:""}${c}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}var hc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,bc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Xe(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(bc)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],o=yc(r);if(!o)return{cleanText:t};let s=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,s)+i+t.slice(s+n[0].length)).trim(),ui:o}}function Sm(t){if(!t||!t.includes("agentx:ui"))return t;let e=hc.exec(t);return e?t.slice(0,e.index).trimEnd():t}function yc(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],o=[],s=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?o.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&s.push(i.label));r.length&&(n.buttons=r),o.length&&(n.replies=o),s.length&&(n.skippedActions=s)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,o=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(o)&&o.filter(s=>typeof s=="string").length>=2&&(n.poll={question:r,options:o.filter(s=>typeof s=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:o,caption:s}=e.media;["image","document","audio","video"].includes(r)&&typeof o=="string"&&o&&(n.media={type:r,url:o,...typeof s=="string"?{caption:s}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function _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 wc=5*6e4;function X(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var cs=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,n=[],r=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(n.map(X)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${X(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let o=r.filter(s=>s.expiresAt>e);o.length===0?this.pending.delete(n):o.length!==r.length&&this.pending.set(n,o)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let o={callId:e,recipient:n,sink:r};this.subs.add(o);let s=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${s}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let d=Date.now(),l=a.filter(c=>c.expiresAt>d);for(let{signal:c}of l)this.deliverTo(o,c);this.pending.delete(i),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(o),this.log(`unsubscribe[${s}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
|
|
557
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+wc),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=X(e.to);for(let o of this.subs)o.callId===e.callId&&X(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as xc,readFileSync as ds,renameSync as kc,rmSync as vc,writeFileSync as Sc}from"fs";import{homedir as Ec}from"os";import{dirname as _c,join as $c}from"path";var us=$c(Ec(),".agentx","call.json");function Tc(t=us,e=Date.now()){try{let n=JSON.parse(ds(t,"utf-8"));if(n?.active===!0&&!(n.until&&Date.parse(n.until)<=e))return{active:!0,mode:"call",reason:`in a call${n.reason?`: ${n.reason}`:""}`}}catch{}return{active:!1,mode:null,reason:"not in a call"}}function ps(t=
|
|
560
|
-
`),kc(s,n)}var gs="owner",
|
|
559
|
+
`):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=X(e.to);if(n===X(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&X(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(X(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+wc),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=X(e.to);for(let o of this.subs)o.callId===e.callId&&X(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as xc,readFileSync as ds,renameSync as kc,rmSync as vc,writeFileSync as Sc}from"fs";import{homedir as Ec}from"os";import{dirname as _c,join as $c}from"path";var us=$c(Ec(),".agentx","call.json");function Tc(t=us,e=Date.now()){try{let n=JSON.parse(ds(t,"utf-8"));if(n?.active===!0&&!(n.until&&Date.parse(n.until)<=e))return{active:!0,mode:"call",reason:`in a call${n.reason?`: ${n.reason}`:""}`}}catch{}return{active:!1,mode:null,reason:"not in a call"}}function ps(t=tr,e=Tc){let n=t();return n.active?n:e()}function Dm(t,e,n=us,r=Date.now()){let o=null;try{o=JSON.parse(ds(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&vc(n,{force:!0});return}xc(_c(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;Sc(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
|
|
560
|
+
`),kc(s,n)}var gs="owner",ze=6e4,ys=60*ze,Ac=24*ys,Rc=7*24*ys,Ic=2*ze,Om={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Dc(t){t.exec(`
|
|
561
561
|
CREATE TABLE IF NOT EXISTS owner_presence (
|
|
562
562
|
person TEXT NOT NULL,
|
|
563
563
|
surface TEXT NOT NULL,
|
|
@@ -566,17 +566,17 @@ data: ${JSON.stringify(n)}
|
|
|
566
566
|
);
|
|
567
567
|
`)}var ms=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;Dc(e)}written=new Map;touch(e,n=gs){let r=this.now(),o=`${n}
|
|
568
568
|
${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this.db.prepare(`INSERT INTO owner_presence (person, surface, at) VALUES (?, ?, ?)
|
|
569
|
-
ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=gs){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function
|
|
569
|
+
ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=gs){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function Lm(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var fs=class{constructor(e,n=Date.now){this.db=e;this.now=n;Jt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
|
|
570
570
|
WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
|
|
571
571
|
ORDER BY at DESC LIMIT 500`).all(this.now()-Rc)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,o=>this.answered(o,n,r),r)}seenPush(e,n="phone"){let r=[],o=this.db.prepare("SELECT id, title FROM owner_told WHERE channel = 'push' AND outcome IN ('sent', 'held') AND at BETWEEN ? AND ? ORDER BY at DESC");for(let s of e){let i=s.title.endsWith("\u2026")?s.title.slice(0,-1):s.title,d=o.all(s.at-Ic,s.at).find(l=>l.title===s.title||i!==s.title&&l.title.startsWith(i));d&&r.push(d.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
|
|
572
572
|
WHERE seen_at IS NULL AND (${hs(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
|
|
573
|
-
WHERE answered_at IS NULL AND (${hs(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let o=new Set(e.filter(Boolean));if(!o.size)return 0;let s=this.openRequestRows().filter(i=>o.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(s)}};function hs(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function
|
|
573
|
+
WHERE answered_at IS NULL AND (${hs(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let o=new Set(e.filter(Boolean));if(!o.size)return 0;let s=this.openRequestRows().filter(i=>o.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(s)}};function hs(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function Pm(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(s=>`${s}:default`),...e.addresses],o=[];for(let s of r){let i=s.trim(),a=he(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function he(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function Cc(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function Nc(t){return he(t)==="push"?["phone","desk"]:[t]}function Mm(t,e,n){let r=t.filter(s=>n(he(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>Nc(s).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!o||i>o.at)&&(o={stop:s,at:i})}return o?.stop??r[0]}function Oc(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(s=>s!==e&&n(he(s)))??null}var Lc=3;async function Fm(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*ze,i=e.prepare(`SELECT id FROM owner_told
|
|
574
574
|
WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
|
|
575
575
|
AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
|
|
576
576
|
AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
|
|
577
|
-
ORDER BY at LIMIT 20`).all(Math.max(o-Lc*s,o-Ac),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),d=0;for(let{id:l}of i){if(a.run(o,l).changes!==1)continue;let c=n.get(l);if(!c)continue;let p=`${c.channel}:${c.chatId}`,u=Oc(t.stops,p,t.up);if(!u){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${p}; no other address to try`);continue}let g=Math.round((o-c.at)/
|
|
577
|
+
ORDER BY at LIMIT 20`).all(Math.max(o-Lc*s,o-Ac),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),d=0;for(let{id:l}of i){if(a.run(o,l).changes!==1)continue;let c=n.get(l);if(!c)continue;let p=`${c.channel}:${c.chatId}`,u=Oc(t.stops,p,t.up);if(!u){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${p}; no other address to try`);continue}let g=Math.round((o-c.at)/ze),m=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,f=`${c.text?`${c.text}
|
|
578
578
|
|
|
579
|
-
`:""}(Sent again here: ${m}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:Cc(u),from:c.from,title:c.title,text:f,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,f),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${m}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var bs=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};function Pc(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function Fm(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function Mc(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,S=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[S]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,S)=>'<option value="'+r(h)+'">'+r(S)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(S=>!p[S.ref]).map(S=>i(S.ref,S.name)).join(""),m=g(l.agents),f=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(m||f?(m?'<optgroup label="Agents">'+m+"</optgroup>":"")+(f?'<optgroup label="People">'+f+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(m||f?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,S)=>{if(h.kind!=="agent")return"";let Je=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+S+'">Start <input type="time" id="oe-start-'+S+'" value="'+r(Je.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+S+'">End <input type="time" id="oe-end-'+S+'" value="'+r(Je.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Se=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+S+'" value="'+Se[0]+'"'+(Je.days.indexOf(Se[0])>=0?" checked":"")+' aria-label="'+Se[2]+'">'+Se[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,S)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+S+'"><span class="org-kind">Role</span><input id="oe-role-'+S+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&section=agents&under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,S)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,D=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',ae=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),ve=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+ae+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+ae+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+D+ve+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function Um(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?Pc(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>Mc(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var Wm=`
|
|
579
|
+
`:""}(Sent again here: ${m}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:Cc(u),from:c.from,title:c.title,text:f,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,f),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${m}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var bs=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};function Pc(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function Wm(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function Mc(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,S=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[S]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,S)=>'<option value="'+r(h)+'">'+r(S)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(S=>!p[S.ref]).map(S=>i(S.ref,S.name)).join(""),m=g(l.agents),f=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(m||f?(m?'<optgroup label="Agents">'+m+"</optgroup>":"")+(f?'<optgroup label="People">'+f+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(m||f?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,S)=>{if(h.kind!=="agent")return"";let Qe=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+S+'">Start <input type="time" id="oe-start-'+S+'" value="'+r(Qe.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+S+'">End <input type="time" id="oe-end-'+S+'" value="'+r(Qe.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Se=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+S+'" value="'+Se[0]+'"'+(Qe.days.indexOf(Se[0])>=0?" checked":"")+' aria-label="'+Se[2]+'">'+Se[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,S)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+S+'"><span class="org-kind">Role</span><input id="oe-role-'+S+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&section=agents&under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,S)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,D=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',ae=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),ve=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+ae+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+ae+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+D+ve+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function jm(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?Pc(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>Mc(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var Bm=`
|
|
580
580
|
.oe-tree, .oe-tree ul { list-style: none; margin: 0; padding: 0; font-size: var(--ax-fs-sm); }
|
|
581
581
|
.oe-tree ul { margin-left: 10px; padding-left: 12px; border-left: var(--ax-border-w) solid var(--ax-border-2); }
|
|
582
582
|
.oe-tree li { padding: 3px 0; }
|
|
@@ -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
|
-
`;Ze();function Jt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map(E))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:E(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ws(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Ee(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Ee(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=xs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function xs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Bm(t,e){let n=new Set,r=xs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}Ze();var ks=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},ze=["mon","tue","wed","thu","fri","sat","sun"],Qt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Fc(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!ze.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?ze.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Uc(t){let e=ze.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>ze.indexOf(r)===e+o))return`${Qt[t[0]]} to ${Qt[t[t.length-1]]}`;let n=t.map(r=>Qt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var Zt={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function en(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function $s(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Wc(t){let e=t?.business?.roles??{};return{agents:[...$s(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...en(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Qe}}function jc(t){let e=t?.business??{},n=e.roles??{},r=$s(t),o=en(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Jt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function vs(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(en(t).keys()),o=En(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return Sn(le(e),n,r,o)??ws(Jt(e),n,r,o,i)}function qc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function Ss(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function Es(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>ks)throw new Error(`Keep the role under ${ks} characters.`);return e}function Bc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function _s(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:E(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:E(o.from),to:E(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function zm(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=vs(n),s=jc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Wc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?E(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=Es(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Ss(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=Es(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Ss(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=_s(r,w=>w.from===u.ref||w.to===u.ref),f=qc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(m?`, with ${m} ${m===1?"line":"lines"}`:"")+(f.length?` and out of ${f.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Qe.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[m,f]=g.map(E);for(let x of[m,f])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(m===f)throw new Error(`${l(m)} cannot be linked to themself.`);let w={from:m,to:f,type:u};if(s.relations.some(x=>x.from===m&&x.to===f&&x.type===u))throw new Error(`${l(m)} already ${Zt[u]} ${l(f)}.`);if(u==="acts-for"&&i.get(m).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(m)} is a person.`);if(u==="acts-for"&&i.get(f).kind!=="person")throw new Error(`An agent acts for a person: ${l(f)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===m);if(x)throw new Error(`${l(m)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Bc(s.relations,f,m))throw new Error(`${l(m)} cannot report to ${l(f)}: ${l(f)} already reports up to ${l(m)}.`)}if(u==="reports-to"&&i.get(m).kind==="agent"){let x=C(f);r.orgChart[C(m).id].reportsTo=x.kind==="agent"?x.id:f}else r.relations=[...r.relations??[],w];c=`${l(m)} ${Zt[u]} ${l(f)}`;break}case"remove-relation":{let u={from:E(String(e.from??"")),to:E(String(e.to??"")),type:String(e.type??"")};if(!_s(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${Zt[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Fc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Uc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=vs(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Hc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Ts=class{constructor(e=Hc,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},Vc="That code didn't work. Check it, or run agentx app pair for a new one.",Xc=400;async function Ym(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await vr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await zc(n,e.minMs??Xc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Vc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function zc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as dd}from"child_process";import{mkdtempSync as rd,rmSync as od,writeFileSync as sd}from"fs";import{tmpdir as id}from"os";import{join as Cs}from"path";import{randomBytes as Kc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var q={top:8,side:32,bottom:60},tn={height:56,keep:52},As=`
|
|
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 ws(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Ee(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Ee(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=xs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function xs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Vm(t,e){let n=new Set,r=xs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}et();var ks=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 Fc(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!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 Uc(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 $s(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Wc(t){let e=t?.business?.roles??{};return{agents:[...$s(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...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 jc(t){let e=t?.business??{},n=e.roles??{},r=$s(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 vs(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)??ws(Qt(e),n,r,o,i)}function Bc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function Ss(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function Es(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>ks)throw new Error(`Keep the role under ${ks} characters.`);return e}function qc(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 Gm(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=vs(n),s=jc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Wc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?E(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=Es(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Ss(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=Es(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Ss(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=_s(r,w=>w.from===u.ref||w.to===u.ref),f=Bc(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(qc(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=Fc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Uc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=vs(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Hc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Ts=class{constructor(e=Hc,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},Vc="That code didn't work. Check it, or run agentx app pair for a new one.",Xc=400;async function Qm(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 Sr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await zc(n,e.minMs??Xc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Vc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function zc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as dd}from"child_process";import{mkdtempSync as rd,rmSync as od,writeFileSync as sd}from"fs";import{tmpdir as id}from"os";import{join as Cs}from"path";import{randomBytes as Kc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var B={top:8,side:32,bottom:60},nn={height:56,keep:52},As=`
|
|
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;
|
|
@@ -639,11 +639,11 @@ body {
|
|
|
639
639
|
font: 13.5px/1.5 var(--ac-font); color: var(--ac-text); font-feature-settings: "ss01", "cv11";
|
|
640
640
|
-webkit-font-smoothing: antialiased; -webkit-user-select: none; user-select: none; cursor: default;
|
|
641
641
|
}
|
|
642
|
-
.wrap { padding: ${
|
|
642
|
+
.wrap { padding: ${B.top}px ${B.side}px ${B.bottom}px; }
|
|
643
643
|
.card {
|
|
644
644
|
background: var(--ac-paper); border: 1px solid var(--ac-rim); border-radius: 18px;
|
|
645
645
|
box-shadow: var(--ac-shadow); overflow: hidden; animation: ac-in .26s cubic-bezier(.65,0,.35,1);
|
|
646
|
-
position: relative; display: flex; flex-direction: column; max-height: calc(100vh - ${
|
|
646
|
+
position: relative; display: flex; flex-direction: column; max-height: calc(100vh - ${B.top+B.bottom}px);
|
|
647
647
|
}
|
|
648
648
|
.card::before {
|
|
649
649
|
content: ""; position: absolute; top: 6px; left: 50%; width: 32px; height: 4px; margin-left: -16px;
|
|
@@ -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 Rs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Is=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Gc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Rs(n):Is(n)}`}function Yc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Is(n)],Rs(n)].join(" ")}function Jc(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function Qc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var
|
|
741
|
+
`;var Rs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Is=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Gc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Rs(n):Is(n)}`}function Yc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Is(n)],Rs(n)].join(" ")}function Jc(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function Qc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var 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>`,Zc=rn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),ed=rn('<path d="m6 15 6-6 6 6"/>'),td=rn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Ds(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Kc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=Bn(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:Wn,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>
|
|
@@ -856,7 +856,7 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
|
|
|
856
856
|
`;var ad=440,ld=`
|
|
857
857
|
ObjC.import("Cocoa"); ObjC.import("WebKit")
|
|
858
858
|
function run(argv) {
|
|
859
|
-
var path = argv[0], side = ${
|
|
859
|
+
var path = argv[0], side = ${B.side}, gripTop = ${B.top}, gripEnd = ${B.top+nn.height}, keep = ${nn.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
|
|
860
860
|
var app = $.NSApplication.sharedApplication
|
|
861
861
|
app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
|
|
862
862
|
ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
|
|
@@ -930,27 +930,27 @@ function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
|
|
|
930
930
|
function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
|
|
931
931
|
`;function cd(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"&&Os.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let o=e.choices??[],s;if(o.length){if(typeof r.choice!="string"||!o.includes(r.choice))return{action:"dismiss"};s=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
|
|
933
|
-
`).trim():"",!i||i.length>
|
|
933
|
+
`).trim():"",!i||i.length>Un.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Ns(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=rd(Cs(id(),"agentx-card-"));try{let s=Cs(o,"card.html");sd(s,Ds(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",ld,s,String(ad),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?cd(a.stdout,t):null}finally{od(o,{recursive:!0,force:!0})}}var Os=["not now","timed out","closed"],ud=(t,e,n)=>new Promise(r=>{try{dd(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ls=160,on=15e3;function Ps(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ls?e.slice(0,Ls):e}async function pd(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?vr(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(Ps(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,"--",Ps(t)],on)}}function Us(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function gd(t,e,n){return Us(["on run argv","set opts to items 3 thru -1 of argv",'set pick to choose from list opts with title (item 1 of argv) with prompt (item 2 of argv) OK button name "Next" cancel button name "Not now"','if pick is false then return ""',"return item 1 of pick","end run"],[t,e,...n])}function Ms(t,e,n,r,o){return Us(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
|
|
934
934
|
`),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Fs(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
|
|
935
|
-
`);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function
|
|
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
|
|
|
937
|
-
`)}async function Ws(t,e,n={}){let r=n.run??ud,o=(e.style??"card")==="card",s=pd(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Ns(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await s,md(t,e,r)}async function md(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=(r+5)*1e3,s=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let l=await n("/usr/bin/osascript",gd(s,
|
|
937
|
+
`)}async function Ws(t,e,n={}){let r=n.run??ud,o=(e.style??"card")==="card",s=pd(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Ns(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await s,md(t,e,r)}async function md(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=(r+5)*1e3,s=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let l=await n("/usr/bin/osascript",gd(s,sn(t),t.choices),o);if(i=l.stdout.replace(/\n$/,""),!l.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let l=i?`${i}
|
|
938
938
|
|
|
939
|
-
Message (edit it if you like):`:`${
|
|
939
|
+
Message (edit it if you like):`:`${sn(t)}
|
|
940
940
|
|
|
941
|
-
Message (edit it if you like):`,p=await n("/usr/bin/osascript",Ms(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,
|
|
942
|
-
Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Rd,fstatSync as Id,openSync as Dd,realpathSync as Gs}from"fs";import{isAbsolute as Cd,resolve as Ys,sep as Js}from"path";var
|
|
943
|
-
`)[0]}); Siri voices will not switch`),null}}var
|
|
944
|
-
`).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as tu,rm as nu,writeFile as ru}from"fs/promises";import{tmpdir as ou}from"os";import{join as ci}from"path";ki();var su=64*1024,iu=2,
|
|
941
|
+
Message (edit it if you like):`,p=await n("/usr/bin/osascript",Ms(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,jn(t.draft,i)),o),u=p.ok?Fs(p.stdout):null;if(u?.button==="Send"){let g=u.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return u?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",Ms(s,sn(t),["Not now","No","Yes"],r),o),d=a.ok?Fs(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var cn=24*36e5,an=!1,fd=10*6e4,js=-1/0;function Bs(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)||Rr(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 qs=new Map;function hd(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 qs.get(s.id)===K(s,ot.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=cn})??null:null}function bd(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 Df(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=Bs(e,t.reaches)?null:hd(e,t.reaches),s=o?bd(o,e.now??Date.now()):Bs(e,t.reaches);if(!s)return"none";let i=(t.focus??ps)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:qn(s);if(d){if(o)qs.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,Hn(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-js<fd;o&&n.speak&&(js=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??Ws)(s,p?{...n,speak:!1}:n,{from:u,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${nr(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 bo(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 Cf(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}`}:(Wr(t.root,e),{ok:!0,message:`${e} will show on the Mac within a minute`}):{ok:!1,error:`no card "${e}"; the popup shows decision cards only`}}import{existsSync as yd,mkdirSync as wd,readFileSync as xd,renameSync as kd,writeFileSync as vd}from"fs";import{dirname as Sd,resolve as Ed}from"path";var _d=["all","urgent","off"],$d=24*36e5,Hs=24*36e5,Td=30*24*36e5,Vs=t=>_d.includes(t);function Pf(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Vs(e)?e:"off",computer:Vs(n)?n:t.popupEnabled?"all":"off"}}function zs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=$d}function Xs(t,e,n){return t==="all"||t==="urgent"&&zs(e,n)}function Ks(t){return Ed(t,".agentx","desk-routed.json")}function Ad(t){let e=Ks(t);if(!yd(e))return null;try{let n=JSON.parse(xd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function dn(t,e){let n=Ks(t);wd(Sd(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;vd(r,JSON.stringify(e,null,2)),kd(r,n)}async function Mf(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Ad(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return 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)>Hs&&delete u.computerHeld,u.computerHeld&&c.push(p);continue}d.items[p.key]={at:a,seen:a};let g=p.askedAt?Date.parse(p.askedAt):n;n-g<=Hs&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>Td&&delete d.items[p];dn(e,d);for(let p of l)if(Xs(o.phone,p,n))try{await t.phone(p,zs(p,n)),i.phone.push(p.key)}catch(u){s(`[desk] ${p.key}: not sent to the phone: ${u?.message??u}`)}if(t.computer){let p=!1;for(let u of[...c,...l]){let g=d.items[u.key];if(!Xs(o.computer,u,n)){g.computerHeld&&(delete g.computerHeld,p=!0);continue}try{let m=await t.computer(u);m&&i.computer.push(u.key),m&&g.computerHeld&&(delete g.computerHeld,p=!0),!m&&!g.computerHeld&&(g.computerHeld=!0,p=!0)}catch(m){s(`[desk] ${u.key}: not shown on this computer: ${m?.message??m}`),g.computerHeld&&(delete g.computerHeld,p=!0)}}p&&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 Ff(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
|
|
942
|
+
Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Rd,fstatSync as Id,openSync as Dd,realpathSync as Gs}from"fs";import{isAbsolute as Cd,resolve as Ys,sep as Js}from"path";var Hf="/app-files",Nd=/^[A-Za-z0-9_.:-]{1,64}$/;function Od(t,e,n=process.cwd()){if(!e||e.length>W.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${dt}/ first`};if(!ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Gs(Ys(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Gs(Cd(e)?e:Ys(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Js))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${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 Ld(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function Pd(t,e,n){return{"Content-Type":t,"Content-Disposition":Ld(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function Md(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Vf(t,e,n,r){let o=(x,b)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(b))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!Nd.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let d=Od(a,i,r.cwd);if(!d.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${d.error}`),o(d.status,{error:d.error});let l;try{l=Dd(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=Id(l);if(!x.isFile())return ye(l),o(404,{error:"not a file"});c=x.size}catch{return ye(l),o(404,{error:"file not found"})}if(c>W.bytes)return ye(l),o(413,{error:`the file is larger than ${W.bytes/1024/1024} MB`});let p=d.path.split(Js).pop()||"file",u=Pd(d.mime,p,d.kind),g=Md(t.headers.range,c);if(g==="unsatisfiable"){ye(l),e.writeHead(416,{...u,"Content-Range":`bytes */${c}`}),e.end();return}let{start:m,end:f}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...u,"Content-Length":String(c?f-m+1:0),...g?{"Content-Range":`bytes ${m}-${f}/${c}`}:{}}),t.method==="HEAD"||c===0){ye(l),e.end();return}let w=Rd("",{fd:l,start:m,end:f,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as we}from"child_process";import{readFileSync as Fd,writeFileSync as Ud}from"fs";import{tmpdir as Wd}from"os";import{join as jd}from"path";$n();var Qs=t=>t&&t!==1?Math.round(175*t):null,Ge=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function Bd(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=Fd(t,"utf8").trim();if(e)return e}catch{}return null}function eh(t=Bd()){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=jd(Wd(),`agentx-say-${process.pid}-${++e}.mp3`);return Ud(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return Y(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function Zs(t,e){let n=t.languages&&_e(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var qd=(t,e="")=>{let n=Zs(t,e),r=Qs(t.rate);return[...n&&!Ro(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Hd(t,e,n){if(!n)return["say",qd(t,e)];let r=Zs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function th(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function nh(t=un()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function rh(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 Co(e)}catch(n){return Y("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
|
|
943
|
+
`)[0]}); Siri voices will not switch`),null}}var oh=(t,e)=>{if(!t){let[n,r]=Hd(e.voice,e.text,un()),o=Qs(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=we(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?we("afplay",[t],{stdio:"ignore"}):we("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as ei}from"child_process";import{accessSync as Vd,constants as Xd,readFileSync as ti}from"fs";import{homedir as zd}from"os";import{basename as se,delimiter as ni,dirname as Kd,extname as Gd,join as pn}from"path";var z={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function ri(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>z.ms+2e3?{status:413,error:mn()}:null}var mn=()=>`The recording is longer than ${z.ms/6e4} minutes.`,Yd={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function oi(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Yd[e]??null}function si(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function 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=zd(),o=[pn(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(ni).filter(Boolean)];for(let s of[e,...o.map(i=>pn(i,t))])if(s)try{return Vd(s,Xd.X_OK),s}catch{}return null}function dh(t){return{key:t,mlx:gn("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:gn("whisper",process.env.AGENTX_WHISPER),ffmpeg:Jd()}}var Jd=()=>gn("ffmpeg",process.env.AGENTX_FFMPEG);async function ii(t,e){return e?Qd(t,e):null}async function Qd(t,e){let n=String(z.ms/1e3+5);try{let o=[...(await Zd(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function ai(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([ti(t)],{type:e}),se(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:o,signal:r??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let i=await s.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function li(t,e,n,r,o){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",o,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",o,"--fp16","False"],i={...process.env,PATH:`${Kd(r)}${ni}${process.env.PATH??""}`};await eu(e,s,12e4,i);try{return ti(pn(o,se(n,Gd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Zd(t,e,n){return new Promise((r,o)=>{let s=ei(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${se(t)} took too long`))},n);s.stderr.on("data",d=>{i=(i+d).slice(-8192)}),s.on("error",d=>{clearTimeout(a),o(d)}),s.on("exit",d=>{clearTimeout(a),d===0?r(i):o(new Error(`${se(t)} exited ${d}`))})})}function eu(t,e,n,r=process.env){return new Promise((o,s)=>{let i=ei(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",d="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${se(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{d.length<4096&&(d+=c)}),i.on("error",c=>{clearTimeout(l),s(c)}),i.on("exit",c=>{clearTimeout(l),c===0?o(a):s(new Error(`${se(t)} exited ${c}: ${d.trim().split(`
|
|
944
|
+
`).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as tu,rm as nu,writeFile as ru}from"fs/promises";import{tmpdir as ou}from"os";import{join as ci}from"path";ki();var su=64*1024,iu=2,hn=0;function kh(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function vh(t,e,n,r){return t.method!=="POST"?$(e,405,{error:"POST"}):n==="/voice/transcribe"?au(t,e,r):du(t,e,r)}async function au(t,e,n){let r=String(t.headers["content-type"]||""),o=oi(r);if(!o)return $(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=ri(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),$(e,s.status,{error:s.error});let i=await di(t,z.bytes);if(!i)return $(e,413,{error:gu()});if(!i.length)return $(e,400,{error:"The recording is empty."});if(hn>=iu)return $(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),d=n.host(),l=si(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+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 tu(ci(ou(),"agentx-phone-voice-"));try{c=await lu(p,`speech.${o}`,i,r,d,l,n)}finally{await nu(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{hn--}$(e,c[0],c[1])}async function lu(t,e,n,r,o,s,i){let a=ci(t,e);if(await ru(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??ii)(a,o.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>z.ms+2e3)return[413,{error:mn()}]}let d=[];for(let l of s)try{let c=await cu(l,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(c){let p=String(c?.message??c).split(`
|
|
945
945
|
`)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function cu(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return ai(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return li(t,a,e,r.ffmpeg,o)}async function du(t,e,n){let r=await di(t,su);if(!r)return $(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return $(e,400,{error:"expected JSON"})}let s=typeof o?.agent=="string"?o.agent:"",i=typeof o?.peer=="string"&&o.peer?o.peer:void 0;if(!s)return $(e,400,{error:"agent is required"});let a=uu(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return $(e,422,{error:"Nothing in this answer can be said aloud."});let d=n.pronounce?n.pronounce(a):a,l=n.voiceOf(s,i);if(!l)return $(e,404,{error:`Unknown agent: ${s}`});let c=(u,g=200)=>$(e,g,{fallback:"browser",reason:u,text:d});if(l.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let p=n.elevenLabsKey();if(!p)return c("No ElevenLabs key is set on this computer.");try{let u=await(n.synth??pu)(p,l,d);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":u.length,"Cache-Control":"no-store","X-Spoken-Chars":String(d.length)}),e.end(u)}catch(u){return n.log(`[voice] phone answer synthesis failed: ${String(u?.message??u).split(`
|
|
946
|
-
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function uu(t,e){let n=
|
|
946
|
+
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function uu(t,e){let n=Xe(Ae(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Tn(n,e)}async function pu(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 gu=()=>`The recording is larger than ${z.bytes/1024/1024} MB, more than ${z.ms/6e4} minutes of speech.`;function Sh(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 di(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let o=[],s=0;t.on("data",i=>{if(!(s>e)){if(s+=i.length,s>e){o.length=0,n(null);return}o.push(i)}}),t.on("end",()=>{s<=e&&n(Buffer.concat(o))}),t.on("error",r)})}function $(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}var mu="[Live voice call on the owner's watch or headset. Your answer is read aloud to them and they can't see a screen. Answer what they just said, in a few short spoken sentences.]",fu="operator",hu=50,ui=4,pi=500;function bu(t){let e={channel:"app",chatId:t.chatId,sender:fu,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${mu}
|
|
947
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
|
|
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 Ah(t,e,n,r){let{path:o,body:s}=bu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:Qn(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:wu(x);return{status:p,text:w,tools:d,files:f.artifacts,...b?{ui:b}:{},...g?{error:g}:{}}};try{let p=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!p.ok||!p.body){let u=await p.json().then(g=>g?.error).catch(()=>"");return c("error",i,u||`AgentX answered HTTP ${p.status}.`)}for await(let u of xu(p.body)){r(u.event,u.data);let g=u.data??{};if(u.event==="start")a=g.rich===!1;else if(u.event==="text"&&typeof g.text=="string")i+=g.text;else if(u.event==="tool"&&g.status==="start"&&d.length<hu){let m={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};d.push(m),g.id&&l.set(String(g.id),m)}else if(u.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(u.event==="done")return c("done",typeof g.content=="string"&&g.content?g.content:i);if(u.event==="error")return c("error",i,yu(g.error))}}return n.aborted?c("stopped",i):c("error",i,"The connection to the agent closed before it answered.")}catch(p){return n.aborted?c("stopped",i):c("error",i,`Could not reach AgentX: ${p?.message||p}`)}}function yu(t){let e=String(t||"The agent could not answer.");return zn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function wu(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,ui).map(i=>i.slice(0,pi));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,ui).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,pi)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*xu(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
|
|
949
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(`
|
|
952
952
|
`))c.startsWith("event:")?d=c.slice(6).trim():c.startsWith("data:")&&l.push(c.slice(5).replace(/^ /,""));if(l.length)try{yield{event:d,data:JSON.parse(l.join(`
|
|
953
|
-
`))}}catch{}}}}finally{e.releaseLock()}}var gi=["custom","announce"];function
|
|
953
|
+
`))}}catch{}}}}finally{e.releaseLock()}}var gi=["custom","announce"];function Ih(t,e){let n=t.nodeName,r=t.recent().filter(s=>gi.includes(s.kind)).slice(-500),o=(e?.list()??[]).slice(-500).map(s=>({...s,node:n}));return{node:n,events:r,wakes:o}}function Dh(t,e={}){let n=e.now??Date.now(),r=Math.max(1,Math.min(200,Math.floor(e.limit||50))),o=new Map;for(let b of t)for(let y of b.events)gi.includes(y.kind)&&!o.has(y.id)&&o.set(y.id,y);let s=[...o.values()].sort((b,y)=>Date.parse(b.at)-Date.parse(y.at)||b.id.localeCompare(y.id)),i=new Map,a=new Map,d=new Set;for(let b of t)for(let y of b.wakes){let k=y.node||b.node,D=`${k}#${y.agentId}#${y.eventId}`;if(d.has(D))continue;d.add(D);let ae=i.get(y.eventId)??[];if(ae.push(vu(y,k,n)),i.set(y.eventId,ae),y.status!=="skipped"){let ve=`${y.agentId}#${y.rootId}`,h=a.get(ve)??[];h.push({eventId:y.eventId,at:y.decidedAt}),a.set(ve,h)}}for(let b of i.values())b.sort((y,k)=>y.decidedAt-k.decidedAt||y.agentId.localeCompare(k.agentId));let l=new Map,c=[];for(let b of s){let y=ku(b,o,a,c);y&&y!==b.id&&l.set(b.id,y),c.push(b)}let p=b=>{let y=b;for(let k=0;k<50;k++){let D=l.get(y);if(!D)return y;y=D}return y},u=new Map,g=b=>({event:b,wakes:i.get(b.id)??[]});for(let b of s){let y=p(b.id);y===b.id?u.set(b.id,{...g(b),replies:[]}):u.get(y)?.replies.push(g(b))}let m=b=>Math.max(Date.parse(b.event.at),...b.replies.map(y=>Date.parse(y.event.at))),f=[...u.values()].sort((b,y)=>m(y)-m(b)),w=[...i.values()].flat(),x=b=>w.filter(y=>b.includes(y.status)).length;return{threads:f.slice(0,r),total:f.length,counts:{events:s.length,wakes:w.length,ran:x(["ran"]),waiting:x(["waiting","held","running"]),timedOut:x(["timed-out","dropped"]),failed:x(["failed"]),skipped:x(["skipped"])}}}function ku(t,e,n,r){if(t.parentId&&e.has(t.parentId))return t.parentId;let o=Date.parse(t.at);if(t.agentId){let s=(n.get(`${t.agentId}#${t.rootId}`)??[]).filter(i=>i.eventId!==t.id&&e.has(i.eventId)&&Date.parse(e.get(i.eventId).at)<=o).sort((i,a)=>a.at-i.at)[0];if(s)return s.eventId}if(t.rootId!==t.id)for(let s=r.length-1;s>=0;s--){let i=r[s];if(i.rootId===t.rootId&&(i.agentId??i.node)!==(t.agentId??t.node))return i.id}}function vu(t,e,n){let r={agentId:t.agentId,node:e,status:t.status,decidedAt:t.decidedAt,attempts:t.attempts};if(t.reason&&(r.reason=t.reason),t.startedAt&&(r.startedAt=t.startedAt),t.endedAt&&(r.endedAt=t.endedAt),t.taskId&&(r.taskId=t.taskId),t.error&&(r.error=t.error),t.status!=="skipped"){let o=t.startedAt??t.endedAt??n;r.waitedMs=Math.max(0,o-t.decidedAt)}return r}import{existsSync as M,readFileSync as xn,writeFileSync as kn,mkdirSync as Ye,readdirSync as wn,rmSync as Su,statSync as U}from"fs";import{resolve as mi,relative as Eu,dirname as vn,join as Q,extname as xe,basename as Sn}from"path";var I=200*1024,fi=new Set([".md",".markdown",".txt"]),ie=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),_u=6,$u=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function q(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=mi(t);if(M(n)||Ye(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=mi(n,e);if(Eu(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function hi(t){let e=xe(t).toLowerCase();if(!fi.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function bn(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Lh(t){let e=q(t,"."),n=[],r=new Set,o=[];try{o=wn(e)}catch{}for(let a of $u){let d=Q(e,a);if(M(d)&&U(d).isFile()){let l=U(d).size,c=l>0&&l<I?yn(d):"";n.push({path:a,title:bn(c,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of o){if(r.has(a))continue;let d=Q(e,a);try{let l=U(d);if(!l.isFile()||!fi.has(xe(a).toLowerCase()))continue;let c=l.size>0&&l.size<I?yn(d):"";n.push({path:a,title:bn(c,a),size:l.size,exists:!0})}catch{}}let s=[],i=Q(e,".claude","skills");if(M(i))try{for(let a of wn(i)){let d=Q(i,a),l;try{l=U(d)}catch{continue}if(!l.isDirectory())continue;let c=Q(d,"SKILL.md");if(!M(c))continue;let p=U(c),u=p.size<I?yn(c):"";s.push({slug:a,title:bn(u,a),size:p.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,d)=>a.slug.localeCompare(d.slug)),{identity:n,skills:s,workspace:e}}function yn(t){try{return xn(t,"utf-8")}catch{return""}}function Ph(t,e){let n=q(t,e);if(hi(n),!M(n))return{path:e,content:""};if(U(n).size>I)throw new Error(`File is too large to edit in the admin panel (> ${I/1024} KB).`);return{path:e,content:xn(n,"utf-8")}}function Mh(t,e,n){let r=q(t,e);hi(r);let o=Buffer.from(n,"utf-8");if(o.length>I)throw new Error(`File too large (${o.length} > ${I} bytes).`);return Ye(vn(r),{recursive:!0}),kn(r,o),{path:e,bytes:o.length}}function Fh(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,o=q(t,r);if(M(o))throw new Error(`Skill "${e}" already exists.`);Ye(vn(o),{recursive:!0});let s=n.content?.trim()?n.content:Tu(e,n.title);return kn(o,s),{slug:e,path:r}}function Uh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=q(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);if(!U(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Su(n,{recursive:!0,force:!0}),{slug:e}}function Wh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=q(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=[];return o(n,"",0,r),r.sort((s,i)=>s.kind!==i.kind?s.kind==="dir"?-1:1:s.path.localeCompare(i.path)),r;function o(s,i,a,d){if(a>_u)return;let l=[];try{l=wn(s)}catch{return}for(let c of l){if(c==="node_modules"||c===".git")continue;let p=Q(s,c),u=i?`${i}/${c}`:c,g;try{g=U(p)}catch{continue}if(g.isDirectory())d.push({path:`${u}/`,kind:"dir",size:0,editable:!1}),o(p,u,a+1,d);else if(g.isFile()){let m=xe(c).toLowerCase(),f=ie.has(m)||ie.has(c.toLowerCase());d.push({path:u,kind:"file",size:g.size,editable:f&&g.size<I})}}}}function jh(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=q(t,`.claude/skills/${e}/${n}`);if(!M(r)||!U(r).isFile())throw new Error(`File not found: ${n}`);let o=xe(r).toLowerCase(),s=Sn(r).toLowerCase();if(!ie.has(o)&&!ie.has(s))throw new Error(`File type not editable: ${n}`);if(U(r).size>I)throw new Error(`File too large to edit (> ${I/1024} KB): ${n}`);return{path:n,content:xn(r,"utf-8")}}function Bh(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let o=q(t,`.claude/skills/${e}/${n}`),s=xe(o).toLowerCase(),i=Sn(o).toLowerCase();if(!ie.has(s)&&!ie.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>I)throw new Error(`File too large (${a.length} > ${I} bytes).`);return Ye(vn(o),{recursive:!0}),kn(o,a),{path:n,bytes:a.length}}function qh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=q(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=o=>M(Q(n,o));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function Tu(t,e){return`# ${e?.trim()||t}
|
|
954
954
|
|
|
955
955
|
Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
|
|
956
956
|
|
|
@@ -963,7 +963,7 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
963
963
|
|
|
964
964
|
\`\`\`bash
|
|
965
965
|
# Example invocation
|
|
966
|
-
claude-code ${
|
|
966
|
+
claude-code ${Sn(t)} --arg value
|
|
967
967
|
\`\`\`
|
|
968
|
-
`}
|
|
969
|
-
//# sourceMappingURL=chunk-
|
|
968
|
+
`}Pn();var bi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function yi(t){return{...bi,...t??{},regions:{...t?.regions??{}},buffer:{...bi.buffer,...t?.buffer??{}}}}function Xh(t){try{return yi(Ln(t).screen)}catch{return yi(void 0)}}var Au=/^[a-z][\w-]*$/,wi=["window","screen","menubar","notifications"];function ke(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Je=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function xi(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function zh(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(!Au.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=xi(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ke(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ke(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=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&&!wi.includes(r)&&!n.regions?.[r])try{xi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...wi,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Ir as a,Du as b,Yt as c,oc as d,sc as e,gm as f,mm as g,fm as h,ym as i,wm as j,xm as k,as as l,ls as m,km as n,Xe as o,Sm as p,_m as q,X as r,cs as s,A as t,Lu as u,ps as v,Dm as w,Om as x,ms as y,Lm as z,fs as A,Pm as B,he as C,Cc as D,Mm as E,Fm as F,bs as G,Yu as H,Qi as I,np as J,Gr as K,N as L,Wu as M,ju as N,up as O,Ne as P,pp as Q,jr as R,zu as S,G as T,Wp as U,mo as V,bo as W,Pc as X,Wm as Y,Mc as Z,jm as _,Bm as $,Qt as aa,ws as ba,Vm as ca,en as da,Wc as ea,jc as fa,Gm as ga,La as ha,Pa as ia,qp as ja,Hp as ka,qa as la,Kp as ma,Ts as na,Qm as oa,Jp as pa,Qp as qa,rs as ra,jt as sa,Jl as ta,R as ua,Ws as va,Df as wa,Cf as xa,_d as ya,Pf as za,Xs as Aa,Mf as Ba,Ff as Ca,Hf as Da,Od as Ea,Pd as Fa,Vf as Ga,eg as Ha,tg as Ia,ng as Ja,rg as Ka,og as La,sg as Ma,ig as Na,ag as Oa,cg as Pa,dg as Qa,gg as Ra,mg as Sa,fg as Ta,yg as Ua,wg as Va,xg as Wa,kg as Xa,vg as Ya,Sg as Za,Eg as _a,Ng as $a,Dt as ab,Og as bb,Lg as cb,me as db,fe as eb,Bd as fb,eh as gb,th as hb,nh as ib,rh as jb,un as kb,oh as lb,Ot as mb,Lt as nb,Be as ob,wl as pb,kl as qb,Wg as rb,Mt as sb,Ft as tb,vl as ub,Sl as vb,Bo as wb,Xo as xb,jg as yb,$l as zb,Bg as Ab,Ol as Bb,Ml as Cb,Ut as Db,Ul as Eb,zo as Fb,z as Gb,ri as Hb,oi as Ib,si as Jb,gn as Kb,dh as Lb,Jd as Mb,ai as Nb,li as Ob,kh as Pb,vh as Qb,gu as Rb,Sh as Sb,di as Tb,Jo as Ub,Ah as Vb,wu as Wb,Ih as Xb,Dh as Yb,qe as Zb,rm as _b,Kt as $b,dm as ac,Lh as bc,Ph as cc,Mh as dc,Fh as ec,Uh as fc,Wh as gc,jh as hc,Bh as ic,qh as jc,bi as kc,yi as lc,Xh as mc,wi as nc,zh as oc};
|
|
969
|
+
//# sourceMappingURL=chunk-NKSQNQ5V.js.map
|