agentix-cli 0.137.2 → 0.138.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/{App-TOAWET76.js → App-F42CYCKX.js} +2 -2
  2. package/dist/{ChatApp-4DRCRKFS.js → ChatApp-RPMQBKHV.js} +2 -2
  3. package/dist/{absorb-eval-OXNL5QGQ.js → absorb-eval-HRPEHJSO.js} +2 -2
  4. package/dist/{agent-GALMGMNJ.js → agent-L5CJF3GH.js} +2 -2
  5. package/dist/{board-dashboard-2A6VSQ7V.js → board-dashboard-33NGOGWC.js} +440 -285
  6. package/dist/board-dashboard-33NGOGWC.js.map +1 -0
  7. package/dist/{chunk-XZIKAHFU.js → chunk-375MXG3H.js} +2 -2
  8. package/dist/{chunk-5ADXRVYT.js → chunk-4HHHVWDB.js} +5 -5
  9. package/dist/{chunk-Q72TK3DO.js → chunk-5HLD66CW.js} +2 -2
  10. package/dist/{chunk-5RHCM3L7.js → chunk-6AUWEL6V.js} +2 -2
  11. package/dist/{chunk-635B6SXI.js → chunk-6VP2KMUM.js} +2 -2
  12. package/dist/{chunk-WCXXXAHV.js → chunk-7DYVNET6.js} +1 -1
  13. package/dist/chunk-7DYVNET6.js.map +1 -0
  14. package/dist/{chunk-3K3LRLZX.js → chunk-7V73QTQ7.js} +2 -2
  15. package/dist/{chunk-PNITKKDR.js → chunk-7YZL5MUL.js} +9 -9
  16. package/dist/{chunk-PNITKKDR.js.map → chunk-7YZL5MUL.js.map} +1 -1
  17. package/dist/chunk-A5GYG56I.js +2 -0
  18. package/dist/chunk-A5GYG56I.js.map +1 -0
  19. package/dist/{chunk-GIQKQD2B.js → chunk-AGQYUOZY.js} +2 -2
  20. package/dist/{chunk-2JKKGS77.js → chunk-AP4DADXG.js} +2 -2
  21. package/dist/{chunk-DIE6XXJF.js → chunk-CZZJEFUM.js} +2 -2
  22. package/dist/{chunk-23LWLYOK.js → chunk-DBJUGKX2.js} +2 -2
  23. package/dist/{chunk-B6PMIUVV.js → chunk-EGPCEQJN.js} +2 -2
  24. package/dist/{chunk-ZYUVKFX2.js → chunk-GAIXI26T.js} +2 -2
  25. package/dist/{chunk-KHYF6KTY.js → chunk-HJCFLGVT.js} +13 -13
  26. package/dist/chunk-HJCFLGVT.js.map +1 -0
  27. package/dist/{chunk-VDG6Y5L3.js → chunk-HQH44RGL.js} +2 -2
  28. package/dist/chunk-IS2IWRP7.js +4 -0
  29. package/dist/chunk-IS2IWRP7.js.map +1 -0
  30. package/dist/{chunk-BXXP6DTB.js → chunk-JIJDBCV7.js} +2 -2
  31. package/dist/{chunk-Z2QOQBUS.js → chunk-LA6P3TUK.js} +2 -2
  32. package/dist/{chunk-SQ37I2MD.js → chunk-MTDVAO5C.js} +2 -2
  33. package/dist/{chunk-7JUISIE7.js → chunk-QGSUENRK.js} +2 -2
  34. package/dist/{chunk-PNYBZPPB.js → chunk-SK47VJMQ.js} +3 -3
  35. package/dist/{chunk-RWMDDMYX.js → chunk-TFH6S7IT.js} +2 -2
  36. package/dist/{chunk-QY5YUHGW.js → chunk-TVW5ZKJY.js} +2 -2
  37. package/dist/{chunk-RTKSSFX2.js → chunk-UPNKRCFX.js} +7 -7
  38. package/dist/{chunk-IIFHX625.js → chunk-UPQTTOVQ.js} +2 -2
  39. package/dist/{chunk-E3AEOQMK.js → chunk-VVX4RXMV.js} +2 -2
  40. package/dist/{chunk-PLPDG6GE.js → chunk-XBARUCG5.js} +2 -2
  41. package/dist/{chunk-MXDWLBIA.js → chunk-XVYIPVSC.js} +2 -2
  42. package/dist/{chunk-JC5KLH2K.js → chunk-Y7IHOQC7.js} +2 -2
  43. package/dist/cli.js +1 -1
  44. package/dist/cli.js.map +1 -1
  45. package/dist/{client-PWE4BJH4.js → client-EB55Y6EJ.js} +2 -2
  46. package/dist/{config-E53FBZ47.js → config-7DRUA5R3.js} +2 -2
  47. package/dist/{config-mutate-ZEHN6JMZ.js → config-mutate-GGA7VXXH.js} +2 -2
  48. package/dist/config-mutator-POFVILXH.js +2 -0
  49. package/dist/{contributions-CLLCLS3O.js → contributions-TZ26MTML.js} +2 -2
  50. package/dist/{doctor-XKT5FWPO.js → doctor-GTRZ7GWF.js} +2 -2
  51. package/dist/{follow-up-tool-ZFRZUZLI.js → follow-up-tool-PNB7KMCY.js} +2 -2
  52. package/dist/{hub-N5ADP3LO.js → hub-QWJR4E6V.js} +2 -2
  53. package/dist/index.js +1 -1
  54. package/dist/net-family-X2P3OVDP.js +2 -0
  55. package/dist/ntfy-Q4YHFKWW.js +2 -0
  56. package/dist/{program-AMQ7JGHO.js → program-KMUCHLDU.js} +23 -23
  57. package/dist/{program-AMQ7JGHO.js.map → program-KMUCHLDU.js.map} +1 -1
  58. package/dist/{promote-M4UBD2R6.js → promote-HAPXWGYH.js} +2 -2
  59. package/dist/push-PRFZMCIK.js +2 -0
  60. package/dist/push-bridge-276ZLSUT.js +2 -0
  61. package/dist/{query-KMQHF5HW.js → query-ICLOVLZ3.js} +2 -2
  62. package/dist/{query-settings-PENAE4UG.js → query-settings-7AXUOHDL.js} +2 -2
  63. package/dist/{registry-GYKSYSDD.js → registry-IUNSHCOL.js} +2 -2
  64. package/dist/{request-planner-GBX6DHRQ.js → request-planner-TDCLF2CH.js} +2 -2
  65. package/dist/{review-candidates-SYMRJGI2.js → review-candidates-QCBXLWG6.js} +2 -2
  66. package/dist/{routing-S3L44JLL.js → routing-YUP3HHL5.js} +2 -2
  67. package/dist/schedule-tool-3C22NBMN.js +2 -0
  68. package/dist/{scheduler-AW4F5ZKS.js → scheduler-7NK2FH5V.js} +2 -2
  69. package/dist/{seat-QBBNCOFO.js → seat-PTPPQOTP.js} +2 -2
  70. package/dist/{select-ZCFIMYWS.js → select-2XSTWMBR.js} +2 -2
  71. package/dist/{set-enabled-4F27A3U2.js → set-enabled-SS5Q3OX7.js} +2 -2
  72. package/dist/{tool-M462KSMF.js → tool-QCMSXEDB.js} +2 -2
  73. package/dist/{tool-G6XTO24J.js → tool-RK4LDFFH.js} +2 -2
  74. package/dist/{wiki-JXVHIEZI.js → wiki-Q2E44YAE.js} +2 -2
  75. package/dist/wiki-enrich-6ULCDOTX.js +2 -0
  76. package/package.json +1 -1
  77. package/dist/board-dashboard-2A6VSQ7V.js.map +0 -1
  78. package/dist/chunk-GFKLKPPY.js +0 -4
  79. package/dist/chunk-GFKLKPPY.js.map +0 -1
  80. package/dist/chunk-KHYF6KTY.js.map +0 -1
  81. package/dist/chunk-PBP3D2BM.js +0 -2
  82. package/dist/chunk-PBP3D2BM.js.map +0 -1
  83. package/dist/chunk-WCXXXAHV.js.map +0 -1
  84. package/dist/config-mutator-AK775RTM.js +0 -2
  85. package/dist/net-family-OFHIZDHS.js +0 -2
  86. package/dist/ntfy-W56TUC5C.js +0 -2
  87. package/dist/push-B2GNI3VQ.js +0 -2
  88. package/dist/push-bridge-F4PCXWJF.js +0 -2
  89. package/dist/schedule-tool-FXUFRZHR.js +0 -2
  90. package/dist/wiki-enrich-6776OMUB.js +0 -2
  91. /package/dist/{App-TOAWET76.js.map → App-F42CYCKX.js.map} +0 -0
  92. /package/dist/{ChatApp-4DRCRKFS.js.map → ChatApp-RPMQBKHV.js.map} +0 -0
  93. /package/dist/{absorb-eval-OXNL5QGQ.js.map → absorb-eval-HRPEHJSO.js.map} +0 -0
  94. /package/dist/{agent-GALMGMNJ.js.map → agent-L5CJF3GH.js.map} +0 -0
  95. /package/dist/{chunk-XZIKAHFU.js.map → chunk-375MXG3H.js.map} +0 -0
  96. /package/dist/{chunk-5ADXRVYT.js.map → chunk-4HHHVWDB.js.map} +0 -0
  97. /package/dist/{chunk-Q72TK3DO.js.map → chunk-5HLD66CW.js.map} +0 -0
  98. /package/dist/{chunk-5RHCM3L7.js.map → chunk-6AUWEL6V.js.map} +0 -0
  99. /package/dist/{chunk-635B6SXI.js.map → chunk-6VP2KMUM.js.map} +0 -0
  100. /package/dist/{chunk-3K3LRLZX.js.map → chunk-7V73QTQ7.js.map} +0 -0
  101. /package/dist/{chunk-GIQKQD2B.js.map → chunk-AGQYUOZY.js.map} +0 -0
  102. /package/dist/{chunk-2JKKGS77.js.map → chunk-AP4DADXG.js.map} +0 -0
  103. /package/dist/{chunk-DIE6XXJF.js.map → chunk-CZZJEFUM.js.map} +0 -0
  104. /package/dist/{chunk-23LWLYOK.js.map → chunk-DBJUGKX2.js.map} +0 -0
  105. /package/dist/{chunk-B6PMIUVV.js.map → chunk-EGPCEQJN.js.map} +0 -0
  106. /package/dist/{chunk-ZYUVKFX2.js.map → chunk-GAIXI26T.js.map} +0 -0
  107. /package/dist/{chunk-VDG6Y5L3.js.map → chunk-HQH44RGL.js.map} +0 -0
  108. /package/dist/{chunk-BXXP6DTB.js.map → chunk-JIJDBCV7.js.map} +0 -0
  109. /package/dist/{chunk-Z2QOQBUS.js.map → chunk-LA6P3TUK.js.map} +0 -0
  110. /package/dist/{chunk-SQ37I2MD.js.map → chunk-MTDVAO5C.js.map} +0 -0
  111. /package/dist/{chunk-7JUISIE7.js.map → chunk-QGSUENRK.js.map} +0 -0
  112. /package/dist/{chunk-PNYBZPPB.js.map → chunk-SK47VJMQ.js.map} +0 -0
  113. /package/dist/{chunk-RWMDDMYX.js.map → chunk-TFH6S7IT.js.map} +0 -0
  114. /package/dist/{chunk-QY5YUHGW.js.map → chunk-TVW5ZKJY.js.map} +0 -0
  115. /package/dist/{chunk-RTKSSFX2.js.map → chunk-UPNKRCFX.js.map} +0 -0
  116. /package/dist/{chunk-IIFHX625.js.map → chunk-UPQTTOVQ.js.map} +0 -0
  117. /package/dist/{chunk-E3AEOQMK.js.map → chunk-VVX4RXMV.js.map} +0 -0
  118. /package/dist/{chunk-PLPDG6GE.js.map → chunk-XBARUCG5.js.map} +0 -0
  119. /package/dist/{chunk-MXDWLBIA.js.map → chunk-XVYIPVSC.js.map} +0 -0
  120. /package/dist/{chunk-JC5KLH2K.js.map → chunk-Y7IHOQC7.js.map} +0 -0
  121. /package/dist/{client-PWE4BJH4.js.map → client-EB55Y6EJ.js.map} +0 -0
  122. /package/dist/{config-E53FBZ47.js.map → config-7DRUA5R3.js.map} +0 -0
  123. /package/dist/{config-mutate-ZEHN6JMZ.js.map → config-mutate-GGA7VXXH.js.map} +0 -0
  124. /package/dist/{config-mutator-AK775RTM.js.map → config-mutator-POFVILXH.js.map} +0 -0
  125. /package/dist/{contributions-CLLCLS3O.js.map → contributions-TZ26MTML.js.map} +0 -0
  126. /package/dist/{doctor-XKT5FWPO.js.map → doctor-GTRZ7GWF.js.map} +0 -0
  127. /package/dist/{follow-up-tool-ZFRZUZLI.js.map → follow-up-tool-PNB7KMCY.js.map} +0 -0
  128. /package/dist/{hub-N5ADP3LO.js.map → hub-QWJR4E6V.js.map} +0 -0
  129. /package/dist/{net-family-OFHIZDHS.js.map → net-family-X2P3OVDP.js.map} +0 -0
  130. /package/dist/{ntfy-W56TUC5C.js.map → ntfy-Q4YHFKWW.js.map} +0 -0
  131. /package/dist/{promote-M4UBD2R6.js.map → promote-HAPXWGYH.js.map} +0 -0
  132. /package/dist/{push-B2GNI3VQ.js.map → push-PRFZMCIK.js.map} +0 -0
  133. /package/dist/{push-bridge-F4PCXWJF.js.map → push-bridge-276ZLSUT.js.map} +0 -0
  134. /package/dist/{query-KMQHF5HW.js.map → query-ICLOVLZ3.js.map} +0 -0
  135. /package/dist/{query-settings-PENAE4UG.js.map → query-settings-7AXUOHDL.js.map} +0 -0
  136. /package/dist/{registry-GYKSYSDD.js.map → registry-IUNSHCOL.js.map} +0 -0
  137. /package/dist/{request-planner-GBX6DHRQ.js.map → request-planner-TDCLF2CH.js.map} +0 -0
  138. /package/dist/{review-candidates-SYMRJGI2.js.map → review-candidates-QCBXLWG6.js.map} +0 -0
  139. /package/dist/{routing-S3L44JLL.js.map → routing-YUP3HHL5.js.map} +0 -0
  140. /package/dist/{schedule-tool-FXUFRZHR.js.map → schedule-tool-3C22NBMN.js.map} +0 -0
  141. /package/dist/{scheduler-AW4F5ZKS.js.map → scheduler-7NK2FH5V.js.map} +0 -0
  142. /package/dist/{seat-QBBNCOFO.js.map → seat-PTPPQOTP.js.map} +0 -0
  143. /package/dist/{select-ZCFIMYWS.js.map → select-2XSTWMBR.js.map} +0 -0
  144. /package/dist/{set-enabled-4F27A3U2.js.map → set-enabled-SS5Q3OX7.js.map} +0 -0
  145. /package/dist/{tool-M462KSMF.js.map → tool-QCMSXEDB.js.map} +0 -0
  146. /package/dist/{tool-G6XTO24J.js.map → tool-RK4LDFFH.js.map} +0 -0
  147. /package/dist/{wiki-JXVHIEZI.js.map → wiki-Q2E44YAE.js.map} +0 -0
  148. /package/dist/{wiki-enrich-6776OMUB.js.map → wiki-enrich-6ULCDOTX.js.map} +0 -0
