agentix-cli 0.159.0 → 0.161.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 (178) hide show
  1. package/README.md +25 -20
  2. package/dist/{App-LFKP4IY5.js → App-MXMKX57A.js} +2 -2
  3. package/dist/{ChatApp-SSVWKETD.js → ChatApp-PSKTL3PQ.js} +2 -2
  4. package/dist/{absorb-eval-IPPP2RZV.js → absorb-eval-NACNM4PW.js} +2 -2
  5. package/dist/{agent-SNNE24LT.js → agent-2RYXBN55.js} +2 -2
  6. package/dist/{board-dashboard-YW6WOQAB.js → board-dashboard-4IM47KL3.js} +827 -398
  7. package/dist/board-dashboard-4IM47KL3.js.map +1 -0
  8. package/dist/{chunk-T2GBLNW7.js → chunk-23J4NAHM.js} +2 -2
  9. package/dist/{chunk-KPYWYMRY.js → chunk-34NONG4B.js} +2 -2
  10. package/dist/chunk-4KMS3ES7.js +90 -0
  11. package/dist/chunk-4KMS3ES7.js.map +1 -0
  12. package/dist/{chunk-CDLRTTHR.js → chunk-55ZCWREX.js} +2 -2
  13. package/dist/{chunk-XWQ3ZEIZ.js → chunk-A75ADFHR.js} +2 -2
  14. package/dist/{chunk-KCT6Y2AG.js → chunk-ATF7JKPR.js} +2 -2
  15. package/dist/{chunk-LLJZMS23.js → chunk-AYK2MO3B.js} +2 -2
  16. package/dist/{chunk-XMU63PSI.js → chunk-AYYWQOGG.js} +3 -3
  17. package/dist/{chunk-IERW7MLU.js → chunk-BH46UJ6V.js} +2 -2
  18. package/dist/{chunk-KXK2OKT5.js → chunk-CKIIBDGR.js} +2 -2
  19. package/dist/{chunk-QH7R4IQS.js → chunk-CO272ZNT.js} +2 -2
  20. package/dist/{chunk-UIVNNH6T.js → chunk-GPNX66NP.js} +2 -2
  21. package/dist/{chunk-UIVNNH6T.js.map → chunk-GPNX66NP.js.map} +1 -1
  22. package/dist/{chunk-Z5RMH5SV.js → chunk-GQWH6PPF.js} +2 -2
  23. package/dist/{chunk-2OY7P3HS.js → chunk-IICCM3LV.js} +246 -246
  24. package/dist/chunk-IICCM3LV.js.map +1 -0
  25. package/dist/{chunk-5IXE5AXR.js → chunk-IKRDLKKJ.js} +16 -7
  26. package/dist/chunk-IKRDLKKJ.js.map +1 -0
  27. package/dist/{chunk-DPNCWHJW.js → chunk-ITIW4UUJ.js} +2 -2
  28. package/dist/{chunk-HWOBHAZD.js → chunk-JJ7GP3YA.js} +2 -2
  29. package/dist/chunk-L5EU7TH2.js +181 -0
  30. package/dist/chunk-L5EU7TH2.js.map +1 -0
  31. package/dist/{chunk-ODAZQH7N.js → chunk-M3SXXUNB.js} +2 -2
  32. package/dist/{chunk-M6YFSYJC.js → chunk-O7ITYFU6.js} +2 -2
  33. package/dist/{chunk-7C67DNT6.js → chunk-OGCZJTGG.js} +2 -2
  34. package/dist/{chunk-5NTWGUSJ.js → chunk-OO7T7E4O.js} +2 -2
  35. package/dist/{chunk-KKTHRSSJ.js → chunk-OQWMP5ZD.js} +2 -2
  36. package/dist/chunk-PTX6NWCQ.js +41 -0
  37. package/dist/chunk-PTX6NWCQ.js.map +1 -0
  38. package/dist/{chunk-MBCXPY6T.js → chunk-QA2ZRM57.js} +2 -2
  39. package/dist/{chunk-P5RTEJUB.js → chunk-SCEQJFQO.js} +2 -2
  40. package/dist/{chunk-EMGB23H5.js → chunk-UKUH662W.js} +2 -2
  41. package/dist/chunk-UKUH662W.js.map +1 -0
  42. package/dist/{chunk-P76PFVMJ.js → chunk-V6FVFN7S.js} +2 -2
  43. package/dist/{chunk-5TTHN7DP.js → chunk-VL74KOR7.js} +18 -13
  44. package/dist/chunk-VL74KOR7.js.map +1 -0
  45. package/dist/{chunk-JYSJDHNS.js → chunk-VUEQ4SL5.js} +18 -9
  46. package/dist/{chunk-JYSJDHNS.js.map → chunk-VUEQ4SL5.js.map} +1 -1
  47. package/dist/{chunk-2J7LN4SR.js → chunk-WEUGS4GI.js} +2 -2
  48. package/dist/{chunk-S5CNKZBP.js → chunk-X45QYAZ2.js} +2 -2
  49. package/dist/{chunk-UIBUZ2N3.js → chunk-XG5FRD7G.js} +19 -8
  50. package/dist/chunk-XG5FRD7G.js.map +1 -0
  51. package/dist/chunk-XIRM45DH.js +11 -0
  52. package/dist/chunk-XIRM45DH.js.map +1 -0
  53. package/dist/{chunk-LSC64WL3.js → chunk-XOQB2M6T.js} +2 -2
  54. package/dist/{chunk-ECY6WMZP.js → chunk-Y3DUSCYH.js} +2 -2
  55. package/dist/cli.js +1 -1
  56. package/dist/{client-GVAZIQQW.js → client-RKJQW7V4.js} +2 -2
  57. package/dist/{config-IWC47ZIT.js → config-VUCSD5CQ.js} +2 -2
  58. package/dist/config-mutate-XGYCOQ2Q.js +2 -0
  59. package/dist/config-mutator-AOZIMD3Q.js +2 -0
  60. package/dist/{contributions-HEPV2YXR.js → contributions-SK2T5B5H.js} +2 -2
  61. package/dist/{doctor-HOTKJEW5.js → doctor-63WBE26X.js} +2 -2
  62. package/dist/{failure-candidates-NQX2JMMS.js → failure-candidates-HNENLQJC.js} +2 -2
  63. package/dist/{follow-up-tool-R2U755ZJ.js → follow-up-tool-Z5AKB2WM.js} +2 -2
  64. package/dist/hub-5XVB256E.js +2 -0
  65. package/dist/index.d.ts +124 -1
  66. package/dist/index.js +1 -1
  67. package/dist/processes-GRS7BSIU.js +2 -0
  68. package/dist/{program-7QU75QNS.js → program-JAODEQ3Y.js} +283 -267
  69. package/dist/program-JAODEQ3Y.js.map +1 -0
  70. package/dist/{promote-QLBR6G6E.js → promote-IPL7FTWA.js} +2 -2
  71. package/dist/{query-L4TULDGS.js → query-OI7WUKYO.js} +2 -2
  72. package/dist/{query-settings-RH2E6JM2.js → query-settings-N2LLPXIW.js} +2 -2
  73. package/dist/{registry-HNCVWFDT.js → registry-HD6A6L7V.js} +2 -2
  74. package/dist/{request-planner-SH5CLEZZ.js → request-planner-EGSNUPFD.js} +2 -2
  75. package/dist/{review-candidates-V7WCKVVJ.js → review-candidates-U3Z46RRY.js} +2 -2
  76. package/dist/routing-U36AIRKZ.js +2 -0
  77. package/dist/schedule-tool-EG3LABHQ.js +2 -0
  78. package/dist/scheduler-4L7UJTN7.js +2 -0
  79. package/dist/{seat-CHFR5HFA.js → seat-ZQTFH7FE.js} +2 -2
  80. package/dist/{select-FTQBN33Y.js → select-JO5USUIR.js} +2 -2
  81. package/dist/{set-enabled-OCXL7V7L.js → set-enabled-PPOAMZ5R.js} +2 -2
  82. package/dist/{surface-usage-WSY4SHHL.js → surface-usage-W33HGXMP.js} +2 -2
  83. package/dist/token-store-F2PHHO5A.js +2 -0
  84. package/dist/token-tracker-B2UFOH46.js +2 -0
  85. package/dist/{tool-6WLBCL22.js → tool-6G7TMVKS.js} +2 -2
  86. package/dist/{tool-ZFSGK53G.js → tool-YHHUBUIP.js} +2 -2
  87. package/dist/traces-G4HRLRA3.js +2 -0
  88. package/dist/wiki-PG6OQEXK.js +2 -0
  89. package/dist/wiki-enrich-WLEWKV45.js +2 -0
  90. package/dist/{workflow-pilot-HCPSMGIC.js → workflow-pilot-25NMZYUO.js} +2 -2
  91. package/package.json +1 -1
  92. package/dist/board-dashboard-YW6WOQAB.js.map +0 -1
  93. package/dist/chunk-2OY7P3HS.js.map +0 -1
  94. package/dist/chunk-36AXN6ZB.js +0 -11
  95. package/dist/chunk-36AXN6ZB.js.map +0 -1
  96. package/dist/chunk-5IXE5AXR.js.map +0 -1
  97. package/dist/chunk-5TTHN7DP.js.map +0 -1
  98. package/dist/chunk-A43C7UUG.js +0 -41
  99. package/dist/chunk-A43C7UUG.js.map +0 -1
  100. package/dist/chunk-A7AVIFNF.js +0 -86
  101. package/dist/chunk-A7AVIFNF.js.map +0 -1
  102. package/dist/chunk-EHUKKZ5H.js +0 -181
  103. package/dist/chunk-EHUKKZ5H.js.map +0 -1
  104. package/dist/chunk-EMGB23H5.js.map +0 -1
  105. package/dist/chunk-UIBUZ2N3.js.map +0 -1
  106. package/dist/config-mutate-W7KUQC72.js +0 -2
  107. package/dist/config-mutator-ZVDBAYHA.js +0 -2
  108. package/dist/hub-5LSCXPYT.js +0 -2
  109. package/dist/processes-XM77XGOO.js +0 -2
  110. package/dist/program-7QU75QNS.js.map +0 -1
  111. package/dist/routing-KCZ6AY66.js +0 -2
  112. package/dist/schedule-tool-PYG4K4RY.js +0 -2
  113. package/dist/scheduler-X56K6BXS.js +0 -2
  114. package/dist/token-store-AY6OBDVI.js +0 -2
  115. package/dist/token-tracker-W7DFDEFN.js +0 -2
  116. package/dist/traces-GVEQZX24.js +0 -2
  117. package/dist/wiki-6UDGACKC.js +0 -2
  118. package/dist/wiki-enrich-6QKT6KCN.js +0 -2
  119. /package/dist/{App-LFKP4IY5.js.map → App-MXMKX57A.js.map} +0 -0
  120. /package/dist/{ChatApp-SSVWKETD.js.map → ChatApp-PSKTL3PQ.js.map} +0 -0
  121. /package/dist/{absorb-eval-IPPP2RZV.js.map → absorb-eval-NACNM4PW.js.map} +0 -0
  122. /package/dist/{agent-SNNE24LT.js.map → agent-2RYXBN55.js.map} +0 -0
  123. /package/dist/{chunk-T2GBLNW7.js.map → chunk-23J4NAHM.js.map} +0 -0
  124. /package/dist/{chunk-KPYWYMRY.js.map → chunk-34NONG4B.js.map} +0 -0
  125. /package/dist/{chunk-CDLRTTHR.js.map → chunk-55ZCWREX.js.map} +0 -0
  126. /package/dist/{chunk-XWQ3ZEIZ.js.map → chunk-A75ADFHR.js.map} +0 -0
  127. /package/dist/{chunk-KCT6Y2AG.js.map → chunk-ATF7JKPR.js.map} +0 -0
  128. /package/dist/{chunk-LLJZMS23.js.map → chunk-AYK2MO3B.js.map} +0 -0
  129. /package/dist/{chunk-XMU63PSI.js.map → chunk-AYYWQOGG.js.map} +0 -0
  130. /package/dist/{chunk-IERW7MLU.js.map → chunk-BH46UJ6V.js.map} +0 -0
  131. /package/dist/{chunk-KXK2OKT5.js.map → chunk-CKIIBDGR.js.map} +0 -0
  132. /package/dist/{chunk-QH7R4IQS.js.map → chunk-CO272ZNT.js.map} +0 -0
  133. /package/dist/{chunk-Z5RMH5SV.js.map → chunk-GQWH6PPF.js.map} +0 -0
  134. /package/dist/{chunk-DPNCWHJW.js.map → chunk-ITIW4UUJ.js.map} +0 -0
  135. /package/dist/{chunk-HWOBHAZD.js.map → chunk-JJ7GP3YA.js.map} +0 -0
  136. /package/dist/{chunk-ODAZQH7N.js.map → chunk-M3SXXUNB.js.map} +0 -0
  137. /package/dist/{chunk-M6YFSYJC.js.map → chunk-O7ITYFU6.js.map} +0 -0
  138. /package/dist/{chunk-7C67DNT6.js.map → chunk-OGCZJTGG.js.map} +0 -0
  139. /package/dist/{chunk-5NTWGUSJ.js.map → chunk-OO7T7E4O.js.map} +0 -0
  140. /package/dist/{chunk-KKTHRSSJ.js.map → chunk-OQWMP5ZD.js.map} +0 -0
  141. /package/dist/{chunk-MBCXPY6T.js.map → chunk-QA2ZRM57.js.map} +0 -0
  142. /package/dist/{chunk-P5RTEJUB.js.map → chunk-SCEQJFQO.js.map} +0 -0
  143. /package/dist/{chunk-P76PFVMJ.js.map → chunk-V6FVFN7S.js.map} +0 -0
  144. /package/dist/{chunk-2J7LN4SR.js.map → chunk-WEUGS4GI.js.map} +0 -0
  145. /package/dist/{chunk-S5CNKZBP.js.map → chunk-X45QYAZ2.js.map} +0 -0
  146. /package/dist/{chunk-LSC64WL3.js.map → chunk-XOQB2M6T.js.map} +0 -0
  147. /package/dist/{chunk-ECY6WMZP.js.map → chunk-Y3DUSCYH.js.map} +0 -0
  148. /package/dist/{client-GVAZIQQW.js.map → client-RKJQW7V4.js.map} +0 -0
  149. /package/dist/{config-IWC47ZIT.js.map → config-VUCSD5CQ.js.map} +0 -0
  150. /package/dist/{config-mutate-W7KUQC72.js.map → config-mutate-XGYCOQ2Q.js.map} +0 -0
  151. /package/dist/{config-mutator-ZVDBAYHA.js.map → config-mutator-AOZIMD3Q.js.map} +0 -0
  152. /package/dist/{contributions-HEPV2YXR.js.map → contributions-SK2T5B5H.js.map} +0 -0
  153. /package/dist/{doctor-HOTKJEW5.js.map → doctor-63WBE26X.js.map} +0 -0
  154. /package/dist/{failure-candidates-NQX2JMMS.js.map → failure-candidates-HNENLQJC.js.map} +0 -0
  155. /package/dist/{follow-up-tool-R2U755ZJ.js.map → follow-up-tool-Z5AKB2WM.js.map} +0 -0
  156. /package/dist/{hub-5LSCXPYT.js.map → hub-5XVB256E.js.map} +0 -0
  157. /package/dist/{processes-XM77XGOO.js.map → processes-GRS7BSIU.js.map} +0 -0
  158. /package/dist/{promote-QLBR6G6E.js.map → promote-IPL7FTWA.js.map} +0 -0
  159. /package/dist/{query-L4TULDGS.js.map → query-OI7WUKYO.js.map} +0 -0
  160. /package/dist/{query-settings-RH2E6JM2.js.map → query-settings-N2LLPXIW.js.map} +0 -0
  161. /package/dist/{registry-HNCVWFDT.js.map → registry-HD6A6L7V.js.map} +0 -0
  162. /package/dist/{request-planner-SH5CLEZZ.js.map → request-planner-EGSNUPFD.js.map} +0 -0
  163. /package/dist/{review-candidates-V7WCKVVJ.js.map → review-candidates-U3Z46RRY.js.map} +0 -0
  164. /package/dist/{routing-KCZ6AY66.js.map → routing-U36AIRKZ.js.map} +0 -0
  165. /package/dist/{schedule-tool-PYG4K4RY.js.map → schedule-tool-EG3LABHQ.js.map} +0 -0
  166. /package/dist/{scheduler-X56K6BXS.js.map → scheduler-4L7UJTN7.js.map} +0 -0
  167. /package/dist/{seat-CHFR5HFA.js.map → seat-ZQTFH7FE.js.map} +0 -0
  168. /package/dist/{select-FTQBN33Y.js.map → select-JO5USUIR.js.map} +0 -0
  169. /package/dist/{set-enabled-OCXL7V7L.js.map → set-enabled-PPOAMZ5R.js.map} +0 -0
  170. /package/dist/{surface-usage-WSY4SHHL.js.map → surface-usage-W33HGXMP.js.map} +0 -0
  171. /package/dist/{token-store-AY6OBDVI.js.map → token-store-F2PHHO5A.js.map} +0 -0
  172. /package/dist/{token-tracker-W7DFDEFN.js.map → token-tracker-B2UFOH46.js.map} +0 -0
  173. /package/dist/{tool-6WLBCL22.js.map → tool-6G7TMVKS.js.map} +0 -0
  174. /package/dist/{tool-ZFSGK53G.js.map → tool-YHHUBUIP.js.map} +0 -0
  175. /package/dist/{traces-GVEQZX24.js.map → traces-G4HRLRA3.js.map} +0 -0
  176. /package/dist/{wiki-6UDGACKC.js.map → wiki-PG6OQEXK.js.map} +0 -0
  177. /package/dist/{wiki-enrich-6QKT6KCN.js.map → wiki-enrich-WLEWKV45.js.map} +0 -0
  178. /package/dist/{workflow-pilot-HCPSMGIC.js.map → workflow-pilot-25NMZYUO.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as h}from"./chunk-T2GBLNW7.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
