agentix-cli 0.219.0 → 0.220.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 (142) hide show
  1. package/dist/{App-ET75JEWK.js → App-QRZJGHNK.js} +2 -2
  2. package/dist/{ChatApp-F2NT5M2O.js → ChatApp-DYC2WNAP.js} +2 -2
  3. package/dist/{absorb-eval-EA5ESP4Y.js → absorb-eval-4FENRVXM.js} +2 -2
  4. package/dist/{adapter-7PKOKXO5.js → adapter-5WMQSSQM.js} +2 -2
  5. package/dist/{agent-SDNU6MUI.js → agent-UDKXN4QV.js} +2 -2
  6. package/dist/{board-dashboard-PI22IXZN.js → board-dashboard-CZXKVKK7.js} +4 -4
  7. package/dist/{chunk-Z3FJRBTG.js → chunk-3XS7M5LM.js} +273 -272
  8. package/dist/chunk-3XS7M5LM.js.map +1 -0
  9. package/dist/{chunk-TCBIAKGS.js → chunk-4UJDRI7W.js} +2 -2
  10. package/dist/{chunk-KCS737RC.js → chunk-5BT4VPJC.js} +2 -2
  11. package/dist/{chunk-U4AUJ6XI.js → chunk-5CUOKXOD.js} +2 -2
  12. package/dist/{chunk-PTVDVI2U.js → chunk-5QXRGX2F.js} +2 -2
  13. package/dist/{chunk-Y3TXTZYG.js → chunk-5RCWAXVK.js} +2 -2
  14. package/dist/{chunk-6HCCMU57.js → chunk-5XN2OMBS.js} +2 -2
  15. package/dist/{chunk-V75JESS5.js → chunk-6EJJKOMW.js} +3 -3
  16. package/dist/{chunk-IQNKEUEL.js → chunk-ABMDDRZL.js} +2 -2
  17. package/dist/{chunk-MELXJ5AR.js → chunk-AEFO6ES5.js} +2 -2
  18. package/dist/{chunk-6X7SABYJ.js → chunk-AZCGU5XU.js} +2 -2
  19. package/dist/{chunk-EPOQUX4G.js → chunk-CIW37UJT.js} +2 -2
  20. package/dist/{chunk-UYDC2YMH.js → chunk-D5LIMOI6.js} +2 -2
  21. package/dist/{chunk-3XUAIA7U.js → chunk-E3SA7KIZ.js} +2 -2
  22. package/dist/{chunk-EWXY73XA.js → chunk-GO4J44UD.js} +2 -2
  23. package/dist/{chunk-34TEBXFP.js → chunk-JD5TCX4X.js} +2 -2
  24. package/dist/{chunk-SQJ3IHNL.js → chunk-JMRFYGET.js} +2 -2
  25. package/dist/{chunk-HHSPOS7O.js → chunk-M6TZ7IIJ.js} +2 -2
  26. package/dist/{chunk-IKOJM4GM.js → chunk-NCMPJPXG.js} +2 -2
  27. package/dist/{chunk-ZT4FCL5B.js → chunk-NW7B53KD.js} +2 -2
  28. package/dist/{chunk-W2KIJ5LL.js → chunk-PSUOF7O5.js} +2 -2
  29. package/dist/{chunk-MUCWUVOW.js → chunk-RHNOMUYZ.js} +86 -86
  30. package/dist/chunk-RHNOMUYZ.js.map +1 -0
  31. package/dist/{chunk-CR37IINZ.js → chunk-SQP6A5AG.js} +2 -2
  32. package/dist/{chunk-5OEW46QP.js → chunk-TN3XNBQN.js} +2 -2
  33. package/dist/{chunk-7ATCEK7R.js → chunk-U476QMLK.js} +2 -2
  34. package/dist/{chunk-EZDHAX4Z.js → chunk-VOVDWFFP.js} +2 -2
  35. package/dist/{chunk-EZDHAX4Z.js.map → chunk-VOVDWFFP.js.map} +1 -1
  36. package/dist/{chunk-IIJB3OPV.js → chunk-WQTPSXVB.js} +2 -2
  37. package/dist/{chunk-DGCYSQAZ.js → chunk-XC3466Z4.js} +2 -2
  38. package/dist/{chunk-XTXFA5EJ.js → chunk-XPYZBWI7.js} +2 -2
  39. package/dist/{chunk-GPX4LDAX.js → chunk-XV7IHWQE.js} +2 -2
  40. package/dist/{chunk-YMMGY7GR.js → chunk-Y6KR7NXL.js} +2 -2
  41. package/dist/cli.js +1 -1
  42. package/dist/{client-7PLIDORM.js → client-W7VFEYQ3.js} +2 -2
  43. package/dist/{config-3R4EGNUG.js → config-ZVRI3GFZ.js} +2 -2
  44. package/dist/{config-mutate-3PGEBKJ6.js → config-mutate-OM4MI56W.js} +2 -2
  45. package/dist/{config-mutator-LQQOOUZR.js → config-mutator-RK3UQORI.js} +2 -2
  46. package/dist/{contributions-D4O76KGX.js → contributions-3WW5AJ5A.js} +2 -2
  47. package/dist/{doctor-QM4KUMQJ.js → doctor-PLN3QJE4.js} +2 -2
  48. package/dist/{follow-up-tool-X3YPYSP2.js → follow-up-tool-LS4OUMLZ.js} +2 -2
  49. package/dist/{hub-PBJHXL2G.js → hub-J43NXLW3.js} +2 -2
  50. package/dist/index.d.ts +83 -1
  51. package/dist/index.js +1 -1
  52. package/dist/{org-tool-37GNUUAD.js → org-tool-NVCSDX4I.js} +2 -2
  53. package/dist/{program-243AGBJJ.js → program-BRFPOZLO.js} +24 -24
  54. package/dist/{promote-CFI4HJDJ.js → promote-AO6KC3SU.js} +2 -2
  55. package/dist/{query-J6S3GWPY.js → query-W6OYKQ2U.js} +2 -2
  56. package/dist/{query-settings-2NKI7UFN.js → query-settings-2D6NCHCV.js} +2 -2
  57. package/dist/{registry-R2QIR6GI.js → registry-3J5U67DS.js} +2 -2
  58. package/dist/{request-planner-NKGUSV4N.js → request-planner-SDO5MNFV.js} +2 -2
  59. package/dist/{review-candidates-43HXKXWD.js → review-candidates-EAOLCDIK.js} +2 -2
  60. package/dist/{routing-72F2DJTV.js → routing-VDVZ4IYF.js} +2 -2
  61. package/dist/{schedule-tool-V3KMSJHK.js → schedule-tool-65H6URQU.js} +2 -2
  62. package/dist/{scheduler-ZBTMOE3T.js → scheduler-B52UIMKB.js} +2 -2
  63. package/dist/{seat-GYYH2IW5.js → seat-5DLUHBTK.js} +2 -2
  64. package/dist/{select-JNVP4P5N.js → select-Z3JDFC2C.js} +2 -2
  65. package/dist/{set-enabled-U26A4RMI.js → set-enabled-FMI2GXCF.js} +2 -2
  66. package/dist/{sprint-tool-YCDVAF2Y.js → sprint-tool-B2LNMNPB.js} +2 -2
  67. package/dist/tool-AR4BLSYC.js +2 -0
  68. package/dist/{tool-GHQ2FM4T.js → tool-EG6PL6NM.js} +2 -2
  69. package/dist/{tool-JEHJS2SA.js → tool-OVW6DDOO.js} +2 -2
  70. package/dist/{tool-MB3IYEP7.js → tool-RW32VEIV.js} +2 -2
  71. package/dist/{tool-CF7OTKDV.js → tool-YT3WBUHS.js} +2 -2
  72. package/dist/{wiki-6UFGH2OO.js → wiki-7PQ5YVA7.js} +2 -2
  73. package/dist/wiki-enrich-IQZ5Y7A5.js +2 -0
  74. package/package.json +1 -1
  75. package/dist/chunk-MUCWUVOW.js.map +0 -1
  76. package/dist/chunk-Z3FJRBTG.js.map +0 -1
  77. package/dist/tool-K3RAEZKE.js +0 -2
  78. package/dist/wiki-enrich-7LMT3CFV.js +0 -2
  79. /package/dist/{App-ET75JEWK.js.map → App-QRZJGHNK.js.map} +0 -0
  80. /package/dist/{ChatApp-F2NT5M2O.js.map → ChatApp-DYC2WNAP.js.map} +0 -0
  81. /package/dist/{absorb-eval-EA5ESP4Y.js.map → absorb-eval-4FENRVXM.js.map} +0 -0
  82. /package/dist/{adapter-7PKOKXO5.js.map → adapter-5WMQSSQM.js.map} +0 -0
  83. /package/dist/{agent-SDNU6MUI.js.map → agent-UDKXN4QV.js.map} +0 -0
  84. /package/dist/{board-dashboard-PI22IXZN.js.map → board-dashboard-CZXKVKK7.js.map} +0 -0
  85. /package/dist/{chunk-TCBIAKGS.js.map → chunk-4UJDRI7W.js.map} +0 -0
  86. /package/dist/{chunk-KCS737RC.js.map → chunk-5BT4VPJC.js.map} +0 -0
  87. /package/dist/{chunk-U4AUJ6XI.js.map → chunk-5CUOKXOD.js.map} +0 -0
  88. /package/dist/{chunk-PTVDVI2U.js.map → chunk-5QXRGX2F.js.map} +0 -0
  89. /package/dist/{chunk-Y3TXTZYG.js.map → chunk-5RCWAXVK.js.map} +0 -0
  90. /package/dist/{chunk-6HCCMU57.js.map → chunk-5XN2OMBS.js.map} +0 -0
  91. /package/dist/{chunk-V75JESS5.js.map → chunk-6EJJKOMW.js.map} +0 -0
  92. /package/dist/{chunk-IQNKEUEL.js.map → chunk-ABMDDRZL.js.map} +0 -0
  93. /package/dist/{chunk-MELXJ5AR.js.map → chunk-AEFO6ES5.js.map} +0 -0
  94. /package/dist/{chunk-6X7SABYJ.js.map → chunk-AZCGU5XU.js.map} +0 -0
  95. /package/dist/{chunk-EPOQUX4G.js.map → chunk-CIW37UJT.js.map} +0 -0
  96. /package/dist/{chunk-UYDC2YMH.js.map → chunk-D5LIMOI6.js.map} +0 -0
  97. /package/dist/{chunk-3XUAIA7U.js.map → chunk-E3SA7KIZ.js.map} +0 -0
  98. /package/dist/{chunk-EWXY73XA.js.map → chunk-GO4J44UD.js.map} +0 -0
  99. /package/dist/{chunk-34TEBXFP.js.map → chunk-JD5TCX4X.js.map} +0 -0
  100. /package/dist/{chunk-SQJ3IHNL.js.map → chunk-JMRFYGET.js.map} +0 -0
  101. /package/dist/{chunk-HHSPOS7O.js.map → chunk-M6TZ7IIJ.js.map} +0 -0
  102. /package/dist/{chunk-IKOJM4GM.js.map → chunk-NCMPJPXG.js.map} +0 -0
  103. /package/dist/{chunk-ZT4FCL5B.js.map → chunk-NW7B53KD.js.map} +0 -0
  104. /package/dist/{chunk-W2KIJ5LL.js.map → chunk-PSUOF7O5.js.map} +0 -0
  105. /package/dist/{chunk-CR37IINZ.js.map → chunk-SQP6A5AG.js.map} +0 -0
  106. /package/dist/{chunk-5OEW46QP.js.map → chunk-TN3XNBQN.js.map} +0 -0
  107. /package/dist/{chunk-7ATCEK7R.js.map → chunk-U476QMLK.js.map} +0 -0
  108. /package/dist/{chunk-IIJB3OPV.js.map → chunk-WQTPSXVB.js.map} +0 -0
  109. /package/dist/{chunk-DGCYSQAZ.js.map → chunk-XC3466Z4.js.map} +0 -0
  110. /package/dist/{chunk-XTXFA5EJ.js.map → chunk-XPYZBWI7.js.map} +0 -0
  111. /package/dist/{chunk-GPX4LDAX.js.map → chunk-XV7IHWQE.js.map} +0 -0
  112. /package/dist/{chunk-YMMGY7GR.js.map → chunk-Y6KR7NXL.js.map} +0 -0
  113. /package/dist/{client-7PLIDORM.js.map → client-W7VFEYQ3.js.map} +0 -0
  114. /package/dist/{config-3R4EGNUG.js.map → config-ZVRI3GFZ.js.map} +0 -0
  115. /package/dist/{config-mutate-3PGEBKJ6.js.map → config-mutate-OM4MI56W.js.map} +0 -0
  116. /package/dist/{config-mutator-LQQOOUZR.js.map → config-mutator-RK3UQORI.js.map} +0 -0
  117. /package/dist/{contributions-D4O76KGX.js.map → contributions-3WW5AJ5A.js.map} +0 -0
  118. /package/dist/{doctor-QM4KUMQJ.js.map → doctor-PLN3QJE4.js.map} +0 -0
  119. /package/dist/{follow-up-tool-X3YPYSP2.js.map → follow-up-tool-LS4OUMLZ.js.map} +0 -0
  120. /package/dist/{hub-PBJHXL2G.js.map → hub-J43NXLW3.js.map} +0 -0
  121. /package/dist/{org-tool-37GNUUAD.js.map → org-tool-NVCSDX4I.js.map} +0 -0
  122. /package/dist/{program-243AGBJJ.js.map → program-BRFPOZLO.js.map} +0 -0
  123. /package/dist/{promote-CFI4HJDJ.js.map → promote-AO6KC3SU.js.map} +0 -0
  124. /package/dist/{query-J6S3GWPY.js.map → query-W6OYKQ2U.js.map} +0 -0
  125. /package/dist/{query-settings-2NKI7UFN.js.map → query-settings-2D6NCHCV.js.map} +0 -0
  126. /package/dist/{registry-R2QIR6GI.js.map → registry-3J5U67DS.js.map} +0 -0
  127. /package/dist/{request-planner-NKGUSV4N.js.map → request-planner-SDO5MNFV.js.map} +0 -0
  128. /package/dist/{review-candidates-43HXKXWD.js.map → review-candidates-EAOLCDIK.js.map} +0 -0
  129. /package/dist/{routing-72F2DJTV.js.map → routing-VDVZ4IYF.js.map} +0 -0
  130. /package/dist/{schedule-tool-V3KMSJHK.js.map → schedule-tool-65H6URQU.js.map} +0 -0
  131. /package/dist/{scheduler-ZBTMOE3T.js.map → scheduler-B52UIMKB.js.map} +0 -0
  132. /package/dist/{seat-GYYH2IW5.js.map → seat-5DLUHBTK.js.map} +0 -0
  133. /package/dist/{select-JNVP4P5N.js.map → select-Z3JDFC2C.js.map} +0 -0
  134. /package/dist/{set-enabled-U26A4RMI.js.map → set-enabled-FMI2GXCF.js.map} +0 -0
  135. /package/dist/{sprint-tool-YCDVAF2Y.js.map → sprint-tool-B2LNMNPB.js.map} +0 -0
  136. /package/dist/{tool-K3RAEZKE.js.map → tool-AR4BLSYC.js.map} +0 -0
  137. /package/dist/{tool-GHQ2FM4T.js.map → tool-EG6PL6NM.js.map} +0 -0
  138. /package/dist/{tool-JEHJS2SA.js.map → tool-OVW6DDOO.js.map} +0 -0
  139. /package/dist/{tool-MB3IYEP7.js.map → tool-RW32VEIV.js.map} +0 -0
  140. /package/dist/{tool-CF7OTKDV.js.map → tool-YT3WBUHS.js.map} +0 -0
  141. /package/dist/{wiki-6UFGH2OO.js.map → wiki-7PQ5YVA7.js.map} +0 -0
  142. /package/dist/{wiki-enrich-7LMT3CFV.js.map → wiki-enrich-IQZ5Y7A5.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{Cc as m,sc as l}from"./chunk-EZDHAX4Z.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{Cc as m,sc as l}from"./chunk-VOVDWFFP.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-TCBIAKGS.js.map
4
+ //# sourceMappingURL=chunk-4UJDRI7W.js.map
@@ -1,7 +1,7 @@
1
- import{Cc as S,qc as b,rc as k,uc as x}from"./chunk-EZDHAX4Z.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{Cc as S,qc as b,rc as k,uc as x}from"./chunk-VOVDWFFP.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-KCS737RC.js.map
7
+ //# sourceMappingURL=chunk-5BT4VPJC.js.map
@@ -1,4 +1,4 @@
1
- import{a as I}from"./chunk-IMLAPB7G.js";import{d as le}from"./chunk-QPABR72X.js";import{b as ue}from"./chunk-KP7KDLZ2.js";import{o as k}from"./chunk-BXK5S2KK.js";import{Ra as oe,Sa as se,Ua as ie,Va as ae,ab as $,gb as ot,o as B,r as rt}from"./chunk-EZDHAX4Z.js";import{accessSync as lt,closeSync as ut,constants as ct,existsSync as fe,openSync as pt,readFileSync as dt,readSync as ft,statSync as mt}from"node:fs";import{dirname as O,join as L}from"node:path";import{fileURLToPath as gt}from"node:url";import{homedir as ht}from"node:os";import{join as ce,win32 as j}from"path";function E(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var U="agentx-helper.exe";function st(e){return j.join(e,"Programs","AgentX",U)}var pe="AgentX Helper.app";function X(e){return ce(e,"Applications",pe,"Contents/MacOS/agentx-mac-helper")}function it(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&E(e)==="macos"?r:void 0}function de(e){let t=it(e.platform,e.env);if(t)return t;let n=E(e.platform);if(n==="macos"){let r=X(e.home);return e.exists(r)||!e.root?r:ce(e.root,"apps/mac-helper/build",pe,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||j.join(e.home,"AppData","Local"),o=st(r);return e.exists(o)||!e.root?o:j.join(e.root,"apps","win-helper","build",U)}return null}function at(e){let t=E(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${U} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function fn(e){let t=E(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=at(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var J="tn.acme.agentx.voice",bn="AgentX Desktop.app",kn="AgentX Helper.app";function xn(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 vn(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 G(e){return`'${e.replace(/'/g,"'\\''")}'`}var me="/usr/bin:/bin:/usr/sbin:/sbin";function An(e,t){return t||[...new Set([...e?[O(e)]:[],...me.split(":")])].join(":")}function T(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function Nn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?T(t[1]):me}var Pn=e=>/agentx\.voice.*\.plist$/.test(e);function Rn(e,t){let n=null,r=[];for(let{file:o,plist:s}of[...t].sort((i,a)=>i.file<a.file?-1:1)){let i=s.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],a=s.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!i||!a||!T(a).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:T(i)}):n={file:o,label:T(i)})}return{keep:n??{file:L(e,`${J}.plist`),label:J},remove:r}}function ge(e,t,n){for(let r of t.split(":"))if(r&&n(L(r,e)))return L(r,e);return null}function Cn(e){try{if(lt(e,ct.X_OK),!mt(e).isFile())return!1;let t=pt(e,"r"),n=Buffer.alloc(2);try{ft(t,n,0,2,0)}finally{ut(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function $n(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 ${G(e.cwd)} && ${G(e.node)} ${G(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{a as I}from"./chunk-IMLAPB7G.js";import{d as le}from"./chunk-QPABR72X.js";import{b as ue}from"./chunk-KP7KDLZ2.js";import{o as k}from"./chunk-BXK5S2KK.js";import{Ra as oe,Sa as se,Ua as ie,Va as ae,ab as $,gb as ot,o as B,r as rt}from"./chunk-VOVDWFFP.js";import{accessSync as lt,closeSync as ut,constants as ct,existsSync as fe,openSync as pt,readFileSync as dt,readSync as ft,statSync as mt}from"node:fs";import{dirname as O,join as L}from"node:path";import{fileURLToPath as gt}from"node:url";import{homedir as ht}from"node:os";import{join as ce,win32 as j}from"path";function E(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var U="agentx-helper.exe";function st(e){return j.join(e,"Programs","AgentX",U)}var pe="AgentX Helper.app";function X(e){return ce(e,"Applications",pe,"Contents/MacOS/agentx-mac-helper")}function it(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&E(e)==="macos"?r:void 0}function de(e){let t=it(e.platform,e.env);if(t)return t;let n=E(e.platform);if(n==="macos"){let r=X(e.home);return e.exists(r)||!e.root?r:ce(e.root,"apps/mac-helper/build",pe,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||j.join(e.home,"AppData","Local"),o=st(r);return e.exists(o)||!e.root?o:j.join(e.root,"apps","win-helper","build",U)}return null}function at(e){let t=E(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${U} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function fn(e){let t=E(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=at(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var J="tn.acme.agentx.voice",bn="AgentX Desktop.app",kn="AgentX Helper.app";function xn(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 vn(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 G(e){return`'${e.replace(/'/g,"'\\''")}'`}var me="/usr/bin:/bin:/usr/sbin:/sbin";function An(e,t){return t||[...new Set([...e?[O(e)]:[],...me.split(":")])].join(":")}function T(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function Nn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?T(t[1]):me}var Pn=e=>/agentx\.voice.*\.plist$/.test(e);function Rn(e,t){let n=null,r=[];for(let{file:o,plist:s}of[...t].sort((i,a)=>i.file<a.file?-1:1)){let i=s.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],a=s.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!i||!a||!T(a).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:T(i)}):n={file:o,label:T(i)})}return{keep:n??{file:L(e,`${J}.plist`),label:J},remove:r}}function ge(e,t,n){for(let r of t.split(":"))if(r&&n(L(r,e)))return L(r,e);return null}function Cn(e){try{if(lt(e,ct.X_OK),!mt(e).isFile())return!1;let t=pt(e,"r"),n=Buffer.alloc(2);try{ft(t,n,0,2,0)}finally{ut(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function $n(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 ${G(e.cwd)} && ${G(e.node)} ${G(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??J)}</string>
@@ -36,4 +36,4 @@ function run(argv) {
36
36
  `),on(r,n)}var un=5*6e4;function fo(e,t,n=Date.now()){let r=ne(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=un)?!1:r.items[`card:${t}`]?.state!=="failed"}var re=24*36e5;function et(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 cn(e,t,n,r){let o=Date.parse(e.expires),s=[w(e.ask,k.ask)];return e.choices?.length&&s.push(...e.choices.map((i,a)=>`${a+1}. ${i}`)),e.recommend&&s.push(`Recommended: ${w(e.recommend,k.recommend)}`),s.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,k.title),notes:s.join(`
37
37
  `),due:et(r,t,o),priority:Number.isFinite(o)&&o-r<=re?"high":"none"}}function pn(e,t,n,r){let o=[w(e.question||e.text,k.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],s=e.dueAt??void 0;return{key:`request:${e.id}`,title:ee(e,k.title).headline,notes:o.join(`
38
38
  `),due:et(r,t,s),priority:s!==void 0&&s-r<=re?"high":"none"}}async function mo(e){let{root:t,settings:n,tasks:r,log:o}=e,s=e.now??Date.now(),i=new Date(s).toISOString(),a={created:0,completed:0,dismissed:0,failed:0},l=ne(t);delete l.lastError;let c=u=>{l.lastError={at:i,message:u}},f=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>s&&f.set(`card:${u.id}`,cn(u,n,e.answerUrl,s));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&f.set(`request:${u.id}`,pn(u,n,e.answerUrl,s))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Qe(t,l),a}let h=!0,S=new Map,tt=async u=>{if(!S.has(u))try{S.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),S.set(u,null),h=!1}return S.get(u)};for(let[u,p]of Object.entries(l.items)){if(p.state!=="open"||!p.id)continue;let d=await tt(p.list);if(d)if(f.has(u))d.has(p.id)||(l.items[u]={...p,state:"dismissed",at:i},a.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(b){o(`[mirror] ${u}: could not complete its task: ${b?.message??b}`),c(String(b?.message??b));continue}l.items[u]={...p,state:"completed",at:i},a.completed++}}let R=null,W="",F=0,N=[];for(let[u,p]of f){let d=l.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=te)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(g){o(`[mirror] could not make list "${n.list}": ${g?.message??g}`),W=String(g?.message??g),c(W),R=!1}let b=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:g}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});l.items[u]={id:g,list:n.list,state:"open",at:i,createdAt:i,failures:0},a.created++}catch(g){let C=String(g?.message??g);u.startsWith("card:")&&F++;let H=b+1;l.items[u]={list:n.list,state:"failed",at:i,failures:H,lastError:C},c(C),a.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${te}): ${C}`),H===te&&N.push({title:p.title,message:C})}}F&&o(`[mirror] ${F} card(s) could not be added to Reminders; the Mac popup shows them instead`);let nt=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(N.length&&!(s-nt<re)){let u=N[0],p=N.length>1?` (and ${N.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),l.failureToldAt=i}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}h&&(l.checkedAt=i,l.cards=n.include.includes("card"));for(let[u,p]of Object.entries(l.items))p.state!=="open"&&!f.has(u)&&s-Date.parse(p.at)>ln&&delete l.items[u];return Qe(t,l),a}var Ye=5*6e4;function go(e,t,n,r,o=Date.now()){let s=ne(e),i=l=>{let c=l?Date.parse(l):NaN;return c>=n&&c<r},a={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[l,c]of Object.entries(s.items))!c.id||!i(c.createdAt)||(l.startsWith("card:")?a.created.cards++:a.created.requests++);for(let l of t){if(!i(l.created_at))continue;a.raised++;let c=s.items[`card:${l.id}`];if(c?.id)continue;let f=Date.parse(l.created_at);if((l.status==="pending"?NaN:Date.parse(l.decided_at??""))-f<=Ye){a.closedFast++;continue}if(l.status==="pending"&&o-f<=Ye){a.tooNew++;continue}let S=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";a.missed.push({id:l.id,title:l.title,reason:S})}return a}function ho(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Hr as a,Br as b,jt as c,jr as d,Be as e,Jt as f,Ue as g,Ur as h,zr as i,Xe as j,Y as k,Z as l,Vr as m,Qr as n,Yt as o,Yr as p,Zr as q,eo as r,ee as s,w as t,en as u,io as v,E as w,de as x,at as y,fn as z,bn as A,kn as B,xn as C,vn as D,An as E,Nn as F,Pn as G,Rn as H,ge as I,Cn as J,$n as K,In as L,En as M,yt as N,P as O,ke as P,Q,Me as R,Dr as S,Mr as T,_r as U,ne as V,fo as W,mo as X,go as Y,ho as Z};
39
- //# sourceMappingURL=chunk-U4AUJ6XI.js.map
39
+ //# sourceMappingURL=chunk-5CUOKXOD.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-YMMGY7GR.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-DCIYOPJF.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-Y6KR7NXL.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-DCIYOPJF.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-PTVDVI2U.js.map
6
+ //# sourceMappingURL=chunk-5QXRGX2F.js.map
@@ -1,4 +1,4 @@
1
- import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-7YOLZGB5.js";import{b as qt,c as Gt}from"./chunk-IH65GDJR.js";import{b as Ct,f as Ft,g as _t,j as Ht,l as Bt,m as Kt,s as zt}from"./chunk-ZT4FCL5B.js";import{a as Lt}from"./chunk-GV7S5BAX.js";import{c as Ut}from"./chunk-SZDACK6O.js";import{b as Mt,d as Et,e as jt}from"./chunk-5ONH4ITT.js";import{e as Nt,g as Ot,h as Dt,i as Le}from"./chunk-JRAG37V5.js";import{a as Pt,b as Ce,d as Fe,e as Wt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Tt}from"./chunk-A7JSRDJL.js";import{c as At,d as St}from"./chunk-AHWWJ7AF.js";import{y as xt,z as Tr}from"./chunk-YMMGY7GR.js";import{b as Rt,f as Wr}from"./chunk-72SZI2UW.js";import{Va as je,gb as Pr}from"./chunk-EZDHAX4Z.js";import{j as Ee,r as xr}from"./chunk-N47Y5ADQ.js";import{existsSync as Nr,mkdirSync as Jt,readFileSync as Or,writeFileSync as Dr,renameSync as Mr}from"fs";import{resolve as Yt,dirname as Er}from"path";var Vt=class{filePath;log;constructor(e={}){let t=e.baseDir??Yt(process.cwd(),".agentx");this.filePath=Yt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Nr(this.filePath))return{version:1,overrides:{}};try{let e=Or(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Jt(Er(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Dr(t,JSON.stringify(e,null,2)),Mr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let i=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),i}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as tn,writeFileSync as He,appendFileSync as _r,mkdirSync as Lr,existsSync as nn,statSync as Ur}from"fs";import{resolve as ge}from"path";var Qt="[Agent Memory \u2014 persistent facts from past conversations]",jr=2400;function Zt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Cr(n,e=Date.now()){let t=Et(n,e),r=n.undated?"UNVERIFIED (never checked) ":Zt(t,Nt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Fr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Tt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Dt(n,e);return{line:`- [${n.category}] ${Zt(o,Ot(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Xt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Qt.length,i=!1;for(let a of n){let d=e.length>0?jt(a.content,e):null,u,c,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),u=Cr(d,t),c=d.id}else u=Fr(a,t),d&&(u.line+=` [differs from wiki ${d.id}]`);let f=u.unverified&&!i?Le.length:0;if(s+f+u.line.length>jr)break;r.push({fact:a,...u,...c?{wikiRef:c}:{}}),s+=f+u.line.length,f&&(i=!0)}return r}function en(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Qt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
1
+ import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-7YOLZGB5.js";import{b as qt,c as Gt}from"./chunk-IH65GDJR.js";import{b as Ct,f as Ft,g as _t,j as Ht,l as Bt,m as Kt,s as zt}from"./chunk-NW7B53KD.js";import{a as Lt}from"./chunk-GV7S5BAX.js";import{c as Ut}from"./chunk-SZDACK6O.js";import{b as Mt,d as Et,e as jt}from"./chunk-5ONH4ITT.js";import{e as Nt,g as Ot,h as Dt,i as Le}from"./chunk-JRAG37V5.js";import{a as Pt,b as Ce,d as Fe,e as Wt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Tt}from"./chunk-A7JSRDJL.js";import{c as At,d as St}from"./chunk-AHWWJ7AF.js";import{y as xt,z as Tr}from"./chunk-Y6KR7NXL.js";import{b as Rt,f as Wr}from"./chunk-72SZI2UW.js";import{Va as je,gb as Pr}from"./chunk-VOVDWFFP.js";import{j as Ee,r as xr}from"./chunk-N47Y5ADQ.js";import{existsSync as Nr,mkdirSync as Jt,readFileSync as Or,writeFileSync as Dr,renameSync as Mr}from"fs";import{resolve as Yt,dirname as Er}from"path";var Vt=class{filePath;log;constructor(e={}){let t=e.baseDir??Yt(process.cwd(),".agentx");this.filePath=Yt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Nr(this.filePath))return{version:1,overrides:{}};try{let e=Or(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Jt(Er(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Dr(t,JSON.stringify(e,null,2)),Mr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let i=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),i}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as tn,writeFileSync as He,appendFileSync as _r,mkdirSync as Lr,existsSync as nn,statSync as Ur}from"fs";import{resolve as ge}from"path";var Qt="[Agent Memory \u2014 persistent facts from past conversations]",jr=2400;function Zt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Cr(n,e=Date.now()){let t=Et(n,e),r=n.undated?"UNVERIFIED (never checked) ":Zt(t,Nt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Fr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Tt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Dt(n,e);return{line:`- [${n.category}] ${Zt(o,Ot(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Xt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Qt.length,i=!1;for(let a of n){let d=e.length>0?jt(a.content,e):null,u,c,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),u=Cr(d,t),c=d.id}else u=Fr(a,t),d&&(u.line+=` [differs from wiki ${d.id}]`);let f=u.unverified&&!i?Le.length:0;if(s+f+u.line.length>jr)break;r.push({fact:a,...u,...c?{wikiRef:c}:{}}),s+=f+u.line.length,f&&(i=!0)}return r}function en(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Qt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
2
2
  `)}var rn=200,Hr=7,on=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ge(e,".agentx/memory"),this.ledger=new Mt(ge(e,".agentx/wiki")),nn(this.memoryDir)||Lr(this.memoryDir,{recursive:!0})}filePath(e){return ge(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ce(t.content)||ne(t.content))return!1;let r=t.source.trust??Pt(t.source.channel),o=t.review??Wt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return _r(this.filePath(e),JSON.stringify(s)+`
3
3
  `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!nn(t))return[];try{let{mtimeMs:r,size:o}=Ur(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let a=tn(t,"utf-8").split(`
4
4
  `).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(_e);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),i=ge(this.memoryDir,`${t}_bm25_cache.json`),a=St(s,i),d=At(e,a),u=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=u.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return en(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Xt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let i of r)if(o.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let a=i.intervalDays||1;i.intervalDays=Math.min(a*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),s=!0}s&&He(this.filePath(e),r.map(i=>JSON.stringify(i)).join(`
@@ -39,4 +39,4 @@ ${n.text}`}async function Pe(n,e){let t=n.channels[e.channel],r={channel:e.chann
39
39
  `).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let i=JSON.parse(r[s]);(!e||i.person===e)&&o.push(i)}catch{}return o}load(){if(kt(this.file))try{let e=JSON.parse(bt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){ur(pr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${gr(4).toString("hex")}.tmp`;cr(t,JSON.stringify(e,null,2)+`
40
40
  `,{encoding:"utf-8",mode:384}),lr(t,this.file)}};import{extname as bi}from"path";var hr=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,wr=/<agentx-artifact>[\s\S]*$/i;function dl(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(hr,(i,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let u=d.mime,c=u.startsWith("image/")?"image":u==="application/pdf"?"pdf":u.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:u})}}catch{}return""});return{text:(t?s.replace(wr,""):s).trim(),artifacts:r}}function ul(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(hr,(s,i)=>{try{let a=JSON.parse(i.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});r=(e?o.replace(wr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,i)=>s===void 0||i===void 0?o:`[${s||i}](${i})`)}var vi={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},ll={bytes:20*1024*1024,perMessage:20,pathChars:512};function cl(n){return vi[bi(n).toLowerCase()]??null}var Ii=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ![what it shows](https://...)."].join(`
41
41
  `);function pl(n,e,t){return n==="app"&&e&&t!==!1?Ii:void 0}import{lstatSync as It,mkdirSync as $i,readdirSync as Ai,realpathSync as vt,unlinkSync as Si}from"fs";import{join as De,resolve as yr}from"path";var kr=".agentx/outbox",Ri=7*24*60*60*1e3;function xi(n,e){try{let t=vt(yr(e,n)),r=De(t,kr);return vt(r)===r&&It(r).isDirectory()?r:null}catch{return null}}function hl(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=vt(yr(t,n));It(De(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||$i(De(o,kr),{recursive:!0})}catch{return 0}let r=xi(n,t);return r?br(r,(e.now??Date.now())-(e.maxAgeMs??Ri)):0}function br(n,e){let t=0;for(let r of Ai(n)){let o=De(n,r);try{let s=It(o);s.isDirectory()?t+=br(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(Si(o),t++)}catch{}}return t}export{Vt as a,on as b,sn as c,qi as d,qr as e,Gi as f,zr as g,Yi as h,Vi as i,Qi as j,Zi as k,Xi as l,ea as m,ta as n,Vr as o,na as p,ra as q,aa as r,Ge as s,oo as t,da as u,ua as v,so as w,la as x,fn as y,fa as z,ga as A,mn as B,hn as C,co as D,ka as E,ba as F,$a as G,Aa as H,x as I,re as J,A as K,Je as L,xo as M,Qe as N,U as O,et as P,nt as Q,id as R,ad as S,mt as T,_s as U,qs as V,wt as W,zo as X,si as Y,Tu as Z,Nu as _,Ou as $,Du as aa,Mu as ba,ai as ca,di as da,Eu as ea,ju as fa,Cu as ga,Fu as ha,Uu as ia,Hu as ja,Bu as ka,Ku as la,qu as ma,Gu as na,zu as oa,Ju as pa,Yu as qa,Vu as ra,Qu as sa,gi as ta,Zu as ua,Xu as va,el as wa,tl as xa,mr as ya,dl as za,ul as Aa,ll as Ba,cl as Ca,pl as Da,kr as Ea,hl as Fa};
42
- //# sourceMappingURL=chunk-Y3TXTZYG.js.map
42
+ //# sourceMappingURL=chunk-5RCWAXVK.js.map
@@ -1,4 +1,4 @@
1
- import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Kb as Ge,Wa as Ke,Xa as Ye,Ya as Je,_a as Xe,c as Le,ua as _,za as qe}from"./chunk-3XUAIA7U.js";import{a as V}from"./chunk-IMLAPB7G.js";import{k as Be}from"./chunk-EWXY73XA.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Ne,e as We}from"./chunk-LQE73AZR.js";import{a as Z,b as Ue}from"./chunk-TCBIAKGS.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{ia as G}from"./chunk-Y3TXTZYG.js";import{b as ue}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-KCS737RC.js";import{s as ge,u as Oe}from"./chunk-BXK5S2KK.js";import{b as He}from"./chunk-SQJ3IHNL.js";import{c as De,d as Me}from"./chunk-OWNQ2FD4.js";import{a as je}from"./chunk-ROLSSYXE.js";import{Cc as xe,J as le,Lb as Ee,M as F,S as Za,Sb as at,Va as ce,Wa as Pe,gb as et,nc as pe,rc as q,sc as Re}from"./chunk-EZDHAX4Z.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
1
+ import{a as Ze,b as k,c as D,d as ea,e as fe,f as he,g as H,h as be,i as L,j as N,n as aa,o as ta,p as ra,q as na}from"./chunk-EFGAPAYZ.js";import{e as Ve,i as Qe}from"./chunk-QAWKN2N4.js";import{b as me}from"./chunk-DODL5POT.js";import{Kb as Ge,Wa as Ke,Xa as Ye,Ya as Je,_a as Xe,c as Le,ua as _,za as qe}from"./chunk-E3SA7KIZ.js";import{a as V}from"./chunk-IMLAPB7G.js";import{k as Be}from"./chunk-GO4J44UD.js";import{b as Q}from"./chunk-2VDO2HEK.js";import{c as Ne,e as We}from"./chunk-LQE73AZR.js";import{a as Z,b as Ue}from"./chunk-4UJDRI7W.js";import{b as Fe}from"./chunk-MRIVENBY.js";import{ia as G}from"./chunk-5RCWAXVK.js";import{b as ue}from"./chunk-7AB3QUGH.js";import{a as K,b as X}from"./chunk-5BT4VPJC.js";import{s as ge,u as Oe}from"./chunk-BXK5S2KK.js";import{b as He}from"./chunk-JMRFYGET.js";import{c as De,d as Me}from"./chunk-OWNQ2FD4.js";import{a as je}from"./chunk-ROLSSYXE.js";import{Cc as xe,J as le,Lb as Ee,M as F,S as Za,Sb as at,Va as ce,Wa as Pe,gb as et,nc as pe,rc as q,sc as Re}from"./chunk-VOVDWFFP.js";import{existsSync as Y,readFileSync as xa,writeFileSync as ga,appendFileSync as lt,mkdirSync as ct}from"fs";import{dirname as pt,resolve as M}from"path";import{fileURLToPath as xt}from"url";import{hostname as gt}from"os";import{spawn as ut}from"child_process";var ve=`:root {
2
2
  /* --- Brand (agentina) --------------------------------------------- */
3
3
  --ax-blue: #2979FF;
4
4
  --ax-blue-d: #1B5FD9;
@@ -2903,4 +2903,4 @@ tr:hover td { background: var(--bg-hover); }
2903
2903
  ${r}`).all(a,...t,...n).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Qo(e,a){return Ua(e,a,ce,"ORDER BY created_at")}function Zo(e,a,t=50){return Ua(e,a,[...ce,...Pe],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(t,500)))}at();var ze="member:",pr=90,xr="members",gr="tailscale-user-login",ur=400,mr=60*60*1e3;function fr(e){let a=e.scopes.find(t=>t.startsWith(ze));return a?a.slice(ze.length):null}function qa(e,a){if(!e)return null;let t=a.verify(e),r=t?fr(t):null;return t&&r?{rec:t,personId:r}:null}function ii(e,a){let t=e.people().find(s=>s.id===a);if(!t)return{ok:!1,error:`No person "${a}". Add them first: agentx people add ${a} --name "\u2026"`};let{token:r,record:n}=e.tokens.create({name:`${t.name} (machine not paired yet)`,scopes:[`${ze}${t.id}`],expiresInDays:pr}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:n.id,name:t.id});return e.members.log({person:t.id,device:n.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:n.id,person:t}}var hr=Math.round(Ne/6e4);function br(e){return e==="client"?"Your project":"My work"}function si(e){let a=br(e.person.role),t=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${a}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${a}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",t,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${We(e.code)}`,` The code works once, for ${hr} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
2904
2904
  `)}var vr="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",wr="Too many machines are waiting for the owner's answer. Try again later.",Fa="That code didn't work. Check it, or ask the person who invited you for a new one.",Ka=(e,a)=>{let t=e.headers[a];return(Array.isArray(t)?t[0]:t||"").trim()};function Ya(e){let a=e.socket?.remoteAddress||"";return a==="127.0.0.1"||a==="::1"||a==="::ffff:127.0.0.1"}function yr(e){if(!Ya(e))return null;let a=Ka(e,gr).toLowerCase();return a?a.slice(0,80):null}function kr(e){let a=e.socket?.remoteAddress||"unknown";if(!Ya(e))return a;let t=Ka(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(t)?t:a}function $r(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function _r(e){return e.identities.map(Ee).filter(a=>!!a&&a.channel==="tailscale").map(a=>a.value)}async function di(e,a){let t=Date.now(),r=a.now??Date.now,n=a.log??(b=>console.log(b)),o=kr(e),i=a.limiter.retryAfter(o);if(i>0)return n(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,d="";try{let b=await Q(e,2048);s=b.code,d=$r(b.machine)}catch{}let l=a.codes.redeem(s),c=l?qa(l.token,a.tokens):null;if(await Cr(t,a.minMs??ur),!l||!c)return a.limiter.fail(o),n(`[member] pair-code failed from ${o}`),{status:401,body:{error:Fa}};a.limiter.succeed(o);let{rec:m,personId:g}=c,u=a.people().find(b=>b.id===g);if(!u)return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),n(`[member] pair-code for ${g} refused from ${o}: person no longer listed`),{status:403,body:{error:Fa}};let x=yr(e),f=_r(u);if(f.length&&(!x||!f.includes(x)))return a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:`network login ${x??"missing"}; expected ${f.join(" or ")}`}),n(`[member] ${g}: pairing from ${o} refused: the network says "${x??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:vr}};let A=d||"Unnamed machine",y=u.name.slice(0,40),v=Oe(a.root,{title:`New machine for ${y}`,ask:`From ${o}, ${x?`network login ${x}`:"no network login reported"}. Machine name, as typed there: "${A}". Let it see their own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:xr},{now:r()});return v.ok?(a.members.add({tokenId:m.id,personId:g,name:A,state:"pending",cardId:v.card.id,address:o,...x?{network:x}:{},createdAt:new Date(r()).toISOString()}),a.members.log({person:g,device:m.id,event:"paired",address:o,detail:A}),n(`[member] ${g} paired "${A}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:g,name:A,state:"pending"},token:l.token}):(a.tokens.revoke(m.id),a.members.log({person:g,device:m.id,event:"refused",address:o,detail:v.error}),n(`[member] ${g}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:wr}})}var de="this machine is not paired",Sr="waiting for the owner to approve this machine";function Ja(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function li(e,a){return a.state==="pending"&&a.cardId?Ja(ge(e,a.cardId)):null}function ci(e,a,t){let r=a.now??Date.now,n=a.log??(c=>console.log(c)),o=qa(e,a.tokens);if(!o)return{ok:!1,status:401,error:de};let{rec:i,personId:s}=o,d=a.members.byToken(i.id);if(!d||d.state==="removed"||d.personId!==s)return{ok:!1,status:401,error:de};if(a.people&&!a.people().some(c=>c.id===s))return Xa(a,i.id,"person no longer listed"),n(`[member] ${s}: "${d.name}" ended: person no longer listed`),{ok:!1,status:401,error:de};if(d.state==="pending"){let c=d.cardId?ge(a.root,d.cardId):null,m=Ja(c);if(m==="yes")d=a.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??d,a.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),n(`[member] ${s}: "${d.name}" approved`);else if(m==="no"){let g=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return a.tokens.revoke(i.id),a.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:g}),a.members.log({person:s,device:i.id,event:"refused",detail:g}),n(`[member] ${s}: "${d.name}" refused: ${g}`),{ok:!1,status:401,error:de}}else return{ok:!1,status:403,error:Sr,waiting:!0}}let l=d.lastSeenAt?Date.parse(d.lastSeenAt):0;return t&&(r()-l>=mr||d.lastAddress!==t)&&(d=a.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:t})??d,a.members.log({person:s,device:i.id,event:"signed-in",address:t})),{ok:!0,device:d,personId:s,rec:i}}function Xa(e,a,t="removed by the owner"){let r=e.members.byToken(a);if(!r)return null;e.tokens.revoke(a);let n=e.members.update(a,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:t});return e.members.log({person:r.personId,device:a,event:"removed",detail:t}),n}function pi(e,a){return e.members.devices(a).filter(t=>t.state!=="removed").map(t=>Xa(e,t.tokenId,"person removed by the owner")).filter(t=>!!t)}async function Cr(e,a){let t=e+a-Date.now();t>0&&await new Promise(r=>setTimeout(r,t))}var Ga=["gitlab","github"];function Ar(e,a,t){let r=String(a||"").trim().toLowerCase();if(!Ga.includes(r))throw new Error(`Request status works on ${Ga.join(" and ")}, not on "${a}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let n=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=t?[...new Set([...n,r])]:n.filter(o=>o!==r),`request status on ${r} is ${t?"on":"off"}`}function ui(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(a=>String(a).toLowerCase()):[]}function mi(e){let{summary:a}=Z(t=>Ar(t,e?.channel,!!e?.enabled));return{summary:a}}var hi="https://myaccount.google.com/apppasswords";function bi(e){let a=e.split("@")[1]?.toLowerCase()??"";if(a==="gmail.com"||a==="googlemail.com")return{imapHost:"imap.gmail.com",imapPort:993,smtpHost:"smtp.gmail.com",smtpPort:465}}function vi(e){let a=e.user&&e.user!==e.address?{user:e.user}:{};return{agent:e.agent,address:e.address,imap:{host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,...a,password:`\${${e.passwordEnv}}`},smtp:{host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465},allowFrom:e.allowFrom,send:e.send}}function wi(e){return`EMAIL_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_PASSWORD`}function $i(e){return`${e.name} <${e.from}> via ${e.host}:${e.port}`}async function _i(e,a){return Be({host:e.host,port:e.port,secure:e.secure,user:e.user,password:e.password},{name:e.name,address:e.from},a,{"Auto-Submitted":"auto-generated"})}function Si(e,a){return{to:e,subject:`${a.name}: test mail`,text:[`This is a test mail from ${a.name}.`,"","If it reached you, AgentX can send mail through this sender.","You can ignore it."].join(`
2905
2905
  `)}}function Ai(e){return new Set(Object.entries(e).filter(([,a])=>a?.wiki?.absorb?.enabled===!1).map(([a])=>a))}function Ti(e,a){return a.only?{agents:[a.only],skipped:[]}:{agents:e.filter(t=>!a.off.has(t)),skipped:e.filter(t=>a.off.has(t))}}function Ii(e,a){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===a?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function zi(e,a){if(a){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Tr="https://ntfy.sh";function Ei(e){return{enabled:!!e?.enabled,server:e?.server||Tr,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Ri(e,a){let t={...e??{}};if("enabled"in a&&(t.enabled=!!a.enabled),"server"in a){let r=String(a.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");t.server=r}if("topic"in a){let r=String(a.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");t.topic=r}if("token"in a){let r=String(a.token??"").trim();r?t.token=r:delete t.token}if(t.enabled&&!t.topic)throw new Error("set a topic before enabling ntfy");return t}Za();function Va(e){return/^(agent|person):/.test(e)?F(e):`person:${e}`}function ji(e){let a=(e?.projects??[]).filter(t=>t?.id);return a.map(t=>({id:t.id,name:t.name?.trim()||t.id,client:Le(t.id,a),...t.pm?{pm:F(t.pm)}:{},...t.lead?{lead:Va(t.lead)}:{},team:[...new Set((t.team??[]).filter(Boolean).map(F))]})).sort((t,r)=>t.client.localeCompare(r.client)||t.name.localeCompare(r.name)||t.id.localeCompare(r.id))}function Hi(e,a,t){if(!t.lead&&!t.team?.length)return;let r=new Set(Object.keys(e.business?.orgChart||{})),n=new Set((e.people||[]).map(i=>String(i.id))),o={id:a,name:a,client:"",...t.lead?{lead:Va(t.lead)}:{},team:(t.team??[]).map(F)};return Ir([o],r,n)}function Ir(e,a,t){let r=n=>{let o=le(n);return o.kind==="agent"?a.has(o.id)?void 0:`"${o.id}", which is not an agent in business.orgChart`:t.has(o.id)?void 0:`"${o.id}", which is not a person in people`};for(let n of e){if(n.lead){if(le(n.lead).kind!=="person")return`Project ${n.name} is led by "${n.lead}"; a lead is a person (person:<id>), the PM is the agent`;let o=r(n.lead);if(o)return`Project ${n.name} is led by ${o}`}for(let o of n.team){let i=r(o);if(i)return`Project ${n.name} has ${i} in its team`}}}export{ve as a,da as b,ye as c,nt as d,ot as e,it as f,ua as g,mt as h,_n as i,Sn as j,Cn as k,ko as l,Co as m,Ba as n,Yo as o,Jo as p,Rn as q,On as r,It as s,Et as t,ke as u,Dn as v,Mn as w,Rt as x,Bn as y,Un as z,Fn as A,Vo as B,Qo as C,Zo as D,pr as E,xr as F,ii as G,hr as H,br as I,si as J,vr as K,wr as L,yr as M,kr as N,$r as O,_r as P,di as Q,Ja as R,li as S,ci as T,Xa as U,pi as V,Ga as W,Ar as X,ui as Y,mi as Z,hi as _,bi as $,vi as aa,wi as ba,$i as ca,_i as da,Si as ea,Ai as fa,Ti as ga,Ii as ha,zi as ia,Ei as ja,Ri as ka,Va as la,ji as ma,Hi as na,Ir as oa,Qt as pa,go as qa,vo as ra,wo as sa};
2906
- //# sourceMappingURL=chunk-6HCCMU57.js.map
2906
+ //# sourceMappingURL=chunk-5XN2OMBS.js.map
@@ -1,4 +1,4 @@
1
- import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-PTVDVI2U.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-YMMGY7GR.js";import{h as Q}from"./chunk-QUFIUXMQ.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-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-5QXRGX2F.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-Y6KR7NXL.js";import{h as Q}from"./chunk-QUFIUXMQ.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-3R4EGNUG.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-V75JESS5.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-ZVRI3GFZ.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-6EJJKOMW.js.map
@@ -1,4 +1,4 @@
1
- import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-PTVDVI2U.js";import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{c as _,d as x}from"./chunk-AHWWJ7AF.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{y as C,z as K}from"./chunk-YMMGY7GR.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
1
+ import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-5QXRGX2F.js";import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{c as _,d as x}from"./chunk-AHWWJ7AF.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{y as C,z as K}from"./chunk-Y6KR7NXL.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
4
4
  `));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
105
- //# sourceMappingURL=chunk-IQNKEUEL.js.map
105
+ //# sourceMappingURL=chunk-ABMDDRZL.js.map
@@ -1,2 +1,2 @@
1
- import{s as p}from"./chunk-ZT4FCL5B.js";import{b as i,c as u,d as l,e as c}from"./chunk-KCS737RC.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,g=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',m=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function x(e){return m.test(e)}function w(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function S(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function $(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??g,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.report==="exceptions"&&(t.report="exceptions"),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){return e.deliverResult===!1?"(failures only)":e.report==="exceptions"?"(exceptions and failures)":"(results and failures)"}function T(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function A(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function D(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function y(e){return e?.approval?.action==="create"}async function R(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&y(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,x as c,w as d,S as e,$ as f,P as g,T as h,A as i,D as j,y as k,R as l,I as m,O as n};
2
- //# sourceMappingURL=chunk-MELXJ5AR.js.map
1
+ import{s as p}from"./chunk-NW7B53KD.js";import{b as i,c as u,d as l,e as c}from"./chunk-5BT4VPJC.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,g=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',m=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function x(e){return m.test(e)}function w(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function S(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function $(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??g,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.report==="exceptions"&&(t.report="exceptions"),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){return e.deliverResult===!1?"(failures only)":e.report==="exceptions"?"(exceptions and failures)":"(results and failures)"}function T(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function A(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function D(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function y(e){return e?.approval?.action==="create"}async function R(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&y(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,x as c,w as d,S as e,$ as f,P as g,T as h,A as i,D as j,y as k,R as l,I as m,O as n};
2
+ //# sourceMappingURL=chunk-AEFO6ES5.js.map
@@ -1,4 +1,4 @@
1
- import{e as g}from"./chunk-V75JESS5.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-6EJJKOMW.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-6X7SABYJ.js.map
17
+ //# sourceMappingURL=chunk-AZCGU5XU.js.map
@@ -1,8 +1,8 @@
1
- import{a as _,b as O,c as q,d as B,f as L,g as z,h as T,i as b,j as v,k as w}from"./chunk-MELXJ5AR.js";import{a as R,b as P,c as E,d as k,e as D}from"./chunk-KCS737RC.js";import{existsSync as K,readFileSync as Y}from"fs";import J from"cronstrue";var A={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},S={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function g(n){try{return J.toString(n,{use24HourTimeFormat:!1})}catch{return n}}function V(n){if(/\b(noon|midday)\b/.test(n))return S.noon;if(/\bmidnight\b/.test(n))return S.midnight;let e=n.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(e){let r=parseInt(e[1],10),i=e[2]?parseInt(e[2],10):0,a=e[3];return a==="pm"&&r<12&&(r+=12),a==="am"&&r===12&&(r=0),r>23||i>59?null:{h:r,m:i}}return null}function H(n){let e=n.trim().toLowerCase();if(!e)return null;let r;if(r=e.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let t=parseInt(r[1],10);return t<1||t>59?null:{cron:`*/${t} * * * *`,human:g(`*/${t} * * * *`),matched:r[0]}}if(/\bevery\s+minute\b/.test(e))return{cron:"* * * * *",human:g("* * * * *"),matched:"every minute"};if(r=e.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let t=parseInt(r[1],10);return t<1||t>23?null:{cron:`0 */${t} * * *`,human:g(`0 */${t} * * *`),matched:r[0]}}if(/\b(every hour|hourly)\b/.test(e))return{cron:"0 * * * *",human:g("0 * * * *"),matched:"every hour"};let i=V(e),a=null;for(let[t,o]of Object.entries(S))if(!(t==="noon"||t==="midnight")&&new RegExp(`\\b(every\\s+)?${t}s?\\b`).test(e)){a=o;break}let d=i||a,m=e.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(m){let t=m[1],o=1;if(t==="last"||(/^\d+(st|nd|rd|th)?$/.test(t)?o=parseInt(t,10):t==="first"||t==="1st"?o=1:t==="2nd"?o=2:t==="3rd"&&(o=3),o<1||o>31))return null;let u=d||{h:9,m:0},p=`${u.m} ${u.h} ${o} * *`;return{cron:p,human:g(p),matched:m[0]}}let s=[],y=Object.keys(A).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${y})s?(?:\\s*(?:,|and|&)\\s*(?:${y})s?)*)\\b`),c=e.match(l);if(c){let t=c[1];for(let o of Object.keys(A))if(new RegExp(`\\b${o}s?\\b`).test(t)){let u=A[o];s.includes(u)||s.push(u)}}if(s.length){let t=d||{h:9,m:0};s.sort((p,h)=>p-h);let o=s.join(","),u=`${t.m} ${t.h} * * ${o}`;return{cron:u,human:g(u),matched:`on ${o}`}}if(/\b(weekday|workday|business day)s?\b/.test(e)){let t=d||{h:9,m:0},o=`${t.m} ${t.h} * * 1-5`;return{cron:o,human:g(o),matched:"weekdays"}}if(/\bweekends?\b/.test(e)){let t=d||{h:9,m:0},o=`${t.m} ${t.h} * * 0,6`;return{cron:o,human:g(o),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(e)||a){let t=d||{h:9,m:0},o=`${t.m} ${t.h} * * *`;return{cron:o,human:g(o),matched:a&&Object.entries(S).find(([,u])=>u===a)?.[0]||"daily"}}if(i){let t=`${i.m} ${i.h} * * *`;return{cron:t,human:g(t),matched:`at ${i.h}:${String(i.m).padStart(2,"0")}`}}return null}function G(n,e){return`${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${e}`}var Z=new Set(["cron","heartbeat","api","a2a","mesh"]),Q=160;function f(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function x(n,e=Q){let r=n.replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1)}\u2026`:r}function ee(n){let e=R(n);if(!K(e))throw new Error(`config not found at ${e}`);return JSON.parse(Y(e,"utf-8"))}function te(n,e){return n?.agents?.[e]?.admin===!0}function ne(n,e,r){return te(n,r.agentId)||e?.createdBy===r.agentId}function re(n,e){let r=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${r}. Agents manage only schedules they created (unless configured admin).`}function oe(n,e){let r=f(n.notify);if(r!=="none"){if(r&&r!=="here"){let i=r.split(":");return i.length<2||!i[0]||!i[1]?"invalid":{channel:i[0],chatId:i.slice(1).join(":")}}if(e.channel&&e.chatId&&!Z.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ie(n,e,r){let i=e.timezone||"UTC",a=e.enabled&&!w(e)?v(b(e.schedule,i,r),i):"\u2014",d=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",m=[`- ${n} [${d}] ${e.schedule} \u2014 ${T(e.schedule)} (${i})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${a}`];return e.notify&&m.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?m.push(` command: ${x(String(e.command))}`):e.prompt&&m.push(` prompt: ${x(String(e.prompt))}`),m.join(`
1
+ import{a as _,b as O,c as q,d as B,f as L,g as z,h as T,i as b,j as v,k as w}from"./chunk-AEFO6ES5.js";import{a as R,b as P,c as E,d as k,e as D}from"./chunk-5BT4VPJC.js";import{existsSync as K,readFileSync as Y}from"fs";import J from"cronstrue";var A={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},S={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function g(n){try{return J.toString(n,{use24HourTimeFormat:!1})}catch{return n}}function V(n){if(/\b(noon|midday)\b/.test(n))return S.noon;if(/\bmidnight\b/.test(n))return S.midnight;let e=n.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(e){let r=parseInt(e[1],10),i=e[2]?parseInt(e[2],10):0,a=e[3];return a==="pm"&&r<12&&(r+=12),a==="am"&&r===12&&(r=0),r>23||i>59?null:{h:r,m:i}}return null}function H(n){let e=n.trim().toLowerCase();if(!e)return null;let r;if(r=e.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let t=parseInt(r[1],10);return t<1||t>59?null:{cron:`*/${t} * * * *`,human:g(`*/${t} * * * *`),matched:r[0]}}if(/\bevery\s+minute\b/.test(e))return{cron:"* * * * *",human:g("* * * * *"),matched:"every minute"};if(r=e.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let t=parseInt(r[1],10);return t<1||t>23?null:{cron:`0 */${t} * * *`,human:g(`0 */${t} * * *`),matched:r[0]}}if(/\b(every hour|hourly)\b/.test(e))return{cron:"0 * * * *",human:g("0 * * * *"),matched:"every hour"};let i=V(e),a=null;for(let[t,o]of Object.entries(S))if(!(t==="noon"||t==="midnight")&&new RegExp(`\\b(every\\s+)?${t}s?\\b`).test(e)){a=o;break}let d=i||a,m=e.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(m){let t=m[1],o=1;if(t==="last"||(/^\d+(st|nd|rd|th)?$/.test(t)?o=parseInt(t,10):t==="first"||t==="1st"?o=1:t==="2nd"?o=2:t==="3rd"&&(o=3),o<1||o>31))return null;let u=d||{h:9,m:0},p=`${u.m} ${u.h} ${o} * *`;return{cron:p,human:g(p),matched:m[0]}}let s=[],y=Object.keys(A).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${y})s?(?:\\s*(?:,|and|&)\\s*(?:${y})s?)*)\\b`),c=e.match(l);if(c){let t=c[1];for(let o of Object.keys(A))if(new RegExp(`\\b${o}s?\\b`).test(t)){let u=A[o];s.includes(u)||s.push(u)}}if(s.length){let t=d||{h:9,m:0};s.sort((p,h)=>p-h);let o=s.join(","),u=`${t.m} ${t.h} * * ${o}`;return{cron:u,human:g(u),matched:`on ${o}`}}if(/\b(weekday|workday|business day)s?\b/.test(e)){let t=d||{h:9,m:0},o=`${t.m} ${t.h} * * 1-5`;return{cron:o,human:g(o),matched:"weekdays"}}if(/\bweekends?\b/.test(e)){let t=d||{h:9,m:0},o=`${t.m} ${t.h} * * 0,6`;return{cron:o,human:g(o),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(e)||a){let t=d||{h:9,m:0},o=`${t.m} ${t.h} * * *`;return{cron:o,human:g(o),matched:a&&Object.entries(S).find(([,u])=>u===a)?.[0]||"daily"}}if(i){let t=`${i.m} ${i.h} * * *`;return{cron:t,human:g(t),matched:`at ${i.h}:${String(i.m).padStart(2,"0")}`}}return null}function G(n,e){return`${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${e}`}var Z=new Set(["cron","heartbeat","api","a2a","mesh"]),Q=160;function f(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function x(n,e=Q){let r=n.replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1)}\u2026`:r}function ee(n){let e=R(n);if(!K(e))throw new Error(`config not found at ${e}`);return JSON.parse(Y(e,"utf-8"))}function te(n,e){return n?.agents?.[e]?.admin===!0}function ne(n,e,r){return te(n,r.agentId)||e?.createdBy===r.agentId}function re(n,e){let r=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${r}. Agents manage only schedules they created (unless configured admin).`}function oe(n,e){let r=f(n.notify);if(r!=="none"){if(r&&r!=="here"){let i=r.split(":");return i.length<2||!i[0]||!i[1]?"invalid":{channel:i[0],chatId:i.slice(1).join(":")}}if(e.channel&&e.chatId&&!Z.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ie(n,e,r){let i=e.timezone||"UTC",a=e.enabled&&!w(e)?v(b(e.schedule,i,r),i):"\u2014",d=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",m=[`- ${n} [${d}] ${e.schedule} \u2014 ${T(e.schedule)} (${i})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${a}`];return e.notify&&m.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?m.push(` command: ${x(String(e.command))}`):e.prompt&&m.push(` prompt: ${x(String(e.prompt))}`),m.join(`
2
2
  `)}async function F(n,e,r){let i=n?.notifications?.destination;if(!i?.channel||!i?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:i.channel,chatId:i.chatId,accountId:i.accountId},r),"The operator has been notified."}catch(a){return`Could not notify the operator (${a?.message??a}); the request is still recorded.`}}async function he(n,e,r={}){let i=(f(n.action)||"list").toLowerCase(),a=r.now?r.now():new Date,d;try{d=ee(r.configPath)}catch(c){return`Error: ${c.message}`}let m=d.crons||{};if(i==="list"){let c=n.mine===!0,t=Object.entries(m).filter(([,o])=>!c||e&&o?.createdBy===e.agentId);return t.length?t.map(([o,u])=>ie(o,u,a)).join(`
3
3
  `):c?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!d.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let s=f(n.id),y=c=>P(c,{configPath:r.configPath,reload:r.reload});if(i==="create"){let c=f(n.when),t=f(n.prompt);if(!c||!t)return"Error: create needs `when` (plain English) and `prompt`.";let o=H(c);if(!o)return`Error: couldn't parse "${c}". ${O}.`;let u=f(n.agent)||e.agentId;if(!d.agents?.[u])return`Error: agent "${u}" not found on this node.`;let p=f(n.timezone)||_;if(!B(p))return`Error: unknown timezone "${p}".`;let h=s||G(o.matched,u);if(!q(h))return`Error: invalid id "${h}" (letters, digits, "-" and "_" only).`;if(m[h])return`Error: a schedule "${h}" already exists. Pick another \`id\`.`;let $=oe(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let I=f(n.report);if(I&&I!=="always"&&I!=="exceptions")return'Error: `report` must be "always" or "exceptions".';let M={action:"create",requestedBy:e.agentId,requestedAt:a.toISOString()},U=L({parsed:o,agent:u,prompt:t,timezone:p,notify:$,report:I,enabled:!1,createdBy:e.agentId,approval:M}),N=await y(j=>E(j,`crons.${h}`,U));if(!N.success)return`Error: ${N.error}`;let C=v(b(o.cron,p,a),p),W=[`Schedule approval requested by ${e.agentId}`,`Create: ${h}`,`When: ${o.human} \u2014 cron \`${o.cron}\` (${p})`,`Next fire: ${C}`,`Agent: ${u}`,$?`${I==="exceptions"?"Exceptions":"Results"} and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${x(t,400)}`,"",`Approve: agentx schedule approve ${h}`,`Reject: agentx schedule reject ${h}`].join(`
4
4
  `),X=await F(d,r,W);return[`Requested schedule "${h}": ${o.human} (cron ${o.cron}, ${p}); next fire would be ${C}.`,"It is saved DISABLED and will not run until the operator approves it.",X].join(`
5
5
  `)}if(!s)return`Error: ${i} needs \`id\`.`;let l=m[s];if(!l)return`Error: schedule "${s}" not found.`;if(!ne(d,l,e))return re(s,l);if(i==="pause"||i==="resume"){let c=i==="resume";if(c&&w(l))return`"${s}" is still awaiting operator approval; it can't be resumed until approved.`;if(l.enabled===c)return`"${s}" is already ${c?"active":"paused"}.`;let t=await y(o=>E(o,`crons.${s}.enabled`,c));return t.success?`"${s}" ${c?"resumed":"paused"}.`:`Error: ${t.error}`}if(i==="delete"){if(w(l)&&l.approval.requestedBy===e.agentId){let h=await y($=>D($,`crons.${s}`));return h.success?`Withdrew the pending request "${s}".`:`Error: ${h.error}`}if(w(l))return`"${s}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${s}\`) can drop it.`;if(l.approval?.action==="delete")return`Deletion of "${s}" is already awaiting approval.`;let c={action:"delete",requestedBy:e.agentId,requestedAt:a.toISOString()},t=await y(h=>{if(!k(h,`crons.${s}`))throw new Error(`schedule "${s}" not found`);E(h,`crons.${s}.approval`,c)});if(!t.success)return`Error: ${t.error}`;let o=l.timezone||"UTC",u=[`Schedule approval requested by ${e.agentId}`,`Delete: ${s}`,`When: ${T(l.schedule)} \u2014 cron \`${l.schedule}\` (${o})`,`Next fire: ${l.enabled?v(b(l.schedule,o,a),o):"\u2014 (paused)"}`,`Agent: ${l.agent}`,"",`Approve: agentx schedule approve ${s}`,`Reject: agentx schedule reject ${s}`].join(`
6
6
  `),p=await F(d,r,u);return[`Deletion of "${s}" requested. It keeps its current state until the operator approves.`,p].join(`
7
7
  `)}return`Error: unknown action "${i}". Use list, create, pause, resume or delete.`}function fe(n,e=process.env){let r=f(e.AGENTX_AGENT_ID)||f(n.callerAgentId);if(!r)return null;let i=!!(f(e.AGENTX_CHANNEL)&&f(e.AGENTX_CHAT_ID)),a=f(i?e.AGENTX_CHANNEL:n.channel),d=f(i?e.AGENTX_CHAT_ID:n.chatId),m=f(n.accountId);return{agentId:r,channel:a,chatId:d,...m?{accountId:m}:{}}}export{H as a,G as b,he as c,fe as d};
8
- //# sourceMappingURL=chunk-EPOQUX4G.js.map
8
+ //# sourceMappingURL=chunk-CIW37UJT.js.map
@@ -1,4 +1,4 @@
1
- import{Pa as E,Qa as S,Sa as T,Ta as _,Ua as q,a as w,d as R,i as h,l as j,p as $,r as U}from"./chunk-EZDHAX4Z.js";q();U();var H=1e4,N=["issues","prs","all"],X=/^[\w.-]+(?:\/[\w.-]+)+$/,f=e=>typeof e=="string"?e.trim():"";function b(e){let t=f(e.provider).toLowerCase();if(t!=="github"&&t!=="gitlab")return"count.provider must be github or gitlab";let r=f(e.project),n=r.split("/");if(!X.test(r)||n.some(s=>s==="."||s==="..")||t==="github"&&n.length!==2)return t==="github"?'count.project must be "owner/repo"':'count.project must be "group/project"';let o=(f(e.what)||"issues").toLowerCase();if(!N.includes(o))return`count.what must be one of ${N.join(", ")}`;let i=e.max===void 0||e.max===null||e.max===""?0:Number(e.max);return!Number.isInteger(i)||i<0?"count.max must be a whole number, 0 or more":{provider:t,project:r,what:o,max:i}}function A(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=b(t);return typeof r=="string"?null:r}catch{return null}}var x=e=>e==="issues"?"open issues":e==="prs"?"open pull requests":"open issues and pull requests";function D(e){return`${x(e.what)} in ${e.provider} ${e.project} \u2264 ${e.max}`}async function te(e,t){if(!t)return{verdict:"unverifiable",detail:`no ${e.provider} connector on this node`};try{let r=e.what==="all"?["issues","prs"]:[e.what],n=0;for(let i of r){let s=await t(e.provider,e.project,i);if(typeof s!="number")return{verdict:"unverifiable",detail:`${e.project}: ${s.error}`};n+=s}let o=`${n} ${x(e.what)} in ${e.project}`;return{verdict:n<=e.max?"met":"not_met",detail:o,count:n}}catch(r){return{verdict:"unverifiable",detail:`the count check failed: ${String(r?.message??r).slice(0,200)}`}}}function ne(e,t=fetch){return async(r,n,o)=>{let i;if(r==="github"){let a=e.github;if(!a)return{error:"no github connector on this node (channels.github or requests.checkers.github)"};let l=encodeURIComponent(`repo:${n} is:open is:${o==="prs"?"pr":"issue"}`);i=`${a.apiUrl.replace(/\/$/,"")}/search/issues?q=${l}&per_page=1`}else{let a=e.gitlab;if(!a)return{error:"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)"};i=`${a.url.replace(/\/$/,"")}/api/v4/projects/${encodeURIComponent(n)}/${o==="prs"?"merge_requests":"issues"}?state=opened&per_page=1`}let s;try{s=await t(i,{headers:$(r,e),signal:AbortSignal.timeout(H)})}catch(a){return{error:`could not be reached: ${String(a?.message??a).slice(0,200)}`}}if(!s.ok)return{error:s.status===404?"not found (or not visible to the connector)":`HTTP ${s.status}`};if(r==="gitlab"){let a=Number(s.headers.get("x-total"));return Number.isInteger(a)&&a>=0?a:{error:"no X-Total in the answer"}}let c=await s.json().catch(()=>null),u=Number(c?.total_count);return Number.isInteger(u)&&u>=0?u:{error:"no total_count in the answer"}}}j();function k(e){let t=w(e.number??e.id);if(typeof t!="string")return`check.number: ${t.error}`;let r=i=>e[i]!==void 0&&e[i]!==null&&e[i]!=="";if(r("atLeast")===r("atMost"))return"a number check needs one of atLeast or atMost: the threshold its reading must cross";let n=r("atLeast")?"atLeast":"atMost",o=Number(e[n]);return Number.isFinite(o)?{kind:"number",number:t,[n]:o}:`check.${n} must be a number`}function L(e){if(!e||typeof e!="object"||e.kind!=="number")return null;let t=k(e);return typeof t=="string"?null:t}function v(e){return e.atLeast!==void 0?`number ${e.number} reads \u2265 ${h(e.atLeast)}`:`number ${e.number} reads \u2264 ${h(e.atMost)}`}function se(e,t){if(!t)return{verdict:"unverifiable",detail:"this node keeps no numbers"};let r=t.get(e.number);if(!r)return{verdict:"unverifiable",detail:`no number "${e.number}"`};let n=t.readings(e.number,1)[0];if(!n||n.value===null)return{verdict:"unverifiable",detail:`${e.number}: no reading${n?.error?` (${n.error})`:""}`};let o=e.atLeast!==void 0?n.value>=e.atLeast:n.value<=e.atMost,i=`${r.name}: ${h(n.value,r.unit)} for ${R({start:n.periodStart,end:n.periodEnd})}`;return{verdict:o?"met":"not_met",detail:i}}var P=["active","done","dropped"],le=300,G=500;function de(e,t=E,r=Date.now()){if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="count"){let o=b(e);return typeof o=="string"?o:{kind:"count",...o}}if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="number")return k(e);let n=S(e,t,r);return typeof n!="string"?n:/^closeWhen(\.kind)? must be/.test(n)?"check must be an object with a kind: url, issue, git-ancestor, reply, count or number":n.replace(/^closeWhen/,"check")}function Z(e){if(!e)return null;try{let t=JSON.parse(e);if(t?.kind==="count"){let r=A(e);return r?{kind:"count",...r}:null}if(t?.kind==="number")return L(t)}catch{return null}return _(e)}function z(e){return e.kind==="count"?D(e):e.kind==="number"?v(e):T(e)}function y(e){return{id:e.id,title:e.title,ownerAgent:e.owner_agent??null,state:e.state,doneWhen:e.done_when??null,check:Z(e.check_spec),evidence:e.evidence??null,lastCheck:e.last_check??null,lastCheckAt:e.last_check_at??null,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null}}var O=class{constructor(t){this.db=t;t.exec(`
1
+ import{Pa as E,Qa as S,Sa as T,Ta as _,Ua as q,a as w,d as R,i as h,l as j,p as $,r as U}from"./chunk-VOVDWFFP.js";q();U();var H=1e4,N=["issues","prs","all"],X=/^[\w.-]+(?:\/[\w.-]+)+$/,f=e=>typeof e=="string"?e.trim():"";function b(e){let t=f(e.provider).toLowerCase();if(t!=="github"&&t!=="gitlab")return"count.provider must be github or gitlab";let r=f(e.project),n=r.split("/");if(!X.test(r)||n.some(s=>s==="."||s==="..")||t==="github"&&n.length!==2)return t==="github"?'count.project must be "owner/repo"':'count.project must be "group/project"';let o=(f(e.what)||"issues").toLowerCase();if(!N.includes(o))return`count.what must be one of ${N.join(", ")}`;let i=e.max===void 0||e.max===null||e.max===""?0:Number(e.max);return!Number.isInteger(i)||i<0?"count.max must be a whole number, 0 or more":{provider:t,project:r,what:o,max:i}}function A(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=b(t);return typeof r=="string"?null:r}catch{return null}}var x=e=>e==="issues"?"open issues":e==="prs"?"open pull requests":"open issues and pull requests";function D(e){return`${x(e.what)} in ${e.provider} ${e.project} \u2264 ${e.max}`}async function te(e,t){if(!t)return{verdict:"unverifiable",detail:`no ${e.provider} connector on this node`};try{let r=e.what==="all"?["issues","prs"]:[e.what],n=0;for(let i of r){let s=await t(e.provider,e.project,i);if(typeof s!="number")return{verdict:"unverifiable",detail:`${e.project}: ${s.error}`};n+=s}let o=`${n} ${x(e.what)} in ${e.project}`;return{verdict:n<=e.max?"met":"not_met",detail:o,count:n}}catch(r){return{verdict:"unverifiable",detail:`the count check failed: ${String(r?.message??r).slice(0,200)}`}}}function ne(e,t=fetch){return async(r,n,o)=>{let i;if(r==="github"){let a=e.github;if(!a)return{error:"no github connector on this node (channels.github or requests.checkers.github)"};let l=encodeURIComponent(`repo:${n} is:open is:${o==="prs"?"pr":"issue"}`);i=`${a.apiUrl.replace(/\/$/,"")}/search/issues?q=${l}&per_page=1`}else{let a=e.gitlab;if(!a)return{error:"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)"};i=`${a.url.replace(/\/$/,"")}/api/v4/projects/${encodeURIComponent(n)}/${o==="prs"?"merge_requests":"issues"}?state=opened&per_page=1`}let s;try{s=await t(i,{headers:$(r,e),signal:AbortSignal.timeout(H)})}catch(a){return{error:`could not be reached: ${String(a?.message??a).slice(0,200)}`}}if(!s.ok)return{error:s.status===404?"not found (or not visible to the connector)":`HTTP ${s.status}`};if(r==="gitlab"){let a=Number(s.headers.get("x-total"));return Number.isInteger(a)&&a>=0?a:{error:"no X-Total in the answer"}}let c=await s.json().catch(()=>null),u=Number(c?.total_count);return Number.isInteger(u)&&u>=0?u:{error:"no total_count in the answer"}}}j();function k(e){let t=w(e.number??e.id);if(typeof t!="string")return`check.number: ${t.error}`;let r=i=>e[i]!==void 0&&e[i]!==null&&e[i]!=="";if(r("atLeast")===r("atMost"))return"a number check needs one of atLeast or atMost: the threshold its reading must cross";let n=r("atLeast")?"atLeast":"atMost",o=Number(e[n]);return Number.isFinite(o)?{kind:"number",number:t,[n]:o}:`check.${n} must be a number`}function L(e){if(!e||typeof e!="object"||e.kind!=="number")return null;let t=k(e);return typeof t=="string"?null:t}function v(e){return e.atLeast!==void 0?`number ${e.number} reads \u2265 ${h(e.atLeast)}`:`number ${e.number} reads \u2264 ${h(e.atMost)}`}function se(e,t){if(!t)return{verdict:"unverifiable",detail:"this node keeps no numbers"};let r=t.get(e.number);if(!r)return{verdict:"unverifiable",detail:`no number "${e.number}"`};let n=t.readings(e.number,1)[0];if(!n||n.value===null)return{verdict:"unverifiable",detail:`${e.number}: no reading${n?.error?` (${n.error})`:""}`};let o=e.atLeast!==void 0?n.value>=e.atLeast:n.value<=e.atMost,i=`${r.name}: ${h(n.value,r.unit)} for ${R({start:n.periodStart,end:n.periodEnd})}`;return{verdict:o?"met":"not_met",detail:i}}var P=["active","done","dropped"],le=300,G=500;function de(e,t=E,r=Date.now()){if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="count"){let o=b(e);return typeof o=="string"?o:{kind:"count",...o}}if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="number")return k(e);let n=S(e,t,r);return typeof n!="string"?n:/^closeWhen(\.kind)? must be/.test(n)?"check must be an object with a kind: url, issue, git-ancestor, reply, count or number":n.replace(/^closeWhen/,"check")}function Z(e){if(!e)return null;try{let t=JSON.parse(e);if(t?.kind==="count"){let r=A(e);return r?{kind:"count",...r}:null}if(t?.kind==="number")return L(t)}catch{return null}return _(e)}function z(e){return e.kind==="count"?D(e):e.kind==="number"?v(e):T(e)}function y(e){return{id:e.id,title:e.title,ownerAgent:e.owner_agent??null,state:e.state,doneWhen:e.done_when??null,check:Z(e.check_spec),evidence:e.evidence??null,lastCheck:e.last_check??null,lastCheckAt:e.last_check_at??null,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null}}var O=class{constructor(t){this.db=t;t.exec(`
2
2
  CREATE TABLE IF NOT EXISTS goals (
3
3
  id TEXT PRIMARY KEY,
4
4
  title TEXT NOT NULL,
@@ -17,4 +17,4 @@ import{Pa as E,Qa as S,Sa as T,Ta as _,Ua as q,a as w,d as R,i as h,l as j,p as
17
17
  `)}get(t){let r=this.db.prepare("SELECT * FROM goals WHERE id = ?").get(t);return r?y(r):null}list(t=P,r=200){let n=t.map(()=>"?").join(", ");return this.db.prepare(`SELECT * FROM goals WHERE state IN (${n}) ORDER BY updated_at DESC, rowid DESC LIMIT ?`).all(...t,r).map(y)}ensure(t,r,n){return this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?) ON CONFLICT(id) DO NOTHING").run(t.id,t.title,r,n,n),this.get(t.id)}upsert(t,r){let n=this.get(t.id);return n?this.db.prepare("UPDATE goals SET title = ?, owner_agent = ?, done_when = ?, check_spec = ?, updated_at = ? WHERE id = ?").run(t.title||n.title,t.ownerAgent!==void 0?t.ownerAgent:n.ownerAgent,t.doneWhen!==void 0?t.doneWhen:n.doneWhen,t.check!==void 0?t.check?JSON.stringify(t.check):null:n.check?JSON.stringify(n.check):null,r,t.id):this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, done_when, check_spec, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?, ?, ?)").run(t.id,t.title,t.ownerAgent??null,t.doneWhen??null,t.check?JSON.stringify(t.check):null,r,r),this.get(t.id)}close(t,r,n,o){return this.db.prepare("UPDATE goals SET state = ?, evidence = ?, closed_at = ?, updated_at = ? WHERE id = ? AND state = 'active'").run(r,n?n.slice(0,G):null,o,o,t).changes>0}markChecked(t,r,n){this.db.prepare("UPDATE goals SET last_check = ?, last_check_at = ? WHERE id = ?").run(r.slice(0,G),n,t)}dueChecks(t){return this.db.prepare("SELECT * FROM goals WHERE state = 'active' AND check_spec IS NOT NULL AND (last_check_at IS NULL OR last_check_at <= ?) ORDER BY last_check_at ASC LIMIT 50").all(t).map(y)}};async function pe(e,t,r,n,o=()=>{}){let i=[];for(let s of e.dueChecks(n-r*6e4)){let c;try{c=await t(s.check)}catch(u){c={verdict:"unverifiable",detail:String(u?.message??u)}}e.markChecked(s.id,c.detail,n),c.verdict==="met"&&e.close(s.id,"done",`check: ${c.detail}`,n)?(i.push(s.id),o(`[goals] ${s.id} done: ${c.detail}`)):c.verdict==="unverifiable"&&o(`[goals] ${s.id}: check failed: ${c.detail}`)}return i}function me(e,t){let r=[`[Goal] ${e.title} (${e.id}): ${e.state}${e.ownerAgent?`, owner ${e.ownerAgent}`:""}.`];return e.doneWhen&&r.push(`Done when: ${e.doneWhen}`),e.check&&r.push(`Check: ${z(e.check)}${e.lastCheck?`; last seen: ${e.lastCheck}${e.lastCheckAt?` (${new Date(e.lastCheckAt).toISOString().slice(0,16).replace("T"," ")} UTC)`:""}`:""}`),t&&r.push(`Requests under it: ${t.open} open, ${t.done} done.`),r.join(`
18
18
  `)}var g="Africa/Tunis";function C(e,t=g){let r=Object.fromEntries(new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(e)).map(o=>[o.type,o.value])),n=(Number(r.hour)%24*3600+Number(r.minute)*60+Number(r.second))*1e3+e%1e3;return e-n}var Y=(e,t)=>new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit"}).format(new Date(e));function B(e,t=10){let r=e.replace(/\s+/g," ").trim().split(" ");return r.slice(0,t).join(" ")+(r.length>t?" \u2026":"")}var J=new Set(["issue","idea","approval","erp","card"]);function ge(e,t={}){let r=e.map(n=>{let o=[],i=(s,c)=>{o.some(u=>u.kind===s&&u.ref===c)||o.push({kind:s,ref:c})};for(let s of n.links??[])J.has(s.kind)&&i(s.kind,s.ref);return n.home&&i(n.home.kind,n.home.link),t.hasPlan?.(n.id)&&i("plan",n.id),n.evidence&&i("evidence",n.evidence),{id:n.id,time:Y(n.createdAt,t.zone??g),words:B(n.text),state:n.state,owner:n.agentId,landed:o,noHome:o.length===0&&n.state!=="declined"&&n.state!=="dropped"}});return[...r.filter(n=>n.noHome),...r.filter(n=>!n.noHome)]}var I={timeZone:g,days:7},K=90,W=5,F=120,V=(e,t)=>new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e));function Q(e,t){return{day:V(e,t),start:e,asked:0,done:0,dropped:0,moving:0,waiting:0,stuck:0,rate:null,dropReasons:[],moreReasons:0,resent:0,resentDone:0}}function ke(e,t={}){let r=t.zone??I.timeZone,n=Math.min(Math.max(Math.floor(t.days??I.days),1),K),o=t.now??Date.now(),i=[C(o,r)];for(;i.length<n;)i.unshift(C(i[0]-1,r));let s=i.map(a=>Q(a,r)),c=s.map(()=>new Map),u=0;for(let a of e.flowRows(i[0])){for(;u+1<s.length&&a.createdAt>=s[u+1].start;)u++;let l=s[u];if(l.asked++,a.state==="done")l.done++;else if(a.state==="declined"||a.state==="dropped"){l.dropped++;let p=(a.closeReason??"").replace(/\s+/g," ").trim(),d=p.length>F?`${p.slice(0,F-1)}\u2026`:p||"no reason given";c[u].set(d,(c[u].get(d)??0)+1)}else a.state==="in_progress"||a.state==="waiting_other"?l.moving++:a.state==="waiting_owner"?l.waiting++:a.state==="needs_attention"&&l.stuck++;a.resentAt!==null&&(l.resent++,a.state==="done"&&l.resentDone++)}return s.forEach((a,l)=>{a.rate=a.asked?(a.done+a.dropped)/a.asked:null;let p=[...c[l]].sort((d,m)=>m[1]-d[1]);a.dropReasons=p.slice(0,W).map(([d,m])=>({reason:d,count:m})),a.moreReasons=p.slice(W).reduce((d,[,m])=>d+m,0)}),{zone:r,days:s,today:s[s.length-1]}}var M=e=>e===null?"\u2013":`${Math.round(e*100)}%`;function ye(e){let t=e.today,r=[`Today (${t.day}, ${e.zone}): ${t.asked?`${t.done+t.dropped} of ${t.asked} closed, ${M(t.rate)}`:"nothing asked yet"}.`,` ${t.done} done, ${t.dropped} dropped, ${t.moving} moving, ${t.waiting} waiting on the owner, ${t.stuck} stuck.`+(t.resent?` ${t.resent} resent once on its own, ${t.resentDone} of them done.`:"")];if(t.dropReasons.length){r.push(" Dropped because:");for(let n of t.dropReasons)r.push(` ${n.count} \xD7 ${n.reason}`);t.moreReasons&&r.push(` ${t.moreReasons} more`)}if(e.days.length>1){r.push("","Day asked done dropped moving waiting stuck rate");for(let n of e.days){let o=[n.asked,n.done,n.dropped,n.moving,n.waiting,n.stuck].map(String);r.push(`${n.day} ${o[0].padStart(5)} ${o[1].padStart(4)} ${o[2].padStart(7)} ${o[3].padStart(6)} ${o[4].padStart(7)} ${o[5].padStart(5)} ${M(n.rate).padStart(4)}`)}}return r.join(`
19
19
  `)}export{b as a,A as b,D as c,te as d,ne as e,se as f,le as g,G as h,de as i,z as j,O as k,pe as l,me as m,C as n,ge as o,I as p,K as q,ke as r,ye as s};
20
- //# sourceMappingURL=chunk-UYDC2YMH.js.map
20
+ //# sourceMappingURL=chunk-D5LIMOI6.js.map
@@ -1,4 +1,4 @@
1
- import{a as xt}from"./chunk-GTJIKXDB.js";import{P as Wr,W as Xr,s as Y}from"./chunk-U4AUJ6XI.js";import{f as Br,g as Hr,h as Vr,l as qr}from"./chunk-EWXY73XA.js";import{b as jr}from"./chunk-2VDO2HEK.js";import{t as Fr,u as Ur}from"./chunk-DGCYSQAZ.js";import{d as Pr,e as Mr}from"./chunk-AQASR6KR.js";import{h as he,j as Er,l as $r,m as _r,n as Ar}from"./chunk-RX5O5637.js";import{a as Rr,c as Tr,e as Ir,f as ht,h as Dr,j as Cr,k as Nr,l as bt,m as yt,n as wt}from"./chunk-5ELIX7BQ.js";import{c as Or,d as Lr}from"./chunk-CR37IINZ.js";import{a as br,c as yr}from"./chunk-KP7KDLZ2.js";import{Aa as mr,Ba as W,Ca as fe,Ea as ft,b as pt,f as cr,s as gt,u as mt,za as Oe}from"./chunk-Y3TXTZYG.js";import{a as Ce,b as me,e as dr}from"./chunk-7AB3QUGH.js";import{h as wr,i as xr,j as kr,l as vr,m as Sr}from"./chunk-MELXJ5AR.js";import{s as gr}from"./chunk-ZT4FCL5B.js";import{a as ur,b as Ne,e as pr}from"./chunk-KCS737RC.js";import{c as Le,d as fr,e as hr}from"./chunk-XVV7ZZ77.js";import{b as ne}from"./chunk-5ONH4ITT.js";import{a as lr,c as ut}from"./chunk-ILEC3IAV.js";import{a as er,j as sr,m as ir,o as ct,p as dt,s as ge,t as te,v as ar}from"./chunk-BXK5S2KK.js";import{a as tr,b as nr,d as rr,e as or}from"./chunk-4NZ4T3TQ.js";import{a as Zn}from"./chunk-7IW25T4K.js";import{a as Qn}from"./chunk-QUFIUXMQ.js";import{Cc as Jn,Fa as De,Ha as qn,I as ot,J as C,L as Te,M as $,N as pe,O as jn,R as Bn,S as st,Xa as Xn,b as In,c as Dn,d as Cn,db as zn,e as Nn,f as On,fa as Ie,fb as Kn,g as Ln,ga as Hn,gb as Xi,gc as lt,h as G,ha as Vn,i as Pn,ia as Hi,j as Mn,k as Fn,l as rt,rc as Gn,s as Un,sc as Yn,w as ji,x as Wn,y as Bi}from"./chunk-EZDHAX4Z.js";import{a as it,h as Vi}from"./chunk-KEUW6YLL.js";import{j as at,r as qi}from"./chunk-N47Y5ADQ.js";import{existsSync as zi,readdirSync as Ki,readFileSync as Gi,statSync as Yi}from"fs";import{resolve as Ji}from"path";function zr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var Pe=new Map;function np(t,e=1e3){if(!zi(t))return[];let n=Ki(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ji(t,s);return{path:i,mtime:Yi(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Pe.keys())r.has(s)||Pe.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Pe.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Qi(s,i);Pe.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Qi(t,e){try{let n=Gi(t,"utf-8").split(`
1
+ import{a as xt}from"./chunk-GTJIKXDB.js";import{P as Wr,W as Xr,s as Y}from"./chunk-5CUOKXOD.js";import{f as Br,g as Hr,h as Vr,l as qr}from"./chunk-GO4J44UD.js";import{b as jr}from"./chunk-2VDO2HEK.js";import{t as Fr,u as Ur}from"./chunk-XC3466Z4.js";import{d as Pr,e as Mr}from"./chunk-AQASR6KR.js";import{h as he,j as Er,l as $r,m as _r,n as Ar}from"./chunk-RX5O5637.js";import{a as Rr,c as Tr,e as Ir,f as ht,h as Dr,j as Cr,k as Nr,l as bt,m as yt,n as wt}from"./chunk-5ELIX7BQ.js";import{c as Or,d as Lr}from"./chunk-SQP6A5AG.js";import{a as br,c as yr}from"./chunk-KP7KDLZ2.js";import{Aa as mr,Ba as W,Ca as fe,Ea as ft,b as pt,f as cr,s as gt,u as mt,za as Oe}from"./chunk-5RCWAXVK.js";import{a as Ce,b as me,e as dr}from"./chunk-7AB3QUGH.js";import{h as wr,i as xr,j as kr,l as vr,m as Sr}from"./chunk-AEFO6ES5.js";import{s as gr}from"./chunk-NW7B53KD.js";import{a as ur,b as Ne,e as pr}from"./chunk-5BT4VPJC.js";import{c as Le,d as fr,e as hr}from"./chunk-XVV7ZZ77.js";import{b as ne}from"./chunk-5ONH4ITT.js";import{a as lr,c as ut}from"./chunk-ILEC3IAV.js";import{a as er,j as sr,m as ir,o as ct,p as dt,s as ge,t as te,v as ar}from"./chunk-BXK5S2KK.js";import{a as tr,b as nr,d as rr,e as or}from"./chunk-4NZ4T3TQ.js";import{a as Zn}from"./chunk-7IW25T4K.js";import{a as Qn}from"./chunk-QUFIUXMQ.js";import{Cc as Jn,Fa as De,Ha as qn,I as ot,J as C,L as Te,M as $,N as pe,O as jn,R as Bn,S as st,Xa as Xn,b as In,c as Dn,d as Cn,db as zn,e as Nn,f as On,fa as Ie,fb as Kn,g as Ln,ga as Hn,gb as Xi,gc as lt,h as G,ha as Vn,i as Pn,ia as Hi,j as Mn,k as Fn,l as rt,rc as Gn,s as Un,sc as Yn,w as ji,x as Wn,y as Bi}from"./chunk-VOVDWFFP.js";import{a as it,h as Vi}from"./chunk-KEUW6YLL.js";import{j as at,r as qi}from"./chunk-N47Y5ADQ.js";import{existsSync as zi,readdirSync as Ki,readFileSync as Gi,statSync as Yi}from"fs";import{resolve as Ji}from"path";function zr(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var Pe=new Map;function np(t,e=1e3){if(!zi(t))return[];let n=Ki(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ji(t,s);return{path:i,mtime:Yi(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Pe.keys())r.has(s)||Pe.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Pe.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Qi(s,i);Pe.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Qi(t,e){try{let n=Gi(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Kr=7,Zi={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},T={routines:200,summary:160,filters:6,filterValue:60,text:120},ea=(t,e,n)=>{try{return gr(t,e,n)}catch{return null}},Gr=864e5;function ip(t){let e=t.now??Date.now(),n={...Zi,...t.thresholds},r=t.nextFire??ea,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,T.text),trigger:{schedule:F(a.schedule,T.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?kt(a.nextRun)??kt(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:ia(p.status==="success"?void 0:p.errorSummary,T.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Yr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Kr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Jr(u,c,a.schedule,l,null,e,n,r),o.push(Qr(u))}let s=new Map(zr(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,S)=>S.at-k.at),g=u.map(k=>({at:k.at,status:ra(k.status)})),m=g[0],f=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:f?"schedule":"event",name:F(a.title||a.id,T.text),trigger:f?{schedule:F(w,T.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",T.text),filters:sa(l.filter,a)},agent:oa(a),enabled:p,state:c,nextRunAt:f&&p&&w?kt(r(w,new Date(e),x)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let k=g.find(S=>S.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Yr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Kr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Jr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):ta(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Qr(b))}return o.sort(na).slice(0,T.routines)}function Yr(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 Jr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=eo(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function ta(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=eo(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function eo(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Gr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Gr)} days`:"Disabled and never ran"}}function Qr(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 Zr={critical:0,warning:1,info:2};function na(t,e){let n=t.attention?Zr[t.attention]:3,r=e.attention?Zr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ra(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 oa(t){if(t.ownerAgent)return F(t.ownerAgent,T.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),T.text):null}function sa(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,T.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(F(`${o}=${i.join(",")}`,T.filterValue))}return n.slice(0,T.filters)}function kt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function ia(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as aa,readFileSync as la,renameSync as ca,writeFileSync as da}from"fs";import{resolve as ua}from"path";function to(t){return ua(dt(t),"_state.json")}function N(t){try{let e=JSON.parse(la(to(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 be(t,e){aa(dt(t),{recursive:!0});let n=to(t),r=`${n}.${process.pid}.tmp`;da(r,JSON.stringify(e,null,2)+`
3
3
  `),ca(r,n)}function no(t,e,n,r=Date.now()){let o=N(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),be(t,{...o,snoozed:s})}function up(t,e){be(t,{...N(t),lastDigest:e})}function vt(t,e,n,r=Date.now()){let o=N(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));be(t,{...o,popped:i,wanted:a})}function ro(t,e){let n=N(t);be(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function pp(t,e=Date.now()){be(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as pa,readFileSync as ga}from"fs";Jn();Vi();function oo(t){let e=ur(t),n={};if(pa(e))try{n=Gn(JSON.parse(ga(e,"utf-8")))}catch{n={}}let r=lt.safeParse(n?.requests);return r.success?r.data:lt.parse(void 0)}async function yp(t,e={}){let n=(t.channels??[]).filter(r=>!it.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...it].join(", ")}`}:Ne(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as V,readdirSync as Da,readFileSync as $t,statSync as Ca}from"fs";import{dirname as So,resolve as R}from"path";import{randomBytes as ao}from"crypto";import{existsSync as fa,mkdirSync as ha,readdirSync as ba,readFileSync as ya,renameSync as lo,unlinkSync as wa,writeFileSync as xa}from"fs";import{resolve as co}from"path";function so(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ma=t=>t.trim().split(`
4
4
  `).pop()?.slice(0,300)||"no output";async function io(t,e,n,r=xt){let o=await r(t.bin,[...so(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ma(o.stderr||o.stdout)}`}}async function kp(t,e,n,r,o=xt){return(await o(t.bin,[...so(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var ka=2e3,va=t=>io(t.wacli,t.to,t.text);function St(t){return co(t,".agentx","whatsapp-triage","drafts")}var Sa=t=>/^[a-z0-9-]{8,64}$/.test(t),Me=(t,e)=>co(St(t),`${e}.json`);function uo(t,e){ha(St(t),{recursive:!0});let n=Me(t,e.id),r=`${n}.${process.pid}.tmp`;xa(r,JSON.stringify(e,null,2)+`
@@ -960,4 +960,4 @@ Document the arguments, commands, or files the skill expects. Example:
960
960
  claude-code ${Tn(t)} --arg value
961
961
  \`\`\`
962
962
  `}Jn();var Mi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Fi(t){return{...Mi,...t??{},regions:{...t?.regions??{}},buffer:{...Mi.buffer,...t?.buffer??{}}}}function kb(t){try{return Fi(Yn(t).screen)}catch{return Fi(void 0)}}var Zu=/^[a-z][\w-]*$/,Ui=["window","screen","menubar","notifications"];function _e(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var tt=(t,e)=>_e(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Wi(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 vb(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=tt(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=tt(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=tt(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=_e(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=_e(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!Zu.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=Wi(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=_e(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=_e(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=tt(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!Ui.includes(r)&&!n.regions?.[r])try{Wi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Ui,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{zr as a,np as b,en as c,$c as d,_c as e,Nm as f,Om as g,Lm as h,Fm as i,Um as j,Wm as k,vs as l,Ss as m,jm as n,Hm as o,X as p,Es as q,T as r,ip as s,As as t,Gm as u,Qm as v,Ts as w,Zm as x,Is as y,ef as z,xe as A,Yc as B,tf as C,nf as D,Cs as E,kp as F,va as G,Ap as H,go as I,N as J,up as K,pp as L,oo as M,yp as N,J as O,ig as P,To as Q,Co as R,ed as S,of as T,td as U,sf as V,af as W,nn as X,Os as Y,df as Z,on as _,od as $,sd as aa,mf as ba,nl as ca,rl as da,cg as ea,dg as fa,dl as ga,mg as ha,Vs as ia,Xs as ja,xf as ka,ce as la,$f as ma,zs as na,Rf as oa,bg as pa,yg as qa,ys as ra,qt as sa,yc as ta,I as ua,ii as va,ih as wa,ah as xa,Yd as ya,uh as za,pi as Aa,ph as Ba,gh as Ca,wh as Da,su as Ea,au as Fa,xh as Ga,xg as Ha,kg as Ia,vg as Ja,Sg as Ka,Eg as La,$g as Ma,_g as Na,Ag as Oa,Tg as Pa,Ig as Qa,Ng as Ra,Og as Sa,Lg as Ta,Fg as Ua,Ug as Va,Wg as Wa,jg as Xa,Bg as Ya,Hg as Za,Vg as _a,Zg as $a,Lt as ab,em as bb,tm as cb,ye as db,we as eb,gu as fb,Th as gb,Ih as hb,Dh as ib,Ch as jb,bn as kb,Nh as lb,Ft as mb,Ut as nb,ze as ob,Wl as pb,Bl as qb,im as rb,jt as sb,Bt as tb,Hl as ub,Vl as vb,rs as wb,as as xb,am as yb,zl as zb,lm as Ab,tc as Bb,oc as Cb,Ht as Db,ic as Eb,ls as Fb,z as Gb,Si as Hb,Ei as Ib,$i as Jb,wn as Kb,Uh as Lb,vu as Mb,Ai as Nb,Ri as Ob,Yh as Pb,Jh as Qb,Fu as Rb,Qh as Sb,Ii as Tb,ps as Ub,rb as Vb,Vu as Wb,sb as Xb,ib as Yb,Ke as Zb,Sm as _b,Qt as $b,Im as ac,db as bc,ub as cc,pb as dc,gb as ec,mb as fc,fb as gc,hb as hc,bb as ic,yb as jc,Mi as kc,Fi as lc,kb as mc,Ui as nc,vb as oc};
963
- //# sourceMappingURL=chunk-3XUAIA7U.js.map
963
+ //# sourceMappingURL=chunk-E3SA7KIZ.js.map