@@ -1,8 +1,8 @@
1
- import{a as Re}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-7LN4VKDU.js";import{a as ne}from"./chunk-IMLAPB7G.js";import{q as Kt}from"./chunk-S2GAEH2F.js";import{f as Yt,g as Ae,i as V,j as q,l as Zt}from"./chunk-AKWBDCMU.js";import{b as Jt}from"./chunk-WCXXXAHV.js";import{t as Xt,u as Gt}from"./chunk-635B6SXI.js";import{d as Ht,e as zt}from"./chunk-AQASR6KR.js";import{X as Nt,Z as te,_ as ve,aa as $e,b as Se}from"./chunk-3K3LRLZX.js";import{a as Vt,b as qt,d as Bt}from"./chunk-Y4CYQV7G.js";import{a as Lt,b as Ot}from"./chunk-SHEUCITK.js";import{g as Mt,h as jt,i as Wt,k as Ft,l as Ut}from"./chunk-5RHCM3L7.js";import{q as Pt}from"./chunk-23LWLYOK.js";import{a as Ct,b as Dt}from"./chunk-BXXP6DTB.js";import{Aa as Tt,B as $t,C as At,D as Rt,E as _t,ka as xe,n as ee,o as St,p as vt,q as Jr,ra as It,sa as Et}from"./chunk-KHYF6KTY.js";import{a as we,h as Yr}from"./chunk-BRK6M6LA.js";import{f as ke,n as Zr}from"./chunk-UIBUZ2N3.js";import{existsSync as Qr,readdirSync as ei,readFileSync as ti,statSync as ni}from"fs";import{resolve as ri}from"path";function Qt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],l=a.filter(f=>n-f.at<=r),c=a.filter(f=>n-f.at>r&&n-f.at<=r*2),u=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((o,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[o.state]-l[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var re=new Map;function Ea(t,e=1e3){if(!Qr(t))return[];let n=ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ri(t,s);return{path:o,mtime:ni(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=re.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let l=ii(s,o);re.set(s,{mtime:o,summary:l}),l&&r.push(l)}return r}function ii(t,e){try{let n=ti(t,"utf-8").split(`
2
- `).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),l=a.status??a.run?.status;if(l){s=l;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var si={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},oi=(t,e,n)=>{try{return Pt(t,e,n)}catch{return null}},en=864e5;function Pa(t){let e=t.now??Date.now(),n={...si,...t.thresholds},i=t.nextFire??oi,r=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",u=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?_e(a.nextRun)??_e(i(a.schedule,new Date(e),c)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:pi(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:tn(u),sampledRuns:l.length,flags:[],attention:null};p.flags=nn(p,u,a.schedule,c,null,e,n,i),r.push(rn(p))}let s=new Map(Qt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let l=o.get(a.workflowId);l?l.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(I=>I.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((I,ye)=>ye.at-I.at),g=p.map(I=>({at:I.at,status:ci(I.status)})),f=g[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",C=typeof c.timezone=="string"?c.timezone:"UTC",M={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(b,k.text),timezone:C}:{event:$(typeof c.event=="string"?c.event:"",k.text),filters:di(c.filter,a)},agent:ui(a),enabled:d,state:u,nextRunAt:h&&d&&b?_e(i(b,new Date(e),C)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let I=g.find(ye=>ye.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:tn(g),sampledRuns:p.length,flags:[],attention:null},Q=Date.parse(a.updated||a.created||"");M.flags=h?nn(M,g,b,C,Number.isFinite(Q)?Q:null,e,n,i):ai(M,s.get(a.id)?.state==="dormant",Number.isFinite(Q)?Q:null,e,n),r.push(rn(M))}return r.sort(li).slice(0,k.routines)}function tn(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 nn(t,e,n,i,r,s,o,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=on(c,r,s,o);return p&&l.push(p),l}if(t.consecutiveFailures>=o.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${o.missedFires} scheduled fires missed`}),l}function ai(t,e,n,i,r){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=on(o,n,i,r);return a&&s.push(a),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===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 on(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*en?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/en)} days`:"Disabled and never ran"}}function rn(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 sn={critical:0,warning:1,info:2};function li(t,e){let n=t.attention?sn[t.attention]:3,i=e.attention?sn[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ci(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 ui(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function di(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${r}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function _e(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function pi(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as H,readdirSync as Pi,readFileSync as Ni}from"fs";import{resolve as R}from"path";import{randomBytes as cn}from"crypto";import{existsSync as fi,mkdirSync as mi,readdirSync as hi,readFileSync as bi,renameSync as un,unlinkSync as yi,writeFileSync as wi}from"fs";import{resolve as dn}from"path";function an(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var gi=t=>t.trim().split(`
3
- `).pop()?.slice(0,300)||"no output";async function ln(t,e,n,i=Re){let r=await i(t.bin,[...an(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${gi(r.stderr||r.stdout)}`}}async function Oa(t,e,n,i,r=Re){return(await r(t.bin,[...an(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var ki=2e3,xi=t=>ln(t.wacli,t.to,t.text);function Ie(t){return dn(t,".agentx","whatsapp-triage","drafts")}var Si=t=>/^[a-z0-9-]{8,64}$/.test(t),ie=(t,e)=>dn(Ie(t),`${e}.json`);function pn(t,e){mi(Ie(t),{recursive:!0});let n=ie(t,e.id),i=`${n}.${process.pid}.tmp`;wi(i,JSON.stringify(e,null,2)+`
4
- `,{mode:384}),un(i,n)}function Va(t,e,n=Date.now()){let i=e.text.trim().slice(0,ki);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${cn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return pn(t,r),r}function se(t,e){if(!Si(e))return null;try{return JSON.parse(bi(ie(t,e),"utf-8"))}catch{return null}}function gn(t,e){let n=Ie(t);return fi(n)?hi(n).filter(i=>i.endsWith(".json")).map(i=>se(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function fn(t,e,n,i={}){let r=se(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${ie(t,e)}.${process.pid}.${cn(3).toString("hex")}.claim`;try{un(ie(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(i.send??xi)(r).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}pn(t,o);try{yi(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as vi,readFileSync as $i,renameSync as Ai,writeFileSync as Ri}from"fs";import{resolve as _i}from"path";function mn(t){return _i(Ae(t),"_state.json")}function A(t){try{let e=JSON.parse($i(mn(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 B(t,e){vi(Ae(t),{recursive:!0});let n=mn(t),i=`${n}.${process.pid}.tmp`;Ri(i,JSON.stringify(e,null,2)+`
5
- `),Ai(i,n)}function hn(t,e,n,i=Date.now()){let r=A(t),s={};for(let[o,a]of Object.entries(r.snoozed))Date.parse(a)>i&&(s[o]=a);s[e]=n.toISOString(),B(t,{...r,snoozed:s})}function Xa(t,e){B(t,{...A(t),lastDigest:e})}function bn(t,e,n,i=Date.now()){let r=A(t),s=new Set(n),o={};for(let[l,c]of Object.entries(r.popped??{}))s.has(l)&&(o[l]=c);o[e]=new Date(i).toISOString();let a=(r.wanted??[]).filter(l=>l!==e&&s.has(l));B(t,{...r,popped:o,wanted:a})}function yn(t,e){let n=A(t);B(t,{...n,wanted:[...(n.wanted??[]).filter(i=>i!==e),e]})}function Ga(t,e=Date.now()){B(t,{...A(t),popped:{},passAt:new Date(e).toISOString()})}Zr();_t();_t();var Ya=["done","skipped"],Ii=1e3;function Ei(t){t.exec(`
1
+ import{a as Re}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-7LN4VKDU.js";import{a as ne}from"./chunk-IMLAPB7G.js";import{q as Kt}from"./chunk-S2GAEH2F.js";import{f as Yt,g as Ae,i as V,j as q,l as Zt}from"./chunk-AKWBDCMU.js";import{b as Jt}from"./chunk-7DYVNET6.js";import{t as Xt,u as Gt}from"./chunk-6VP2KMUM.js";import{d as Ht,e as zt}from"./chunk-AQASR6KR.js";import{X as Nt,Z as te,_ as ve,aa as $e,b as Se}from"./chunk-7V73QTQ7.js";import{a as Vt,b as qt,d as Bt}from"./chunk-Y4CYQV7G.js";import{a as Lt,b as Ot}from"./chunk-SHEUCITK.js";import{g as Mt,h as jt,i as Wt,k as Ft,l as Ut}from"./chunk-6AUWEL6V.js";import{q as Pt}from"./chunk-DBJUGKX2.js";import{a as Ct,b as Dt}from"./chunk-JIJDBCV7.js";import{Aa as Tt,B as $t,C as At,D as Rt,E as _t,ka as xe,n as ee,o as St,p as vt,q as Jr,ra as It,sa as Et}from"./chunk-HJCFLGVT.js";import{a as we,h as Yr}from"./chunk-BRK6M6LA.js";import{f as ke,n as Zr}from"./chunk-UIBUZ2N3.js";import{existsSync as Qr,readdirSync as ei,readFileSync as ti,statSync as ni}from"fs";import{resolve as ri}from"path";function Qt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],l=a.filter(f=>n-f.at<=r),c=a.filter(f=>n-f.at>r&&n-f.at<=r*2),u=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((o,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[o.state]-l[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var re=new Map;function Ea(t,e=1e3){if(!Qr(t))return[];let n=ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ri(t,s);return{path:o,mtime:ni(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of re.keys())i.has(s)||re.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=re.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let l=ii(s,o);re.set(s,{mtime:o,summary:l}),l&&r.push(l)}return r}function ii(t,e){try{let n=ti(t,"utf-8").split(`
2
+ `).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),l=a.status??a.run?.status;if(l){s=l;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var si={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},oi=(t,e,n)=>{try{return Pt(t,e,n)}catch{return null}},en=864e5;function Pa(t){let e=t.now??Date.now(),n={...si,...t.thresholds},i=t.nextFire??oi,r=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",u=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?_e(a.nextRun)??_e(i(a.schedule,new Date(e),c)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:pi(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:tn(u),sampledRuns:l.length,flags:[],attention:null};p.flags=nn(p,u,a.schedule,c,null,e,n,i),r.push(rn(p))}let s=new Map(Qt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let l=o.get(a.workflowId);l?l.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(I=>I.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((I,ye)=>ye.at-I.at),g=p.map(I=>({at:I.at,status:ci(I.status)})),f=g[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",C=typeof c.timezone=="string"?c.timezone:"UTC",M={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(b,k.text),timezone:C}:{event:$(typeof c.event=="string"?c.event:"",k.text),filters:di(c.filter,a)},agent:ui(a),enabled:d,state:u,nextRunAt:h&&d&&b?_e(i(b,new Date(e),C)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let I=g.find(ye=>ye.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:tn(g),sampledRuns:p.length,flags:[],attention:null},Q=Date.parse(a.updated||a.created||"");M.flags=h?nn(M,g,b,C,Number.isFinite(Q)?Q:null,e,n,i):ai(M,s.get(a.id)?.state==="dormant",Number.isFinite(Q)?Q:null,e,n),r.push(rn(M))}return r.sort(li).slice(0,k.routines)}function tn(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 nn(t,e,n,i,r,s,o,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=on(c,r,s,o);return p&&l.push(p),l}if(t.consecutiveFailures>=o.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${o.missedFires} scheduled fires missed`}),l}function ai(t,e,n,i,r){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=on(o,n,i,r);return a&&s.push(a),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===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 on(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*en?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/en)} days`:"Disabled and never ran"}}function rn(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 sn={critical:0,warning:1,info:2};function li(t,e){let n=t.attention?sn[t.attention]:3,i=e.attention?sn[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ci(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 ui(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function di(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${r}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function _e(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function pi(t,e){return t===void 0?void 0:$(t,e)}import{mkdirSync as gi,readFileSync as fi,renameSync as mi,writeFileSync as hi}from"fs";import{resolve as bi}from"path";function an(t){return bi(Ae(t),"_state.json")}function A(t){try{let e=JSON.parse(fi(an(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 B(t,e){gi(Ae(t),{recursive:!0});let n=an(t),i=`${n}.${process.pid}.tmp`;hi(i,JSON.stringify(e,null,2)+`
3
+ `),mi(i,n)}function ln(t,e,n,i=Date.now()){let r=A(t),s={};for(let[o,a]of Object.entries(r.snoozed))Date.parse(a)>i&&(s[o]=a);s[e]=n.toISOString(),B(t,{...r,snoozed:s})}function ja(t,e){B(t,{...A(t),lastDigest:e})}function cn(t,e,n,i=Date.now()){let r=A(t),s=new Set(n),o={};for(let[l,c]of Object.entries(r.popped??{}))s.has(l)&&(o[l]=c);o[e]=new Date(i).toISOString();let a=(r.wanted??[]).filter(l=>l!==e&&s.has(l));B(t,{...r,popped:o,wanted:a})}function un(t,e){let n=A(t);B(t,{...n,wanted:[...(n.wanted??[]).filter(i=>i!==e),e]})}function Wa(t,e=Date.now()){B(t,{...A(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as H,readdirSync as Pi,readFileSync as Ni}from"fs";import{resolve as R}from"path";import{randomBytes as gn}from"crypto";import{existsSync as wi,mkdirSync as ki,readdirSync as xi,readFileSync as Si,renameSync as fn,unlinkSync as vi,writeFileSync as $i}from"fs";import{resolve as mn}from"path";function dn(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var yi=t=>t.trim().split(`
4
+ `).pop()?.slice(0,300)||"no output";async function pn(t,e,n,i=Re){let r=await i(t.bin,[...dn(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${yi(r.stderr||r.stdout)}`}}async function Va(t,e,n,i,r=Re){return(await r(t.bin,[...dn(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var Ai=2e3,Ri=t=>pn(t.wacli,t.to,t.text);function Ie(t){return mn(t,".agentx","whatsapp-triage","drafts")}var _i=t=>/^[a-z0-9-]{8,64}$/.test(t),ie=(t,e)=>mn(Ie(t),`${e}.json`);function hn(t,e){ki(Ie(t),{recursive:!0});let n=ie(t,e.id),i=`${n}.${process.pid}.tmp`;$i(i,JSON.stringify(e,null,2)+`
5
+ `,{mode:384}),fn(i,n)}function Ga(t,e,n=Date.now()){let i=e.text.trim().slice(0,Ai);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${gn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return hn(t,r),r}function se(t,e){if(!_i(e))return null;try{return JSON.parse(Si(ie(t,e),"utf-8"))}catch{return null}}function bn(t,e){let n=Ie(t);return wi(n)?xi(n).filter(i=>i.endsWith(".json")).map(i=>se(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function yn(t,e,n,i={}){let r=se(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${ie(t,e)}.${process.pid}.${gn(3).toString("hex")}.claim`;try{fn(ie(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(i.send??Ri)(r).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}hn(t,o);try{vi(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}Zr();_t();_t();var Ya=["done","skipped"],Ii=1e3;function Ei(t){t.exec(`
6
6
  CREATE TABLE IF NOT EXISTS request_plans (
7
7
  request_id TEXT PRIMARY KEY,
8
8
  created_by TEXT NOT NULL,
@@ -52,7 +52,7 @@ import{a as Re}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-7LN4VKDU.js"
52
52
  CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
53
53
  `)}function kn(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function Ee(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 wn(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var Ti={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"},oe=class{constructor(e){this.db=e;Ei(e)}create(e,n,i,r){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),o=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
54
54
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at)
55
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,r),i.forEach((a,l)=>{let c=l===0,u=c&&a.agentId===n&&a.kind!=="message";o.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,c?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,u?r:null,r)}),this.event(e,null,"created",`${i.length} steps, written by ${n}`,r)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?Ee(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(wn)}step(e,n){let i=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return i?wn(i):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(Ee)}updateStep(e,n,i){let r=[],s=[];for(let[o,a]of Object.entries(i)){let l=Ti[o];!l||a===void 0||(r.push(`${l} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}r.length&&this.db.prepare(`UPDATE request_plan_steps SET ${r.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,e,n)}finish(e,n,i){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,i,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(Ee)}event(e,n,i,r,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,i,r.replace(/\s+/g," ").trim().slice(0,Ii))}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at, rowid LIMIT ?").all(e,n).map(i=>({requestId:i.request_id,step:i.step??null,at:i.at,kind:i.kind,detail:i.detail}))}},Za=$t;import{existsSync as Ci,readFileSync as Di}from"fs";Tt();Yr();function xn(t){let e=Ct(t),n={};if(Ci(e))try{n=It(JSON.parse(Di(e,"utf-8")))}catch{n={}}let i=xe.safeParse(n?.requests);return i.success?i.data:xe.parse(void 0)}async function il(t,e={}){let n=(t.channels??[]).filter(i=>!we.has(i.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(i=>`"${i}"`).join(", ")}: use ${[...we].join(", ")}`}:Dt(i=>{let r=i.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays"])t[s]!==void 0&&(r[s]=t[s]);if(t.plans){let s=r.plans??={};for(let o of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents"])t.plans[o]!==void 0&&(s[o]=t.plans[o])}},{configPath:e.configPath,reload:e.reload})}var $n=["card","schedule","memory","wiki","whatsapp","request"],Li=280;function N(t,e=Li){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 R(t.configPath);let e=[R(t.root,"agentx.json"),R(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function Ce(t){return t.wikiDir?R(t.wikiDir):R(t.root,".agentx","wiki")}function Oi(t){return q(t.root,"pending").map(Mi)}function Mi(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:N([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function ji(t){let e=Te(t);if(!H(e))return[];let n;try{n=JSON.parse(Ni(e,"utf-8"))}catch{return[]}let i=new Date(t.now??Date.now()),r=[];for(let[s,o]of Object.entries(n?.crons??{})){let a=o?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let l=o.timezone||"UTC",c=o.schedule?Mt(o.schedule):"",u=o.schedule?`${c.charAt(0).toLowerCase()}${c.slice(1)} (${o.schedule})`:"no schedule",d=String(o.prompt??o.command??""),p=a.action==="create";r.push({key:`schedule:${s}`,kind:"schedule",title:p?`New schedule "${s}" for ${o.agent??"an agent"}`:`Delete schedule "${s}"`,ask:p?`Let ${o.agent??"the agent"} run this ${u}?`:`Remove the schedule "${s}" (${u})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:N(`${d}${p&&o.schedule?` \xB7 first run ${Wt(jt(o.schedule,l,i),l)}`:""}`),more:"agentx schedule list"})}return r}function An(t){let e=R(t,".agentx","memory");return H(e)?Pi(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Wi(t){let e=An(t.root);if(e.length===0)return[];let n=new Se(t.root),i=[];for(let r of e)for(let s of n.held(r))i.push({key:`memory:${r}/${s.id}`,kind:"memory",title:`Fact ${r} learned from ${s.source.channel}`,ask:`Let ${r} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:r,created_at:s.createdAt,detail:N(s.content),more:`agentx memory facts held --agent ${r}`});return i}function Fi(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 Ui(t){return zt(Ce(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:N(`${Fi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function Vi(t){return gn(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:N(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function z(t){if(t.requests)return t.requests;if(R(t.root)!==process.cwd()||!H(R(t.root,".agentx","db.sqlite")))return null;let e=ke({quiet:!0});if(!e)return null;let n=Sn.get(e);return!n&&!At(e)?null:(n||Sn.set(e,n=new Rt(e)),n)}var Sn=new WeakMap;function wl(t){if(t.plans)return t.plans;if(t.requests||R(t.root)!==process.cwd()||!H(R(t.root,".agentx","db.sqlite")))return null;let e=ke({quiet:!0});if(!e||!kn(e))return null;let n=vn.get(e);return n||vn.set(e,n=new oe(e)),n}var vn=new WeakMap;function qi(t){let e=z(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:`Request not finished: ${N(n.text,80)}`,ask:`Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:N(`${n.attentionReason??"It needs attention"}. Asked on ${n.channel}: ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var Rn={card:Oi,schedule:ji,memory:Wi,wiki:Ui,whatsapp:Vi,request:qi};function Bi(t,e){let n=t.expires?Date.parse(t.expires):1/0,i=e.expires?Date.parse(e.expires):1/0;return n!==i?n-i:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function kl(t,e={}){let n=t.now??Date.now(),{snoozed:i}=A(t.root),r=[],s=[],o=0;for(let a of e.kinds??$n){let l;try{l=Rn[a](t)}catch(c){s.push({kind:a,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let u=i[c.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){o++;continue}c.snoozed_until=u}r.push(c)}}return r.sort(Bi),{items:r,snoozed:o,errors:s}}function Hi(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),i=t.slice(e+1);return!$n.includes(n)||!i?null:{kind:n,ref:i}}function zi(t,e,n){switch(e){case"card":return V(t.root,n)?.status==="pending";case"wiki":return Ht(Ce(t),n)?.status==="pending";case"whatsapp":return se(t.root,n)?.status==="pending";default:return Rn[e](t).some(i=>i.key===`${e}:${n}`)}}async function _n(t,e,n,i={}){let r=Hi(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:o}=r,a=t.now??Date.now(),l=i.by??"operator";if(n==="later"){if(!zi(t,s,o))return{ok:!1,error:`nothing waiting for "${e}"`};let u=i.laterHours&&i.laterHours>0?i.laterHours:24,d=new Date(a+u*36e5);return hn(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let c=n==="yes";switch(s){case"card":{let u=Zt(t.root,o,c?"yes":"no",{by:l,note:i.note,now:a,choice:i.choice,text:i.text});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${c?"yes":"no"}${u.card.choice?` (${u.card.choice})`:""}`}:u}case"schedule":{let u=await(c?Ft:Ut)(o,{configPath:Te(t),reload:t.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=o.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let d=o.slice(0,u),p=o.slice(u+1);if(!An(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let g=new Se(t.root);return g.held(d).some(f=>f.id===p)?(g.review(d,p,c?"approved":"rejected",l),{ok:!0,message:`${e} ${c?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let u=Ce(t),d=c?Xt(u,o,{by:l,force:i.force,now:a}):Gt(u,o,{by:l,reason:i.note,now:a});return d.ok?{ok:!0,message:c?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}case"whatsapp":{let u=await fn(t.root,o,c?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return u.ok?{ok:!0,message:c?`${e}: sent to ${u.draft.chat_name||u.draft.to}`:`${e}: dropped, nothing sent`}:u}case"request":{let u=z(t),d=u?.get(o);return!u||!d||d.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:c?xn(Te(t)).enabled?(u.requestPickup(o,a),{ok:!0,message:`${e}: ${d.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."}:(u.close(o,"dropped",i.note?.trim()||`dropped by ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var In=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function Sl(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/requests"||t.startsWith("/requests/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")}function vl(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"}function $l(t){return In.has(t)}function Al(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(In.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 Rl(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let i of t.mesh?.peers||[])i.token&&n.add(i.token);return n}function _l(t,e,n=process.env){let i=s=>s.replace(/\/+$/,"");return(e===i(t.daemonUrl)?t.token:t.daemons.find(s=>i(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function ae(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Xi(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Gi(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function El(t,e=Gi()){let n=ae(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=Xi(n),s=[ae(t.host),ae(t["x-forwarded-host"])].filter(Boolean).map(o=>o.toLowerCase());return r&&s.includes(r)?"same-origin":"foreign"}let i=ae(t["sec-fetch-site"]).toLowerCase();return i==="cross-site"||i==="same-site"?"foreign":"none"}function Tl(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as Qn,mkdirSync as vs,readFileSync as $s,renameSync as As,writeFileSync as Rs}from"fs";import{homedir as _s}from"os";import{dirname as Is,join as Es}from"path";import{execFile as ss,execFileSync as os}from"child_process";import{execFileSync as Ki}from"child_process";import{existsSync as Tn,mkdirSync as Ji,readdirSync as Yi,readFileSync as Cn,renameSync as Zi,writeFileSync as Qi}from"fs";import{homedir as Dn}from"os";import{join as Pe}from"path";var S="siri:",Pn="com.apple.ttsbundle.gryphon-neural_",Nn=t=>!!t&&t.startsWith(Pn),es=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],ts=()=>{try{return Ki("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},De;function Ne(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&De!==void 0)return De;let{platform:n=process.platform,exists:i=Tn,prefDomain:r=ts}=t,s=n==="darwin"&&es.every(o=>i(o))&&r();return e||(De=s),s}var Ln=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],On={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"},Le=t=>On[t.toLowerCase()]??null;function le(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 ns=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function rs(t){let e=new Map;for(let n of t)for(let[,i,r,s]of n.matchAll(ns)){let o=`${i}-${r}`,a=`${Pn}${s}_${o}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:o,quality:"premium",gender:On[s]??null,siri:!0})}return[...e.values()]}function ce(t=Ln,e={}){if(!Ne(e))return[];let n=[];for(let i of t){let r;try{r=Yi(i)}catch{continue}for(let s of r)try{n.push(Cn(Pe(i,s,"Info.plist"),"latin1"))}catch{}}return rs(n)}var En=`#!/bin/sh
55
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,r),i.forEach((a,l)=>{let c=l===0,u=c&&a.agentId===n&&a.kind!=="message";o.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,c?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,u?r:null,r)}),this.event(e,null,"created",`${i.length} steps, written by ${n}`,r)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?Ee(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(wn)}step(e,n){let i=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return i?wn(i):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(Ee)}updateStep(e,n,i){let r=[],s=[];for(let[o,a]of Object.entries(i)){let l=Ti[o];!l||a===void 0||(r.push(`${l} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}r.length&&this.db.prepare(`UPDATE request_plan_steps SET ${r.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,e,n)}finish(e,n,i){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,i,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(Ee)}event(e,n,i,r,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,i,r.replace(/\s+/g," ").trim().slice(0,Ii))}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at, rowid LIMIT ?").all(e,n).map(i=>({requestId:i.request_id,step:i.step??null,at:i.at,kind:i.kind,detail:i.detail}))}},Za=$t;import{existsSync as Ci,readFileSync as Di}from"fs";Tt();Yr();function xn(t){let e=Ct(t),n={};if(Ci(e))try{n=It(JSON.parse(Di(e,"utf-8")))}catch{n={}}let i=xe.safeParse(n?.requests);return i.success?i.data:xe.parse(void 0)}async function il(t,e={}){let n=(t.channels??[]).filter(i=>!we.has(i.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(i=>`"${i}"`).join(", ")}: use ${[...we].join(", ")}`}:Dt(i=>{let r=i.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays"])t[s]!==void 0&&(r[s]=t[s]);if(t.plans){let s=r.plans??={};for(let o of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents"])t.plans[o]!==void 0&&(s[o]=t.plans[o])}},{configPath:e.configPath,reload:e.reload})}var $n=["card","schedule","memory","wiki","whatsapp","request"],Li=280;function N(t,e=Li){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 R(t.configPath);let e=[R(t.root,"agentx.json"),R(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function Ce(t){return t.wikiDir?R(t.wikiDir):R(t.root,".agentx","wiki")}function Oi(t){return q(t.root,"pending").map(Mi)}function Mi(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:N([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function ji(t){let e=Te(t);if(!H(e))return[];let n;try{n=JSON.parse(Ni(e,"utf-8"))}catch{return[]}let i=new Date(t.now??Date.now()),r=[];for(let[s,o]of Object.entries(n?.crons??{})){let a=o?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let l=o.timezone||"UTC",c=o.schedule?Mt(o.schedule):"",u=o.schedule?`${c.charAt(0).toLowerCase()}${c.slice(1)} (${o.schedule})`:"no schedule",d=String(o.prompt??o.command??""),p=a.action==="create";r.push({key:`schedule:${s}`,kind:"schedule",title:p?`New schedule "${s}" for ${o.agent??"an agent"}`:`Delete schedule "${s}"`,ask:p?`Let ${o.agent??"the agent"} run this ${u}?`:`Remove the schedule "${s}" (${u})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:N(`${d}${p&&o.schedule?` \xB7 first run ${Wt(jt(o.schedule,l,i),l)}`:""}`),more:"agentx schedule list"})}return r}function An(t){let e=R(t,".agentx","memory");return H(e)?Pi(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Wi(t){let e=An(t.root);if(e.length===0)return[];let n=new Se(t.root),i=[];for(let r of e)for(let s of n.held(r))i.push({key:`memory:${r}/${s.id}`,kind:"memory",title:`Fact ${r} learned from ${s.source.channel}`,ask:`Let ${r} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:r,created_at:s.createdAt,detail:N(s.content),more:`agentx memory facts held --agent ${r}`});return i}function Fi(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 Ui(t){return zt(Ce(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:N(`${Fi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function Vi(t){return bn(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:N(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function z(t){if(t.requests)return t.requests;if(R(t.root)!==process.cwd()||!H(R(t.root,".agentx","db.sqlite")))return null;let e=ke({quiet:!0});if(!e)return null;let n=Sn.get(e);return!n&&!At(e)?null:(n||Sn.set(e,n=new Rt(e)),n)}var Sn=new WeakMap;function wl(t){if(t.plans)return t.plans;if(t.requests||R(t.root)!==process.cwd()||!H(R(t.root,".agentx","db.sqlite")))return null;let e=ke({quiet:!0});if(!e||!kn(e))return null;let n=vn.get(e);return n||vn.set(e,n=new oe(e)),n}var vn=new WeakMap;function qi(t){let e=z(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:`Request not finished: ${N(n.text,80)}`,ask:`Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:N(`${n.attentionReason??"It needs attention"}. Asked on ${n.channel}: ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var Rn={card:Oi,schedule:ji,memory:Wi,wiki:Ui,whatsapp:Vi,request:qi};function Bi(t,e){let n=t.expires?Date.parse(t.expires):1/0,i=e.expires?Date.parse(e.expires):1/0;return n!==i?n-i:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function kl(t,e={}){let n=t.now??Date.now(),{snoozed:i}=A(t.root),r=[],s=[],o=0;for(let a of e.kinds??$n){let l;try{l=Rn[a](t)}catch(c){s.push({kind:a,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let u=i[c.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){o++;continue}c.snoozed_until=u}r.push(c)}}return r.sort(Bi),{items:r,snoozed:o,errors:s}}function Hi(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),i=t.slice(e+1);return!$n.includes(n)||!i?null:{kind:n,ref:i}}function zi(t,e,n){switch(e){case"card":return V(t.root,n)?.status==="pending";case"wiki":return Ht(Ce(t),n)?.status==="pending";case"whatsapp":return se(t.root,n)?.status==="pending";default:return Rn[e](t).some(i=>i.key===`${e}:${n}`)}}async function _n(t,e,n,i={}){let r=Hi(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:o}=r,a=t.now??Date.now(),l=i.by??"operator";if(n==="later"){if(!zi(t,s,o))return{ok:!1,error:`nothing waiting for "${e}"`};let u=i.laterHours&&i.laterHours>0?i.laterHours:24,d=new Date(a+u*36e5);return ln(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let c=n==="yes";switch(s){case"card":{let u=Zt(t.root,o,c?"yes":"no",{by:l,note:i.note,now:a,choice:i.choice,text:i.text});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${c?"yes":"no"}${u.card.choice?` (${u.card.choice})`:""}`}:u}case"schedule":{let u=await(c?Ft:Ut)(o,{configPath:Te(t),reload:t.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=o.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let d=o.slice(0,u),p=o.slice(u+1);if(!An(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let g=new Se(t.root);return g.held(d).some(f=>f.id===p)?(g.review(d,p,c?"approved":"rejected",l),{ok:!0,message:`${e} ${c?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let u=Ce(t),d=c?Xt(u,o,{by:l,force:i.force,now:a}):Gt(u,o,{by:l,reason:i.note,now:a});return d.ok?{ok:!0,message:c?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}case"whatsapp":{let u=await yn(t.root,o,c?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return u.ok?{ok:!0,message:c?`${e}: sent to ${u.draft.chat_name||u.draft.to}`:`${e}: dropped, nothing sent`}:u}case"request":{let u=z(t),d=u?.get(o);return!u||!d||d.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:c?xn(Te(t)).enabled?(u.requestPickup(o,a),{ok:!0,message:`${e}: ${d.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."}:(u.close(o,"dropped",i.note?.trim()||`dropped by ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var In=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function Sl(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/requests"||t.startsWith("/requests/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")}function vl(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"}function $l(t){return In.has(t)}function Al(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(In.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 Rl(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let i of t.mesh?.peers||[])i.token&&n.add(i.token);return n}function _l(t,e,n=process.env){let i=s=>s.replace(/\/+$/,"");return(e===i(t.daemonUrl)?t.token:t.daemons.find(s=>i(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function ae(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Xi(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Gi(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function El(t,e=Gi()){let n=ae(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=Xi(n),s=[ae(t.host),ae(t["x-forwarded-host"])].filter(Boolean).map(o=>o.toLowerCase());return r&&s.includes(r)?"same-origin":"foreign"}let i=ae(t["sec-fetch-site"]).toLowerCase();return i==="cross-site"||i==="same-site"?"foreign":"none"}function Tl(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as Qn,mkdirSync as vs,readFileSync as $s,renameSync as As,writeFileSync as Rs}from"fs";import{homedir as _s}from"os";import{dirname as Is,join as Es}from"path";import{execFile as ss,execFileSync as os}from"child_process";import{execFileSync as Ki}from"child_process";import{existsSync as Tn,mkdirSync as Ji,readdirSync as Yi,readFileSync as Cn,renameSync as Zi,writeFileSync as Qi}from"fs";import{homedir as Dn}from"os";import{join as Pe}from"path";var S="siri:",Pn="com.apple.ttsbundle.gryphon-neural_",Nn=t=>!!t&&t.startsWith(Pn),es=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],ts=()=>{try{return Ki("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},De;function Ne(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&De!==void 0)return De;let{platform:n=process.platform,exists:i=Tn,prefDomain:r=ts}=t,s=n==="darwin"&&es.every(o=>i(o))&&r();return e||(De=s),s}var Ln=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],On={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"},Le=t=>On[t.toLowerCase()]??null;function le(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 ns=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function rs(t){let e=new Map;for(let n of t)for(let[,i,r,s]of n.matchAll(ns)){let o=`${i}-${r}`,a=`${Pn}${s}_${o}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:o,quality:"premium",gender:On[s]??null,siri:!0})}return[...e.values()]}function ce(t=Ln,e={}){if(!Ne(e))return[];let n=[];for(let i of t){let r;try{r=Yi(i)}catch{continue}for(let s of r)try{n.push(Cn(Pe(i,s,"Info.plist"),"latin1"))}catch{}}return rs(n)}var En=`#!/bin/sh
56
56
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
57
57
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
58
58
  # the OS default for it; any other id is
@@ -509,7 +509,7 @@ function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
509
509
 
510
510
  Message (edit it if you like):`:`${ot(t)}
511
511
 
512
- Message (edit it if you like):`,d=await n("/usr/bin/osascript",kr(s,c,o?["Cancel","Send"]:["Not now","No","Send"],i,Bt(t.draft,o)),r),p=d.ok?xr(d.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...o?{choice:o}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",kr(s,ot(t),["Not now","No","Yes"],i),r),l=a.ok?xr(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var lt=24*36e5,at=!1,Po=10*6e4,$r=-1/0;function Ar(t){let e=t.now??Date.now(),{popped:n={},snoozed:i,passAt:r,wanted:s=[]}=A(t.root),o=r?Date.parse(r):NaN,a=q(t.root,"pending").filter(c=>Date.parse(c.expires)>e),l=a.find(c=>s.includes(`card:${c.id}`));if(l)return l;for(let c of a){let u=`card:${c.id}`;if(n[u])continue;let d=i[u];if(d&&Date.parse(d)>e)continue;let p=Date.parse(c.created_at);if(!(e-p>lt&&!(p<=o)))return c}return null}function Rr(t){try{return z(t)?.listByState("needs_attention")??[]}catch{return[]}}function No(t){let e=t.now??Date.now(),{popped:n={},snoozed:i}=A(t.root);return Rr(t).find(r=>{let s=`request:${r.id}`,o=i[s];return!n[s]&&!(o&&Date.parse(o)>e)&&e-r.updatedAt<=lt})??null}function Lo(t,e){return{id:t.id,title:nt(t.text,Yt.title),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+lt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function eu(t){let{ctx:e,settings:n,log:i}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(at)return"busy";let r=Ar(e)?null:No(e),s=r?Lo(r,e.now??Date.now()):Ar(e);if(!s)return"none";let o=(t.focus??Lt)();if(o.active)return"held";at=!0;let a=`${r?"request":"card"}:${s.id}`;try{let l=[...q(e.root,"pending").map(h=>`card:${h.id}`),...Rr(e).map(h=>`request:${h.id}`)];bn(e.root,a,l,e.now),i(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),u=!!r&&c-$r<Po;r&&n.speak&&($r=c);let d=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),p=await(t.show??vr)(s,u?{...n,speak:!1}:n,{from:d,speak:t.speak});if(p.action==="dismiss")return i(`[approvals] popup: ${a} left waiting: ${p.why??"no answer"} (${Ot(o)} when shown)`),"shown";if(!(r?z(e)?.get(r.id)?.state==="needs_attention":V(e.root,s.id)?.status==="pending"))return i(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await _n(e,a,p.action,{by:"operator (popup)",...p.action==="yes"?{choice:p.choice,text:p.text}:{}});return i(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return i(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{at=!1}}function tu(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let i=e.startsWith("card:")?V(t.root,e.slice(5)):null;return i?i.status!=="pending"?{ok:!1,error:`${e} is already ${i.status}`}:(yn(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{closeSync as K,createReadStream as Oo,fstatSync as Mo,openSync as jo,realpathSync as _r}from"fs";import{isAbsolute as Wo,resolve as Ir,sep as Er}from"path";var au="/app-files",Fo=/^[A-Za-z0-9_.:-]{1,64}$/;function Uo(t,e,n=process.cwd()){if(!e||e.length>te.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 ${$e}/ first`};if(!ve(e))return{ok:!1,status:415,error:"this type of file is not served"};let i;try{i=_r(Ir(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let r;try{r=_r(Wo(e)?e:Ir(i,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!r.startsWith(i+Er))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${$e}/ first`};let s=ve(r);return s?{ok:!0,path:r,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Vo(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 qo(t,e,n){return{"Content-Type":t,"Content-Disposition":Vo(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 Bo(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let i,r;return n[1]?(i=Number(n[1]),r=n[2]?Math.min(Number(n[2]),e-1):e-1):(i=Math.max(0,e-Number(n[2])),r=e-1),i>r||i>=e?"unsatisfiable":{start:i,end:r}}function lu(t,e,n,i){let r=(C,M)=>{e.writeHead(C,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(M))};if(t.method!=="GET"&&t.method!=="HEAD")return r(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",o=n.searchParams.get("file")||"";if(!Fo.test(s))return r(400,{error:"bad agent id"});let a=i.workspaceOf(s);if(!a)return r(404,{error:`no agent "${s}" on this computer`});let l=Uo(a,o,i.cwd);if(!l.ok)return i.log?.(`[app-files] refused ${JSON.stringify(o.slice(0,200))} from ${s}: ${l.error}`),r(l.status,{error:l.error});let c;try{c=jo(l.path,"r")}catch{return r(404,{error:"file not found"})}let u;try{let C=Mo(c);if(!C.isFile())return K(c),r(404,{error:"not a file"});u=C.size}catch{return K(c),r(404,{error:"file not found"})}if(u>te.bytes)return K(c),r(413,{error:`the file is larger than ${te.bytes/1024/1024} MB`});let d=l.path.split(Er).pop()||"file",p=qo(l.mime,d,l.kind),g=Bo(t.headers.range,u);if(g==="unsatisfiable"){K(c),e.writeHead(416,{...p,"Content-Range":`bytes */${u}`}),e.end();return}let{start:f,end:h}=g??{start:0,end:u-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(u?h-f+1:0),...g?{"Content-Range":`bytes ${f}-${h}/${u}`}:{}}),t.method==="HEAD"||u===0){K(c),e.end();return}let b=Oo("",{fd:c,start:f,end:h,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as J}from"child_process";import{readFileSync as Ho,writeFileSync as zo}from"fs";import{tmpdir as Xo}from"os";import{join as Go}from"path";St();var Tr=t=>t&&t!==1?Math.round(175*t):null,me=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function Ko(){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=Ho(t,"utf8").trim();if(e)return e}catch{}return null}function bu(t=Ko()){let e=0;return async(n,i)=>{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 r=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",...me(n.voice.rate)?{voice_settings:{speed:me(n.voice.rate)}}:{}}),signal:i});if(!r.ok)throw new Error(`ElevenLabs ${r.status}: ${(await r.text()).slice(0,160)}`);let s=Go(Xo(),`agentx-say-${process.pid}-${++e}.mp3`);return zo(s,Buffer.from(await r.arrayBuffer())),s}catch(r){if(i.aborted||!n.voice.fallback)throw r;return L(`elevenlabs:${String(r?.message??r).slice(0,40)}`,`[voice] ElevenLabs failed (${String(r?.message??r).slice(0,160)}); speaking with the system voice`),null}}}function Cr(t,e){let n=t.languages&&ee(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Jo=(t,e="")=>{let n=Cr(t,e),i=Tr(t.rate);return[...n&&!Nn(n)?["-v",n]:[],...i?["-r",String(i)]:[]]};function Yo(t,e,n){if(!n)return["say",Jo(t,e)];let i=Cr(t,e);return["/bin/sh",[n,...i?[i]:[]]]}function yu(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function wu(t=ct()){if(t)try{J("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function ku(t=ct()){if(t)try{J("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function ct(t={},e){if(!Ne(t))return null;try{return Mn(e)}catch(n){return L("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
512
+ Message (edit it if you like):`,d=await n("/usr/bin/osascript",kr(s,c,o?["Cancel","Send"]:["Not now","No","Send"],i,Bt(t.draft,o)),r),p=d.ok?xr(d.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...o?{choice:o}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",kr(s,ot(t),["Not now","No","Yes"],i),r),l=a.ok?xr(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var lt=24*36e5,at=!1,Po=10*6e4,$r=-1/0;function Ar(t){let e=t.now??Date.now(),{popped:n={},snoozed:i,passAt:r,wanted:s=[]}=A(t.root),o=r?Date.parse(r):NaN,a=q(t.root,"pending").filter(c=>Date.parse(c.expires)>e),l=a.find(c=>s.includes(`card:${c.id}`));if(l)return l;for(let c of a){let u=`card:${c.id}`;if(n[u])continue;let d=i[u];if(d&&Date.parse(d)>e)continue;let p=Date.parse(c.created_at);if(!(e-p>lt&&!(p<=o)))return c}return null}function Rr(t){try{return z(t)?.listByState("needs_attention")??[]}catch{return[]}}function No(t){let e=t.now??Date.now(),{popped:n={},snoozed:i}=A(t.root);return Rr(t).find(r=>{let s=`request:${r.id}`,o=i[s];return!n[s]&&!(o&&Date.parse(o)>e)&&e-r.updatedAt<=lt})??null}function Lo(t,e){return{id:t.id,title:nt(t.text,Yt.title),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+lt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function eu(t){let{ctx:e,settings:n,log:i}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(at)return"busy";let r=Ar(e)?null:No(e),s=r?Lo(r,e.now??Date.now()):Ar(e);if(!s)return"none";let o=(t.focus??Lt)();if(o.active)return"held";at=!0;let a=`${r?"request":"card"}:${s.id}`;try{let l=[...q(e.root,"pending").map(h=>`card:${h.id}`),...Rr(e).map(h=>`request:${h.id}`)];cn(e.root,a,l,e.now),i(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),u=!!r&&c-$r<Po;r&&n.speak&&($r=c);let d=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),p=await(t.show??vr)(s,u?{...n,speak:!1}:n,{from:d,speak:t.speak});if(p.action==="dismiss")return i(`[approvals] popup: ${a} left waiting: ${p.why??"no answer"} (${Ot(o)} when shown)`),"shown";if(!(r?z(e)?.get(r.id)?.state==="needs_attention":V(e.root,s.id)?.status==="pending"))return i(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await _n(e,a,p.action,{by:"operator (popup)",...p.action==="yes"?{choice:p.choice,text:p.text}:{}});return i(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return i(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{at=!1}}function tu(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let i=e.startsWith("card:")?V(t.root,e.slice(5)):null;return i?i.status!=="pending"?{ok:!1,error:`${e} is already ${i.status}`}:(un(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{closeSync as K,createReadStream as Oo,fstatSync as Mo,openSync as jo,realpathSync as _r}from"fs";import{isAbsolute as Wo,resolve as Ir,sep as Er}from"path";var au="/app-files",Fo=/^[A-Za-z0-9_.:-]{1,64}$/;function Uo(t,e,n=process.cwd()){if(!e||e.length>te.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 ${$e}/ first`};if(!ve(e))return{ok:!1,status:415,error:"this type of file is not served"};let i;try{i=_r(Ir(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let r;try{r=_r(Wo(e)?e:Ir(i,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!r.startsWith(i+Er))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${$e}/ first`};let s=ve(r);return s?{ok:!0,path:r,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Vo(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 qo(t,e,n){return{"Content-Type":t,"Content-Disposition":Vo(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 Bo(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let i,r;return n[1]?(i=Number(n[1]),r=n[2]?Math.min(Number(n[2]),e-1):e-1):(i=Math.max(0,e-Number(n[2])),r=e-1),i>r||i>=e?"unsatisfiable":{start:i,end:r}}function lu(t,e,n,i){let r=(C,M)=>{e.writeHead(C,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(M))};if(t.method!=="GET"&&t.method!=="HEAD")return r(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",o=n.searchParams.get("file")||"";if(!Fo.test(s))return r(400,{error:"bad agent id"});let a=i.workspaceOf(s);if(!a)return r(404,{error:`no agent "${s}" on this computer`});let l=Uo(a,o,i.cwd);if(!l.ok)return i.log?.(`[app-files] refused ${JSON.stringify(o.slice(0,200))} from ${s}: ${l.error}`),r(l.status,{error:l.error});let c;try{c=jo(l.path,"r")}catch{return r(404,{error:"file not found"})}let u;try{let C=Mo(c);if(!C.isFile())return K(c),r(404,{error:"not a file"});u=C.size}catch{return K(c),r(404,{error:"file not found"})}if(u>te.bytes)return K(c),r(413,{error:`the file is larger than ${te.bytes/1024/1024} MB`});let d=l.path.split(Er).pop()||"file",p=qo(l.mime,d,l.kind),g=Bo(t.headers.range,u);if(g==="unsatisfiable"){K(c),e.writeHead(416,{...p,"Content-Range":`bytes */${u}`}),e.end();return}let{start:f,end:h}=g??{start:0,end:u-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(u?h-f+1:0),...g?{"Content-Range":`bytes ${f}-${h}/${u}`}:{}}),t.method==="HEAD"||u===0){K(c),e.end();return}let b=Oo("",{fd:c,start:f,end:h,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as J}from"child_process";import{readFileSync as Ho,writeFileSync as zo}from"fs";import{tmpdir as Xo}from"os";import{join as Go}from"path";St();var Tr=t=>t&&t!==1?Math.round(175*t):null,me=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function Ko(){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=Ho(t,"utf8").trim();if(e)return e}catch{}return null}function bu(t=Ko()){let e=0;return async(n,i)=>{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 r=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",...me(n.voice.rate)?{voice_settings:{speed:me(n.voice.rate)}}:{}}),signal:i});if(!r.ok)throw new Error(`ElevenLabs ${r.status}: ${(await r.text()).slice(0,160)}`);let s=Go(Xo(),`agentx-say-${process.pid}-${++e}.mp3`);return zo(s,Buffer.from(await r.arrayBuffer())),s}catch(r){if(i.aborted||!n.voice.fallback)throw r;return L(`elevenlabs:${String(r?.message??r).slice(0,40)}`,`[voice] ElevenLabs failed (${String(r?.message??r).slice(0,160)}); speaking with the system voice`),null}}}function Cr(t,e){let n=t.languages&&ee(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Jo=(t,e="")=>{let n=Cr(t,e),i=Tr(t.rate);return[...n&&!Nn(n)?["-v",n]:[],...i?["-r",String(i)]:[]]};function Yo(t,e,n){if(!n)return["say",Jo(t,e)];let i=Cr(t,e);return["/bin/sh",[n,...i?[i]:[]]]}function yu(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function wu(t=ct()){if(t)try{J("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function ku(t=ct()){if(t)try{J("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function ct(t={},e){if(!Ne(t))return null;try{return Mn(e)}catch(n){return L("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
513
513
  `)[0]}); Siri voices will not switch`),null}}var xu=(t,e)=>{if(!t){let[n,i]=Yo(e.voice,e.text,ct()),r=Tr(e.voice.rate),s=r?{...process.env,AGENTX_SAY_RATE:String(r)}:process.env,o=J(n,i,{stdio:["pipe","ignore","ignore"],env:s});return o.stdin?.on("error",()=>{}),o.stdin?.end(e.text),o}return process.platform==="darwin"?J("afplay",[t],{stdio:"ignore"}):J("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Dr}from"child_process";import{accessSync as Zo,constants as Qo,readFileSync as Pr}from"fs";import{homedir as ea}from"os";import{basename as F,delimiter as Nr,dirname as ta,extname as na,join as ut}from"path";var P={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Lr(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)>P.ms+2e3?{status:413,error:pt()}:null}var pt=()=>`The recording is longer than ${P.ms/6e4} minutes.`,ra={"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 Or(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return ra[e]??null}function Mr(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 gt(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 dt(t,e,n=process.env.PATH??""){let i=ea(),r=[ut(i,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(Nr).filter(Boolean)];for(let s of[e,...r.map(o=>ut(o,t))])if(s)try{return Zo(s,Qo.X_OK),s}catch{}return null}function _u(t){return{key:t,mlx:dt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:dt("whisper",process.env.AGENTX_WHISPER),ffmpeg:ia()}}var ia=()=>dt("ffmpeg",process.env.AGENTX_FFMPEG);async function jr(t,e){return e?sa(t,e):null}async function sa(t,e){let n=String(P.ms/1e3+5);try{let r=[...(await oa(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=r[r.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function Wr(t,e,n,i){let r=new FormData;r.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),r.set("file",new Blob([Pr(t)],{type:e}),F(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:r,signal:i??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let o=await s.json();if(typeof o.text!="string")throw new Error("ElevenLabs returned no text");return o.text.trim()}async function Fr(t,e,n,i,r){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",r,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",r,"--fp16","False"],o={...process.env,PATH:`${ta(i)}${Nr}${process.env.PATH??""}`};await aa(e,s,12e4,o);try{return Pr(ut(r,F(n,na(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function oa(t,e,n){return new Promise((i,r)=>{let s=Dr(t,e,{stdio:["ignore","ignore","pipe"]}),o="",a=setTimeout(()=>{s.kill("SIGKILL"),r(new Error(`${F(t)} took too long`))},n);s.stderr.on("data",l=>{o=(o+l).slice(-8192)}),s.on("error",l=>{clearTimeout(a),r(l)}),s.on("exit",l=>{clearTimeout(a),l===0?i(o):r(new Error(`${F(t)} exited ${l}`))})})}function aa(t,e,n,i=process.env){return new Promise((r,s)=>{let o=Dr(t,e,{stdio:["ignore","pipe","pipe"],env:i}),a="",l="",c=setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${F(t)} took longer than ${n/1e3}s`))},n);o.stdout.on("data",u=>{a.length<4096&&(a+=u)}),o.stderr.on("data",u=>{l.length<4096&&(l+=u)}),o.on("error",u=>{clearTimeout(c),s(u)}),o.on("exit",u=>{clearTimeout(c),u===0?r(a):s(new Error(`${F(t)} exited ${u}: ${l.trim().split(`
514
514
  `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as la,rm as ca,writeFile as ua}from"fs/promises";import{tmpdir as da}from"os";import{join as Ur}from"path";Jr();var pa=64*1024,ga=2,ft=0;function ju(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Wu(t,e,n,i){return t.method!=="POST"?y(e,405,{error:"POST"}):n==="/voice/transcribe"?fa(t,e,i):ba(t,e,i)}async function fa(t,e,n){let i=String(t.headers["content-type"]||""),r=Or(i);if(!r)return y(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=Lr(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),y(e,s.status,{error:s.error});let o=await Vr(t,P.bytes);if(!o)return y(e,413,{error:ka()});if(!o.length)return y(e,400,{error:"The recording is empty."});if(ft>=ga)return y(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),l=n.host(),c=Mr(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let d=n.nodeName?`on ${n.nodeName}`:"on this computer",p=c.length?"":" "+gt(a,l);return y(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${d} for voice input from the phone.${p}`,setup:!1})}if(!c.length)return y(e,503,{error:"Voice input isn't set up on this computer.",hint:gt(a,l),setup:!1});ft++;let u;try{let d=await la(Ur(da(),"agentx-phone-voice-"));try{u=await ma(d,`speech.${r}`,o,i,l,c,n)}finally{await ca(d,{recursive:!0,force:!0}).catch(()=>{})}}finally{ft--}y(e,u[0],u[1])}async function ma(t,e,n,i,r,s,o){let a=Ur(t,e);if(await ua(a,n,{mode:384}),r.ffmpeg){let c=await(o.measure??jr)(a,r.ffmpeg);if(c==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(c*1e3>P.ms+2e3)return[413,{error:pt()}]}let l=[];for(let c of s)try{let u=await ha(c,a,i,r,t,o);return o.log(`[voice] phone recording transcribed with ${c} (${Math.round(n.length/1024)} KB)`),u?[200,{text:u,engine:c}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:c}]}catch(u){let d=String(u?.message??u).split(`
515
515
  `)[0].slice(0,200);l.push(`${c}: ${d}`),o.log(`[voice] phone transcription with ${c} failed: ${d}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function ha(t,e,n,i,r,s){let o=s.engines?.[t];if(o)return o(e,n,i,r);if(t==="elevenlabs")return Wr(e,n,i.key);let a=t==="mlx-whisper"?i.mlx:i.whisper;return Fr(t,a,e,i.ffmpeg,r)}async function ba(t,e,n){let i=await Vr(t,pa);if(!i)return y(e,413,{error:"request too large"});let r;try{r=JSON.parse(i.toString("utf8")||"{}")}catch{return y(e,400,{error:"expected JSON"})}let s=typeof r?.agent=="string"?r.agent:"",o=typeof r?.peer=="string"&&r.peer?r.peer:void 0;if(!s)return y(e,400,{error:"agent is required"});let a=ya(typeof r?.text=="string"?r.text:"",n.spokenMaxChars?.());if(!a)return y(e,422,{error:"Nothing in this answer can be said aloud."});let l=n.pronounce?n.pronounce(a):a,c=n.voiceOf(s,o);if(!c)return y(e,404,{error:`Unknown agent: ${s}`});let u=(p,g=200)=>y(e,g,{fallback:"browser",reason:p,text:l});if(c.provider!=="elevenlabs")return u("This agent speaks with a system voice, which only plays on the computer.");let d=n.elevenLabsKey();if(!d)return u("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??wa)(d,c,l);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(l.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
@@ -528,5 +528,5 @@ Document the arguments, commands, or files the skill expects. Example:
528
528
  # Example invocation
529
529
  claude-code ${xt(t)} --arg value
530
530
  \`\`\`
531
- `}Tt();var zr={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Xr(t){return{...zr,...t??{},regions:{...t?.regions??{}},buffer:{...zr.buffer,...t?.buffer??{}}}}function td(t){try{return Xr(Et(t).screen)}catch{return Xr(void 0)}}var Ra=/^[a-z][\w-]*$/,Gr=["window","screen","menubar","notifications"];function Z(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var be=(t,e)=>Z(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Kr(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 nd(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=be(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=be(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=be(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Z(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Z(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!Ra.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete r[s]:r[s]=Kr(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=Z(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=Z(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=be(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!Gr.includes(i)&&!n.regions?.[i])try{Kr(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Gr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Qt as a,Ea as b,tt as c,Ks as d,Js as e,mc as f,hc as g,bc as h,ar as i,wc as j,xc as k,D as l,lr as m,k as n,Pa as o,Oa as p,xi as q,Va as r,fn as s,A as t,Xa as u,Ga as v,Ya as w,oe as x,Za as y,xn as z,il as A,z as B,wl as C,kl as D,_n as E,cr as F,$c as G,_c as H,vr as I,eu as J,tu as K,au as L,qo as M,lu as N,Sl as O,vl as P,$l as Q,Al as R,Rl as S,_l as T,El as U,Tl as V,Wl as W,Me as X,Fl as Y,Ul as Z,X as _,G as $,Ko as aa,bu as ba,yu as ca,wu as da,ku as ea,ct as fa,xu as ga,Fe as ha,Ue as ia,pe as ja,ms as ka,bs as la,zl as ma,qe as na,Be as oa,ys as pa,ws as qa,Xn as ra,Yn as sa,Xl as ta,Ss as ua,Gl as va,Ts as wa,Ps as xa,He as ya,Ls as za,Zn as Aa,P as Ba,Lr as Ca,Or as Da,Mr as Ea,_u as Fa,ia as Ga,Wr as Ha,Fr as Ia,ju as Ja,Wu as Ka,ka as La,Fu as Ma,Vr as Na,ge as Oa,oc as Pa,ir as Qa,ze as Ra,Qe as Sa,gc as Ta,Bu as Ua,Hu as Va,zu as Wa,Xu as Xa,Gu as Ya,Ku as Za,Ju as _a,Yu as $a,Zu as ab,zr as bb,Xr as cb,td as db,Gr as eb,nd as fb};
532
- //# sourceMappingURL=chunk-PNITKKDR.js.map
531
+ `}Tt();var zr={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Xr(t){return{...zr,...t??{},regions:{...t?.regions??{}},buffer:{...zr.buffer,...t?.buffer??{}}}}function td(t){try{return Xr(Et(t).screen)}catch{return Xr(void 0)}}var Ra=/^[a-z][\w-]*$/,Gr=["window","screen","menubar","notifications"];function Z(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var be=(t,e)=>Z(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Kr(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 nd(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=be(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=be(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=be(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Z(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Z(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!Ra.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete r[s]:r[s]=Kr(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=Z(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=Z(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=be(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!Gr.includes(i)&&!n.regions?.[i])try{Kr(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Gr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Qt as a,Ea as b,tt as c,Ks as d,Js as e,mc as f,hc as g,bc as h,ar as i,wc as j,xc as k,D as l,lr as m,k as n,Pa as o,Va as p,Ri as q,Ga as r,yn as s,A as t,ja as u,Wa as v,Ya as w,oe as x,Za as y,xn as z,il as A,z as B,wl as C,kl as D,_n as E,cr as F,$c as G,nt as H,_c as I,vr as J,eu as K,tu as L,au as M,qo as N,lu as O,Sl as P,vl as Q,$l as R,Al as S,Rl as T,_l as U,El as V,Tl as W,Wl as X,Me as Y,Fl as Z,Ul as _,X as $,G as aa,Ko as ba,bu as ca,yu as da,wu as ea,ku as fa,ct as ga,xu as ha,Fe as ia,Ue as ja,pe as ka,ms as la,bs as ma,zl as na,qe as oa,Be as pa,ys as qa,ws as ra,Xn as sa,Yn as ta,Xl as ua,Ss as va,Gl as wa,Ts as xa,Ps as ya,He as za,Ls as Aa,Zn as Ba,P as Ca,Lr as Da,Or as Ea,Mr as Fa,_u as Ga,ia as Ha,Wr as Ia,Fr as Ja,ju as Ka,Wu as La,ka as Ma,Fu as Na,Vr as Oa,ge as Pa,oc as Qa,ir as Ra,ze as Sa,Qe as Ta,gc as Ua,Bu as Va,Hu as Wa,zu as Xa,Xu as Ya,Gu as Za,Ku as _a,Ju as $a,Yu as ab,Zu as bb,zr as cb,Xr as db,td as eb,Gr as fb,nd as gb};
532
+ //# sourceMappingURL=chunk-7YZL5MUL.js.map