1
+ import{a as h}from"./chunk-23J4NAHM.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
2
2
  `),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
3
3
  `),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
4
- //# sourceMappingURL=chunk-CDLRTTHR.js.map
4
+ //# sourceMappingURL=chunk-55ZCWREX.js.map
@@ -1,4 +1,4 @@
1
- import{e as g}from"./chunk-XMU63PSI.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
1
+ import{e as g}from"./chunk-AYYWQOGG.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
2
2
  `)}).join(`
3
3
 
4
4
  ---
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
14
14
 
15
15
  ${i}
16
16
  `}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
17
- //# sourceMappingURL=chunk-XWQ3ZEIZ.js.map
17
+ //# sourceMappingURL=chunk-A75ADFHR.js.map
@@ -1,7 +1,7 @@
1
- import{db as b,eb as k,gb as x,ob as S}from"./chunk-A7AVIFNF.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
1
+ import{eb as b,fb as k,hb as x,pb as S}from"./chunk-4KMS3ES7.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${f}`,after:i}}let m=x(u.data);if(m.length)return{success:!1,path:o,error:`Validation failed:
4
4
  ${m.map(f=>` ${f}`).join(`
5
5
  `)}`,after:i}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{v(o,JSON.stringify(i,null,2)+`
6
6
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let h=!1,y;if(s){let a=c||M(i),u=await C(a);u.ok?h=!0:y=u.reason}return{success:!0,path:o,after:i,reloaded:h,reloadSkipped:y}}function M(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function A(r,e,n){let t=e.split("."),s=r;for(let l=0;l<t.length-1;l++){let c=t[l];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function F(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function U(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{O as a,N as b,A as c,F as d,U as e};
7
- //# sourceMappingURL=chunk-KCT6Y2AG.js.map
7
+ //# sourceMappingURL=chunk-ATF7JKPR.js.map
@@ -1,8 +1,8 @@
1
- import{f,k as I}from"./chunk-5TTHN7DP.js";import{createHash as $}from"crypto";var k="failure:",x=3,p=5,A=["error","timeout"],T=["memory-promote","procedure-miner"];function h(t,s){return(s??"").toLowerCase().replace(/https?:\/\/\S+/g,"<url>").replace(/(["'`]).*?\1/g,"<v>").replace(/(?:~|\.{0,2})?\/[\w.@-]+(?:\/[\w.@-]+)*/g,"<path>").replace(/\b[0-9a-z]*\d[0-9a-z]*\b/g,"<n>").replace(/[^a-z<>\s]+/g," ").replace(/\s+/g," ").trim().split(" ").filter(Boolean).slice(0,8).join(" ")||t}function y(t){return`${t.agentId}|${t.tool??"no-tool"}|${t.status}|${h(t.status,t.error)}`}function S(t){return $("sha1").update(t).digest("hex").slice(0,10)}function w(t,s){return`${k}${S(t)}@${Math.floor(Math.log2(Math.max(1,s)))}`}function F(t){return t.finalSessionId??t.resumeSessionId??t.taskId}function _(t,s={}){return A.flatMap(e=>I(t,{status:e,since:s.since,limit:1e3})).filter(e=>!T.some(i=>(e.chatId??"").startsWith(i))).map(e=>{let{tool:i,error:n}=b(f(t,e.taskId)?.steps??[]);return{taskId:e.taskId,agentId:e.agentId,chatId:e.chatId,sessionId:F(e),status:e.status,startedAt:e.startedAt,error:n??e.error,messagePreview:e.messagePreview,tool:i}})}function b(t){let s=null,a=null;for(let e of t)e.name==="tool_use"&&e.action?(s=e.action,e.status==="error"&&(a={tool:e.action,error:e.error??e.outputSummary})):e.name==="tool_result"&&e.status==="error"&&(a={tool:e.action??s,error:e.error??e.outputSummary});return a??{tool:s,error:null}}function C(t,s={}){let a=Math.max(2,s.minSessions??x),e=new Map;for(let n of t){let r=y(n);e.set(r,[...e.get(r)??[],n])}let i=[];for(let[n,r]of e){let l=[...new Set([...r].sort((c,g)=>g.startedAt-c.startedAt).map(c=>c.sessionId))];if(l.length<a)continue;r.sort((c,g)=>g.startedAt-c.startedAt);let o=r[0],u=o.tool??"no tool",d=h(o.status,o.error),m=`failure-${S(n)}`;i.push({occurrences:l.length,sessions:l.slice(0,p),tasks:r.slice(0,p).map(c=>c.taskId),failure:{tool:u,errorClass:d,runs:r.length},agentId:o.agentId,key:`${o.agentId}/feedback_${m}`,stamp:w(n,l.length),memory:{name:m,type:"feedback",description:`${o.agentId}: ${u} keeps failing (${d}) in ${l.length} sessions`.slice(0,200),body:E(o.agentId,u,d,l.length,r),createdAt:new Date(r[r.length-1].startedAt).toISOString(),updatedAt:new Date(o.startedAt).toISOString()}})}return i.sort((n,r)=>r.occurrences-n.occurrences)}function E(t,s,a,e,i){let n=i.slice(0,p).map(r=>{let l=(r.messagePreview??"").replace(/\s+/g," ").trim().slice(0,120),o=(r.error??r.status).replace(/\s+/g," ").trim().slice(0,160);return`- ${new Date(r.startedAt).toISOString().slice(0,10)} \`${r.taskId}\` (${r.status})${l?` \u2014 task: ${l}`:""}
1
+ import{f,k as I}from"./chunk-VL74KOR7.js";import{createHash as $}from"crypto";var k="failure:",x=3,p=5,A=["error","timeout"],T=["memory-promote","procedure-miner"];function h(t,s){return(s??"").toLowerCase().replace(/https?:\/\/\S+/g,"<url>").replace(/(["'`]).*?\1/g,"<v>").replace(/(?:~|\.{0,2})?\/[\w.@-]+(?:\/[\w.@-]+)*/g,"<path>").replace(/\b[0-9a-z]*\d[0-9a-z]*\b/g,"<n>").replace(/[^a-z<>\s]+/g," ").replace(/\s+/g," ").trim().split(" ").filter(Boolean).slice(0,8).join(" ")||t}function y(t){return`${t.agentId}|${t.tool??"no-tool"}|${t.status}|${h(t.status,t.error)}`}function S(t){return $("sha1").update(t).digest("hex").slice(0,10)}function w(t,s){return`${k}${S(t)}@${Math.floor(Math.log2(Math.max(1,s)))}`}function F(t){return t.finalSessionId??t.resumeSessionId??t.taskId}function _(t,s={}){return A.flatMap(e=>I(t,{status:e,since:s.since,limit:1e3})).filter(e=>!T.some(i=>(e.chatId??"").startsWith(i))).map(e=>{let{tool:i,error:n}=b(f(t,e.taskId)?.steps??[]);return{taskId:e.taskId,agentId:e.agentId,chatId:e.chatId,sessionId:F(e),status:e.status,startedAt:e.startedAt,error:n??e.error,messagePreview:e.messagePreview,tool:i}})}function b(t){let s=null,a=null;for(let e of t)e.name==="tool_use"&&e.action?(s=e.action,e.status==="error"&&(a={tool:e.action,error:e.error??e.outputSummary})):e.name==="tool_result"&&e.status==="error"&&(a={tool:e.action??s,error:e.error??e.outputSummary});return a??{tool:s,error:null}}function C(t,s={}){let a=Math.max(2,s.minSessions??x),e=new Map;for(let n of t){let r=y(n);e.set(r,[...e.get(r)??[],n])}let i=[];for(let[n,r]of e){let l=[...new Set([...r].sort((c,g)=>g.startedAt-c.startedAt).map(c=>c.sessionId))];if(l.length<a)continue;r.sort((c,g)=>g.startedAt-c.startedAt);let o=r[0],u=o.tool??"no tool",d=h(o.status,o.error),m=`failure-${S(n)}`;i.push({occurrences:l.length,sessions:l.slice(0,p),tasks:r.slice(0,p).map(c=>c.taskId),failure:{tool:u,errorClass:d,runs:r.length},agentId:o.agentId,key:`${o.agentId}/feedback_${m}`,stamp:w(n,l.length),memory:{name:m,type:"feedback",description:`${o.agentId}: ${u} keeps failing (${d}) in ${l.length} sessions`.slice(0,200),body:E(o.agentId,u,d,l.length,r),createdAt:new Date(r[r.length-1].startedAt).toISOString(),updatedAt:new Date(o.startedAt).toISOString()}})}return i.sort((n,r)=>r.occurrences-n.occurrences)}function E(t,s,a,e,i){let n=i.slice(0,p).map(r=>{let l=(r.messagePreview??"").replace(/\s+/g," ").trim().slice(0,120),o=(r.error??r.status).replace(/\s+/g," ").trim().slice(0,160);return`- ${new Date(r.startedAt).toISOString().slice(0,10)} \`${r.taskId}\` (${r.status})${l?` \u2014 task: ${l}`:""}
2
2
  error: ${o}`});return[`**${t}** hit the same failure in ${e} separate sessions (${i.length} runs).`,`- Tool: \`${s}\`
3
3
  - Error class: \`${a}\``,"Recurrence across sessions is the finding: any one of these runs is session state. Propose the fix that stops it recurring \u2014 what fails, the likely cause, and what to do instead (a missing fact, a better approach, or a tool or configuration change to make) \u2014 or skip it if the examples do not share a cause.",`**Examples (newest first):**
4
4
  ${n.join(`
5
5
  `)}`].join(`
6
6
 
7
7
  `)}export{k as a,x as b,p as c,h as d,y as e,w as f,F as g,_ as h,b as i,C as j};
8
- //# sourceMappingURL=chunk-LLJZMS23.js.map
8
+ //# sourceMappingURL=chunk-AYK2MO3B.js.map
@@ -1,4 +1,4 @@
1
- import{a as _,b as F,c as K,d as z,e as J}from"./chunk-6QZKQUAT.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-IERW7MLU.js";import{a as H}from"./chunk-MWNCS57L.js";import{y as N,z as ot}from"./chunk-ECY6WMZP.js";import{g as Q}from"./chunk-6TURWSMN.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
1
+ import{a as _,b as F,c as K,d as z,e as J}from"./chunk-6QZKQUAT.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-BH46UJ6V.js";import{a as H}from"./chunk-MWNCS57L.js";import{y as N,z as ot}from"./chunk-Y3DUSCYH.js";import{g as Q}from"./chunk-6TURWSMN.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
2
2
 
3
3
  ## Shared wiki (other agents' articles)
4
4
 
@@ -51,5 +51,5 @@ ${o}
51
51
 
52
52
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
53
 
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-IWC47ZIT.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
- //# sourceMappingURL=chunk-XMU63PSI.js.map
54
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-VUCSD5CQ.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
55
+ //# sourceMappingURL=chunk-AYYWQOGG.js.map
@@ -1,6 +1,6 @@
1
- import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-ECY6WMZP.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-6QLRRSKU.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-Y3DUSCYH.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-6QLRRSKU.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-IERW7MLU.js.map
6
+ //# sourceMappingURL=chunk-BH46UJ6V.js.map
@@ -1,5 +1,5 @@
1
- import{fb as m,ob as b}from"./chunk-A7AVIFNF.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{gb as m,pb as b}from"./chunk-4KMS3ES7.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-KXK2OKT5.js.map
5
+ //# sourceMappingURL=chunk-CKIIBDGR.js.map
@@ -1,4 +1,4 @@
1
- import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{S as B,T as J,U as X,V as K,Z as N,ba as Oe}from"./chunk-A7AVIFNF.js";import{existsSync as Q,readFileSync as Ie}from"node:fs";import{dirname as A,join as h}from"node:path";import{fileURLToPath as Ee}from"node:url";import{homedir as Ce}from"node:os";var M="tn.acme.agentx.voice",gt="AgentX Desktop.app",Y="AgentX Helper.app";function yt(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function ht(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function T(e){return`'${e.replace(/'/g,"'\\''")}'`}var Z="/usr/bin:/bin:/usr/sbin:/sbin";function wt(e,t){return t||[...new Set([...e?[A(e)]:[],...Z.split(":")])].join(":")}function R(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function St(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?R(t[1]):Z}var xt=e=>/agentx\.voice.*\.plist$/.test(e);function vt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,u)=>s.file<u.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],u=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!u||!R(u).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:R(s)}):n={file:o,label:R(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function ee(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function bt(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${T(e.cwd)} && ${T(e.node)} ${T(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{S as B,T as J,U as X,V as K,Z as N,ca as Oe}from"./chunk-4KMS3ES7.js";import{existsSync as Q,readFileSync as Ie}from"node:fs";import{dirname as A,join as h}from"node:path";import{fileURLToPath as Ee}from"node:url";import{homedir as Ce}from"node:os";var M="tn.acme.agentx.voice",gt="AgentX Desktop.app",Y="AgentX Helper.app";function yt(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function ht(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function T(e){return`'${e.replace(/'/g,"'\\''")}'`}var Z="/usr/bin:/bin:/usr/sbin:/sbin";function wt(e,t){return t||[...new Set([...e?[A(e)]:[],...Z.split(":")])].join(":")}function R(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function St(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?R(t[1]):Z}var xt=e=>/agentx\.voice.*\.plist$/.test(e);function vt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,u)=>s.file<u.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],u=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!u||!R(u).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:R(s)}):n={file:o,label:R(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function ee(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function bt(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${T(e.cwd)} && ${T(e.node)} ${T(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <plist version="1.0"><dict>
4
4
  <key>Label</key><string>${t(e.label??M)}</string>
@@ -33,4 +33,4 @@ function run(argv) {
33
33
  `),it(r,n)}var ut=5*6e4;function Cn(e,t,n=Date.now()){let r=Ae(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=ut)?!1:r.items[`card:${t}`]?.state!=="failed"}var U=24*36e5;function Re(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function lt(e,t,n,r){let o=Date.parse(e.expires),i=[f(e.ask,y.ask)];return e.choices?.length&&i.push(...e.choices.map((s,u)=>`${u+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${f(e.recommend,y.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:f(e.title,y.title),notes:i.join(`
34
34
  `),due:Re(r,t,o),priority:Number.isFinite(o)&&o-r<=U?"high":"none"}}function ct(e,t,n,r){let o=[f(e.question||e.text,y.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:W(e,y.title).headline,notes:o.join(`
35
35
  `),due:Re(r,t,i),priority:i!==void 0&&i-r<=U?"high":"none"}}async function Tn(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),u={created:0,completed:0,dismissed:0,failed:0},l=Ae(t);delete l.lastError;let p=a=>{l.lastError={at:s,message:a}},S=new Map;try{if(n.include.includes("card"))for(let a of e.cards())a.status==="pending"&&Date.parse(a.expires)>i&&S.set(`card:${a.id}`,lt(a,n,e.answerUrl,i));if(n.include.includes("request"))for(let a of e.requests())a.state==="waiting_owner"&&S.set(`request:${a.id}`,ct(a,n,e.answerUrl,i))}catch(a){return o(`[mirror] could not read what is waiting: ${a?.message??a}`),p(String(a?.message??a)),Ne(t,l),u}let G=!0,v=new Map,Pe=async a=>{if(!v.has(a))try{v.set(a,new Set((await r.listOpen(a)).map(c=>c.id)))}catch(c){o(`[mirror] could not read list "${a}": ${c?.message??c}`),p(String(c?.message??c)),v.set(a,null),G=!1}return v.get(a)};for(let[a,c]of Object.entries(l.items)){if(c.state!=="open"||!c.id)continue;let d=await Pe(c.list);if(d)if(S.has(a))d.has(c.id)||(l.items[a]={...c,state:"dismissed",at:s},u.dismissed++,o(`[mirror] ${a}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(c.id))try{await r.complete(c.id)}catch(g){o(`[mirror] ${a}: could not complete its task: ${g?.message??g}`),p(String(g?.message??g));continue}l.items[a]={...c,state:"completed",at:s},u.completed++}}let E=null,x=[];for(let[a,c]of S){let d=l.items[a];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=j)continue;if(E===null)try{await r.ensureList(n.list),E=!0}catch(m){o(`[mirror] could not make list "${n.list}": ${m?.message??m}`),p(String(m?.message??m)),E=!1}let g=d?.state==="failed"?d.failures:0;try{let{id:m}=await r.add({list:n.list,title:c.title,notes:c.notes,due:c.due,priority:c.priority});l.items[a]={id:m,list:n.list,state:"open",at:s,failures:0},u.created++}catch(m){let b=String(m?.message??m),C=g+1;l.items[a]={list:n.list,state:"failed",at:s,failures:C,lastError:b},p(b),u.failed++,o(`[mirror] ${a}: could not add to Reminders (${C}/${j}): ${b}`),C===j&&x.push({title:c.title,message:b})}}let $e=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(x.length&&!(i-$e<U)){let a=x[0],c=x.length>1?` (and ${x.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${a.title}${c}: ${f(a.message,200)}. Still on the Desk.`),l.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}G&&(l.checkedAt=s,l.cards=n.include.includes("card"));for(let[a,c]of Object.entries(l.items))c.state!=="open"&&!S.has(a)&&i-Date.parse(c.at)>at&&delete l.items[a];return Ne(t,l),u}export{gn as a,he as b,H as c,F as d,yn as e,hn as f,Ze as g,wn as h,Sn as i,xn as j,W as k,f as l,Rn as m,gt as n,Y as o,yt as p,ht as q,wt as r,St as s,xt as t,vt as u,ee as v,bt as w,Nt as x,Te as y,Me as z,_e as A,_ as B,se as C,q as D,ye as E,un as F,ln as G,cn as H,Ae as I,Cn as J,Tn as K};
36
- //# sourceMappingURL=chunk-QH7R4IQS.js.map
36
+ //# sourceMappingURL=chunk-CO272ZNT.js.map
@@ -1,4 +1,4 @@
1
- import{a as Ne}from"./chunk-GTJIKXDB.js";import{C as dn,J as mn,k as O}from"./chunk-QH7R4IQS.js";import{a as w}from"./chunk-JYSJDHNS.js";import{f as pn,i as gn,k as De,l as Ce,n as X,o as W,q as fn}from"./chunk-LQS27HSV.js";import{t as ln,u as cn}from"./chunk-ODAZQH7N.js";import{d as on,e as an}from"./chunk-AQASR6KR.js";import{b as un}from"./chunk-2VDO2HEK.js";import{a as tn,b as nn,d as rn,e as sn}from"./chunk-MNG2AMKZ.js";import{g as Jt,h as Yt,i as Zt,k as Qt,l as en}from"./chunk-2J7LN4SR.js";import{a as Kt,c as Gt}from"./chunk-KP7KDLZ2.js";import{X as Xt,Z as oe,_ as Ie,aa as Te,b as Ae}from"./chunk-A43C7UUG.js";import{q as zt}from"./chunk-7C67DNT6.js";import{a as Bt,b as Ht}from"./chunk-KCT6Y2AG.js";import{$ as Ut,Ya as Ee,_ as Mt,aa as Ft,ba as Wt,eb as qt,fb as jt,n as se,o as Ot,ob as Vt,p as Pt,q as Ns}from"./chunk-A7AVIFNF.js";import{a as Re,h as Ls}from"./chunk-BRK6M6LA.js";import{f as _e,n as Os}from"./chunk-UIBUZ2N3.js";import{existsSync as Ps,readdirSync as Ms,readFileSync as Us,statSync as Fs}from"fs";import{resolve as Ws}from"path";function hn(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],l=a.filter(f=>n-f.at<=s),d=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?d.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:d.length,failed:c,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ie=new Map;function rc(t,e=1e3){if(!Ps(t))return[];let n=Ms(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=Ws(t,o);return{path:i,mtime:Fs(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ie.keys())r.has(o)||ie.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ie.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=qs(o,i);ie.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function qs(t,e){try{let n=Us(t,"utf-8").split(`
1
+ import{a as Ne}from"./chunk-GTJIKXDB.js";import{C as dn,J as mn,k as O}from"./chunk-CO272ZNT.js";import{a as w}from"./chunk-VUEQ4SL5.js";import{f as pn,i as gn,k as De,l as Ce,n as X,o as W,q as fn}from"./chunk-LQS27HSV.js";import{t as ln,u as cn}from"./chunk-M3SXXUNB.js";import{d as on,e as an}from"./chunk-AQASR6KR.js";import{b as un}from"./chunk-2VDO2HEK.js";import{a as tn,b as nn,d as rn,e as sn}from"./chunk-MNG2AMKZ.js";import{g as Jt,h as Yt,i as Zt,k as Qt,l as en}from"./chunk-WEUGS4GI.js";import{a as Kt,c as Gt}from"./chunk-KP7KDLZ2.js";import{b as Ae,da as Xt,fa as oe,ga as Ie,ia as Te}from"./chunk-PTX6NWCQ.js";import{q as zt}from"./chunk-OGCZJTGG.js";import{a as Bt,b as Ht}from"./chunk-ATF7JKPR.js";import{$ as Ut,Za as Ee,_ as Mt,ba as Ft,ca as Wt,fb as qt,gb as jt,n as se,o as Ot,p as Pt,pb as Vt,q as Ns}from"./chunk-4KMS3ES7.js";import{a as Re,h as Ls}from"./chunk-BRK6M6LA.js";import{i as _e,q as Os}from"./chunk-XG5FRD7G.js";import{existsSync as Ps,readdirSync as Ms,readFileSync as Us,statSync as Fs}from"fs";import{resolve as Ws}from"path";function hn(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],l=a.filter(f=>n-f.at<=s),d=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?d.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:d.length,failed:c,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ie=new Map;function rc(t,e=1e3){if(!Ps(t))return[];let n=Ms(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=Ws(t,o);return{path:i,mtime:Fs(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ie.keys())r.has(o)||ie.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ie.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=qs(o,i);ie.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function qs(t,e){try{let n=Us(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),s=r.run?.workflowId;if(!s)return null;let o=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),l=a.status??a.run?.status;if(l){o=l;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var js={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Vs=(t,e,n)=>{try{return zt(t,e,n)}catch{return null}},bn=864e5;function ac(t){let e=t.now??Date.now(),n={...js,...t.thresholds},r=t.nextFire??Vs,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],d=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:E(a.id,k.text),trigger:{schedule:E(a.schedule,k.text),timezone:d},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Le(a.nextRun)??Le(r(a.schedule,new Date(e),d)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:Gs(u.status==="success"?void 0:u.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:yn(c),sampledRuns:l.length,flags:[],attention:null};p.flags=wn(p,c,a.schedule,d,null,e,n,r),s.push(kn(p))}let o=new Map(hn(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(T=>T.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let d=l.config??{},c=a.state||"active",u=c==="active",p=(i.get(a.id)??[]).slice().sort((T,$e)=>$e.at-T.at),g=p.map(T=>({at:T.at,status:zs(T.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof d.spec=="string"?d.spec:"",x=typeof d.timezone=="string"?d.timezone:"UTC",F={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:E(a.title||a.id,k.text),trigger:m?{schedule:E(b,k.text),timezone:x}:{event:E(typeof d.event=="string"?d.event:"",k.text),filters:Ks(d.filter,a)},agent:Xs(a),enabled:u,state:c,nextRunAt:m&&u&&b?Le(r(b,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let T=g.find($e=>$e.status==="success");return T?new Date(T.at).toISOString():null})(),consecutiveFailures:yn(g),sampledRuns:p.length,flags:[],attention:null},re=Date.parse(a.updated||a.created||"");F.flags=m?wn(F,g,b,x,Number.isFinite(re)?re:null,e,n,r):Bs(F,o.get(a.id)?.state==="dormant",Number.isFinite(re)?re:null,e,n),s.push(kn(F))}return s.sort(Hs).slice(0,k.routines)}function yn(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 wn(t,e,n,r,s,o,i,a){let l=[],d=e.length?e[0].at:null;if(!t.enabled){let p=xn(d,s,o,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),d===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(d),u=null;for(let p=0;p<i.missedFires&&(u=a(n,c,r),!!u);p++)c=u;return u&&o>u.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(d).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function Bs(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=xn(i,n,r,s);return a&&o.push(a),o}return t.consecutiveFailures>=s.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function xn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*bn?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/bn)} days`:"Disabled and never ran"}}function kn(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 Hs(t,e){let n=t.attention?Sn[t.attention]:3,r=e.attention?Sn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function zs(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 Xs(t){if(t.ownerAgent)return E(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?E(String(e.config.agentId),k.text):null}function Ks(t,e){let n=[],r=e?.project;if(r&&n.push(E(`project=${r}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[s,o]of Object.entries(t)){let i=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];i.length&&n.push(E(`${s}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Le(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function E(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Gs(t,e){return t===void 0?void 0:E(t,e)}import{mkdirSync as Js,readFileSync as Ys,renameSync as Zs,writeFileSync as Qs}from"fs";import{resolve as eo}from"path";function vn(t){return eo(Ce(t),"_state.json")}function v(t){try{let e=JSON.parse(Ys(vn(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 K(t,e){Js(Ce(t),{recursive:!0});let n=vn(t),r=`${n}.${process.pid}.tmp`;Qs(r,JSON.stringify(e,null,2)+`
3
3
  `),Zs(r,n)}function $n(t,e,n,r=Date.now()){let s=v(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),K(t,{...s,snoozed:o})}function pc(t,e){K(t,{...v(t),lastDigest:e})}function Oe(t,e,n,r=Date.now()){let s=v(t),o=new Set(n),i={};for(let[l,d]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=d);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));K(t,{...s,popped:i,wanted:a})}function Rn(t,e){let n=v(t);K(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function gc(t,e=Date.now()){K(t,{...v(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as to,readFileSync as no}from"fs";Vt();Ls();function _n(t){let e=Bt(t),n={};if(to(e))try{n=qt(JSON.parse(no(e,"utf-8")))}catch{n={}}let r=Ee.safeParse(n?.requests);return r.success?r.data:Ee.parse(void 0)}async function wc(t,e={}){let n=(t.channels??[]).filter(r=>!Re.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Re].join(", ")}`}:Ht(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])t[o]!==void 0&&(s[o]=t[o]);if(t.plans){let o=s.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(o[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((s.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let o=s.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(o[i]=t.catchPromises[i])}if(t.checkers){let o=s.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(o[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as G,readdirSync as bo,readFileSync as yo}from"fs";import{resolve as A}from"path";import{randomBytes as In}from"crypto";import{existsSync as so,mkdirSync as oo,readdirSync as io,readFileSync as ao,renameSync as Tn,unlinkSync as lo,writeFileSync as co}from"fs";import{resolve as Dn}from"path";function En(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ro=t=>t.trim().split(`
4
4
  `).pop()?.slice(0,300)||"no output";async function An(t,e,n,r=Ne){let s=await r(t.bin,[...En(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ro(s.stderr||s.stdout)}`}}async function xc(t,e,n,r,s=Ne){return(await s(t.bin,[...En(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var uo=2e3,po=t=>An(t.wacli,t.to,t.text);function Pe(t){return Dn(t,".agentx","whatsapp-triage","drafts")}var go=t=>/^[a-z0-9-]{8,64}$/.test(t),ae=(t,e)=>Dn(Pe(t),`${e}.json`);function Cn(t,e){oo(Pe(t),{recursive:!0});let n=ae(t,e.id),r=`${n}.${process.pid}.tmp`;co(r,JSON.stringify(e,null,2)+`
@@ -575,4 +575,4 @@ Document the arguments, commands, or files the skill expects. Example:
575
575
  claude-code ${Lt(t)} --arg value
576
576
  \`\`\`
577
577
  `}Vt();var Is={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Ts(t){return{...Is,...t??{},regions:{...t?.regions??{}},buffer:{...Is.buffer,...t?.buffer??{}}}}function pg(t){try{return Ts(jt(t).screen)}catch{return Ts(void 0)}}var ec=/^[a-z][\w-]*$/,Ds=["window","screen","menubar","notifications"];function ne(t,e,n,r){let s=Number(t);if(t===""||t===null||!Number.isFinite(s)||!n(s))throw new Error(`${e} must be ${r}`);return s}var ve=(t,e)=>ne(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Cs(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 gg(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=ve(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=ve(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=ve(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ne(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ne(e.changeThreshold,"changeThreshold",s=>s>=0&&s<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let s={...n.regions??{}};for(let[o,i]of Object.entries(e.regions)){if(!ec.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=Cs(i)}n.regions=s}if(e.buffer&&typeof e.buffer=="object"){let s=e.buffer,o={...n.buffer??{}};"enabled"in s&&(o.enabled=!!s.enabled),"seconds"in s&&(o.seconds=ne(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=ne(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=ve(s.maxPixels,"buffer.maxPixels")),"region"in s&&(o.region=String(s.region).trim()),n.buffer=o}let r=n.buffer?.region;if(r!==void 0&&!Ds.includes(r)&&!n.regions?.[r])try{Cs(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Ds,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{hn as a,rc as b,pt as c,Xi as d,Ki as e,tu as f,nu as g,ru as h,iu as i,au as j,lu as k,Ir as l,Tr as m,cu as n,Dr as o,uu as p,gu as q,N as r,Cr as s,k as t,ac as u,Or as v,wu as w,xu as x,Mr as y,vu as z,Ur as A,$u as B,Z as C,Sa as D,Ru as E,_u as F,Wr as G,xc as H,po as I,Ac as J,Ln as K,v as L,pc as M,gc as N,Dc as O,ce as P,Cc as Q,_n as R,wc as S,P as T,Kc as U,jn as V,Vn as W,Co as X,No as Y,Yc as Z,Zc as _,Wo as $,nd as aa,jr as ba,Iu as ca,od as da,id as ea,Rr as fa,rt as ga,Wi as ha,ts as ia,op as ja,ip as ka,il as la,dp as ma,as as na,up as oa,pp as pa,yp as qa,bl as ra,wp as sa,ld as ta,cd as ua,dd as va,ud as wa,pd as xa,gd as ya,md as za,hd as Aa,Rd as Ba,Ke as Ca,_d as Da,Ed as Ea,J as Fa,Y as Ga,vl as Ha,Ap as Ia,Ip as Ja,Tp as Ka,Dp as La,xt as Ma,Cp as Na,Ye as Oa,Ze as Pa,he as Qa,pi as Ra,fi as Sa,Cd as Ta,et as Ua,tt as Va,mi as Wa,hi as Xa,fr as Ya,yr as Za,Nd as _a,wi as $a,Ld as ab,Ei as bb,Ti as cb,nt as db,Ci as eb,wr as fb,L as gb,ys as hb,ws as ib,ks as jb,Up as kb,Cl as lb,xs as mb,vs as nb,Gp as ob,Jp as pb,Kl as qb,Yp as rb,Rs as sb,be as tb,zd as ub,dt as vb,Qd as wb,tg as xb,ng as yb,rg as zb,sg as Ab,og as Bb,ig as Cb,ag as Db,lg as Eb,cg as Fb,Is as Gb,Ts as Hb,pg as Ib,Ds as Jb,gg as Kb};
578
- //# sourceMappingURL=chunk-UIVNNH6T.js.map
578
+ //# sourceMappingURL=chunk-GPNX66NP.js.map