agentix-cli 0.216.0 → 0.217.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 (166) hide show
  1. package/dist/{App-YGVVIKZD.js → App-IXJCCCGN.js} +2 -2
  2. package/dist/{ChatApp-6TEK2WMU.js → ChatApp-4YCCRL5M.js} +2 -2
  3. package/dist/{absorb-eval-MJ475CNV.js → absorb-eval-YE57HA6N.js} +2 -2
  4. package/dist/{adapter-C6YORAE6.js → adapter-CRVWPQBN.js} +2 -2
  5. package/dist/{agent-44SGRWX2.js → agent-CTZN3P2K.js} +2 -2
  6. package/dist/{board-dashboard-TZKV4DFV.js → board-dashboard-2WE2HBEW.js} +621 -394
  7. package/dist/board-dashboard-2WE2HBEW.js.map +1 -0
  8. package/dist/{chunk-U5DSMDCJ.js → chunk-2F7KQ4DJ.js} +2 -2
  9. package/dist/{chunk-5SQRJUAK.js → chunk-2MAKXLK2.js} +3 -3
  10. package/dist/{chunk-2KQECT4H.js → chunk-3B7RH3IK.js} +2 -2
  11. package/dist/{chunk-2ZNYIHRB.js → chunk-3C6UDZDX.js} +2 -2
  12. package/dist/{chunk-F32VADB7.js → chunk-56UTQ4FU.js} +2 -2
  13. package/dist/{chunk-I4E6BH27.js → chunk-5FFNFW4C.js} +2 -2
  14. package/dist/{chunk-I4E6BH27.js.map → chunk-5FFNFW4C.js.map} +1 -1
  15. package/dist/{chunk-BLKXK27S.js → chunk-64IVC2G6.js} +2 -2
  16. package/dist/{chunk-TO6T6AQY.js → chunk-AOPNASCE.js} +2 -2
  17. package/dist/chunk-BXK5S2KK.js +13 -0
  18. package/dist/chunk-BXK5S2KK.js.map +1 -0
  19. package/dist/{chunk-F2XNWKIL.js → chunk-ELC3M5WS.js} +393 -434
  20. package/dist/chunk-ELC3M5WS.js.map +1 -0
  21. package/dist/{chunk-IKXDCPXS.js → chunk-FFLMSNTN.js} +2 -2
  22. package/dist/{chunk-WLDRIJQX.js → chunk-GEKEILPL.js} +5 -5
  23. package/dist/{chunk-T3B7OUDC.js → chunk-I4FXWN7I.js} +2 -2
  24. package/dist/{chunk-3UATFGSB.js → chunk-IP67DTXX.js} +2 -2
  25. package/dist/chunk-KBSQRQPF.js +10 -0
  26. package/dist/chunk-KBSQRQPF.js.map +1 -0
  27. package/dist/{chunk-TFHJT2AZ.js → chunk-LLNLDZNA.js} +2 -2
  28. package/dist/{chunk-LDSBFDYB.js → chunk-LSFLSB7C.js} +2 -2
  29. package/dist/{chunk-YTWRIIAT.js → chunk-M42GMRZF.js} +2 -2
  30. package/dist/{chunk-PA7CP74O.js → chunk-MFZNBE65.js} +2 -2
  31. package/dist/{chunk-GEKJQ7VV.js → chunk-NFUHYIYG.js} +2 -2
  32. package/dist/chunk-O2YDS2P3.js +8 -0
  33. package/dist/chunk-O2YDS2P3.js.map +1 -0
  34. package/dist/{chunk-LJUBWMPB.js → chunk-OJ4RUZZY.js} +2 -2
  35. package/dist/chunk-PZ2F6J2E.js +134 -0
  36. package/dist/chunk-PZ2F6J2E.js.map +1 -0
  37. package/dist/{chunk-AU7SN4G3.js → chunk-Q432O462.js} +2 -2
  38. package/dist/{chunk-T7SD5EVH.js → chunk-QEOGWSRR.js} +2 -2
  39. package/dist/{chunk-7OJUZ3L5.js → chunk-QGRIW7SE.js} +2 -2
  40. package/dist/{chunk-SZXFWCKA.js → chunk-RKKAP4EY.js} +2 -2
  41. package/dist/{chunk-JTS563OC.js → chunk-SJJ7QEFE.js} +2 -2
  42. package/dist/{chunk-6UTOBSEA.js → chunk-SYIDD7CI.js} +2 -2
  43. package/dist/{chunk-XXFVK5D7.js → chunk-WHAMZPEG.js} +141 -87
  44. package/dist/chunk-WHAMZPEG.js.map +1 -0
  45. package/dist/{chunk-JNBUJKNG.js → chunk-X2GBLX3E.js} +2 -2
  46. package/dist/{chunk-M4H2RYP4.js → chunk-XQH4LCZR.js} +2 -2
  47. package/dist/{chunk-MH7KJQ4N.js → chunk-YXGZSVPY.js} +2 -2
  48. package/dist/{chunk-JMWPBZLU.js → chunk-Z5HYCMDF.js} +2 -2
  49. package/dist/cli.js +1 -1
  50. package/dist/{client-SJLHZDIC.js → client-UPXDV3SM.js} +2 -2
  51. package/dist/{config-Q3ENZQYL.js → config-LAM4HUTA.js} +2 -2
  52. package/dist/{config-mutate-NNAUMQ2Y.js → config-mutate-P4QLFUVH.js} +2 -2
  53. package/dist/{config-mutator-2F2BJNMA.js → config-mutator-RIPSMYAO.js} +2 -2
  54. package/dist/{contributions-SOUGZCAH.js → contributions-SHSEI3TX.js} +2 -2
  55. package/dist/{doctor-H6I433KY.js → doctor-TLDBNHYM.js} +2 -2
  56. package/dist/{follow-up-tool-4FX455DL.js → follow-up-tool-VM4ZDRC5.js} +2 -2
  57. package/dist/{follow-up-tool-4FX455DL.js.map → follow-up-tool-VM4ZDRC5.js.map} +1 -1
  58. package/dist/{grants-U2734ZHZ.js → grants-ZA35QVTX.js} +2 -2
  59. package/dist/{hub-XFZFHLJK.js → hub-7Y6ZUVJV.js} +2 -2
  60. package/dist/index.d.ts +30 -1
  61. package/dist/index.js +1 -1
  62. package/dist/org-tool-TOHI7MBS.js +2 -0
  63. package/dist/{org-tool-OE5QP6W7.js.map → org-tool-TOHI7MBS.js.map} +1 -1
  64. package/dist/{program-7QFRDJUY.js → program-QZKK3Y2W.js} +308 -308
  65. package/dist/program-QZKK3Y2W.js.map +1 -0
  66. package/dist/{promote-FQY3HNL6.js → promote-OBTQ3ZUN.js} +2 -2
  67. package/dist/{query-LIII4CGT.js → query-K6NR3GQE.js} +2 -2
  68. package/dist/{query-settings-6LHW2NCF.js → query-settings-NIZBB73K.js} +2 -2
  69. package/dist/{registry-WQNBXOUL.js → registry-B7X6YGS7.js} +2 -2
  70. package/dist/{request-planner-HYYT3W7X.js → request-planner-YDIX4BQW.js} +2 -2
  71. package/dist/{review-candidates-JOCZEZ2L.js → review-candidates-3QCCHXWM.js} +2 -2
  72. package/dist/{routing-D7W4BDER.js → routing-BGMIY5JY.js} +2 -2
  73. package/dist/schedule-tool-P6XM6W3S.js +2 -0
  74. package/dist/{scheduler-JHY767T4.js → scheduler-PUKN5YSL.js} +2 -2
  75. package/dist/{seat-44NEMWB5.js → seat-OTAJJ5BP.js} +2 -2
  76. package/dist/{select-5FMPLCCG.js → select-KKMXIVVL.js} +2 -2
  77. package/dist/{set-enabled-GVQFNLOS.js → set-enabled-BNF427ZN.js} +2 -2
  78. package/dist/{sprint-tool-X3A5VPJP.js → sprint-tool-Y72HTX5X.js} +2 -2
  79. package/dist/{sprint-tool-X3A5VPJP.js.map → sprint-tool-Y72HTX5X.js.map} +1 -1
  80. package/dist/{tool-KCOCIAFM.js → tool-DW6MYEG2.js} +2 -2
  81. package/dist/{tool-KCOCIAFM.js.map → tool-DW6MYEG2.js.map} +1 -1
  82. package/dist/tool-EA4FWTH6.js +2 -0
  83. package/dist/{tool-QIS3CLU2.js → tool-F4ZVMX4J.js} +2 -2
  84. package/dist/{tool-QIS3CLU2.js.map → tool-F4ZVMX4J.js.map} +1 -1
  85. package/dist/{tool-H7RMHTXM.js → tool-HUOT3I42.js} +2 -2
  86. package/dist/{tool-H7RMHTXM.js.map → tool-HUOT3I42.js.map} +1 -1
  87. package/dist/tool-QDAD4ACK.js +4 -0
  88. package/dist/{tool-ILYSRPZ5.js.map → tool-QDAD4ACK.js.map} +1 -1
  89. package/dist/{wiki-UMPPYYFR.js → wiki-J6MSHSVD.js} +2 -2
  90. package/dist/wiki-enrich-3Y3TZ6ZK.js +2 -0
  91. package/dist/{workspace-setup-VGXHYCD5.js → workspace-setup-CQ5FMT2B.js} +2 -2
  92. package/dist/workspace-setup-CQ5FMT2B.js.map +1 -0
  93. package/package.json +1 -1
  94. package/dist/board-dashboard-TZKV4DFV.js.map +0 -1
  95. package/dist/chunk-4A6UVU2X.js +0 -134
  96. package/dist/chunk-4A6UVU2X.js.map +0 -1
  97. package/dist/chunk-F2XNWKIL.js.map +0 -1
  98. package/dist/chunk-MOEXP6U3.js +0 -8
  99. package/dist/chunk-MOEXP6U3.js.map +0 -1
  100. package/dist/chunk-OQQTV3OF.js +0 -12
  101. package/dist/chunk-OQQTV3OF.js.map +0 -1
  102. package/dist/chunk-RKPAVWXF.js +0 -2
  103. package/dist/chunk-RKPAVWXF.js.map +0 -1
  104. package/dist/chunk-XXFVK5D7.js.map +0 -1
  105. package/dist/org-tool-OE5QP6W7.js +0 -2
  106. package/dist/program-7QFRDJUY.js.map +0 -1
  107. package/dist/schedule-tool-B4RDOKCN.js +0 -2
  108. package/dist/tool-ILYSRPZ5.js +0 -4
  109. package/dist/tool-Z7TIGVEW.js +0 -7
  110. package/dist/tool-Z7TIGVEW.js.map +0 -1
  111. package/dist/wiki-enrich-UVCZ7GTW.js +0 -2
  112. /package/dist/{App-YGVVIKZD.js.map → App-IXJCCCGN.js.map} +0 -0
  113. /package/dist/{ChatApp-6TEK2WMU.js.map → ChatApp-4YCCRL5M.js.map} +0 -0
  114. /package/dist/{absorb-eval-MJ475CNV.js.map → absorb-eval-YE57HA6N.js.map} +0 -0
  115. /package/dist/{adapter-C6YORAE6.js.map → adapter-CRVWPQBN.js.map} +0 -0
  116. /package/dist/{agent-44SGRWX2.js.map → agent-CTZN3P2K.js.map} +0 -0
  117. /package/dist/{chunk-U5DSMDCJ.js.map → chunk-2F7KQ4DJ.js.map} +0 -0
  118. /package/dist/{chunk-5SQRJUAK.js.map → chunk-2MAKXLK2.js.map} +0 -0
  119. /package/dist/{chunk-2KQECT4H.js.map → chunk-3B7RH3IK.js.map} +0 -0
  120. /package/dist/{chunk-2ZNYIHRB.js.map → chunk-3C6UDZDX.js.map} +0 -0
  121. /package/dist/{chunk-F32VADB7.js.map → chunk-56UTQ4FU.js.map} +0 -0
  122. /package/dist/{chunk-BLKXK27S.js.map → chunk-64IVC2G6.js.map} +0 -0
  123. /package/dist/{chunk-TO6T6AQY.js.map → chunk-AOPNASCE.js.map} +0 -0
  124. /package/dist/{chunk-IKXDCPXS.js.map → chunk-FFLMSNTN.js.map} +0 -0
  125. /package/dist/{chunk-WLDRIJQX.js.map → chunk-GEKEILPL.js.map} +0 -0
  126. /package/dist/{chunk-T3B7OUDC.js.map → chunk-I4FXWN7I.js.map} +0 -0
  127. /package/dist/{chunk-3UATFGSB.js.map → chunk-IP67DTXX.js.map} +0 -0
  128. /package/dist/{chunk-TFHJT2AZ.js.map → chunk-LLNLDZNA.js.map} +0 -0
  129. /package/dist/{chunk-LDSBFDYB.js.map → chunk-LSFLSB7C.js.map} +0 -0
  130. /package/dist/{chunk-YTWRIIAT.js.map → chunk-M42GMRZF.js.map} +0 -0
  131. /package/dist/{chunk-PA7CP74O.js.map → chunk-MFZNBE65.js.map} +0 -0
  132. /package/dist/{chunk-GEKJQ7VV.js.map → chunk-NFUHYIYG.js.map} +0 -0
  133. /package/dist/{chunk-LJUBWMPB.js.map → chunk-OJ4RUZZY.js.map} +0 -0
  134. /package/dist/{chunk-AU7SN4G3.js.map → chunk-Q432O462.js.map} +0 -0
  135. /package/dist/{chunk-T7SD5EVH.js.map → chunk-QEOGWSRR.js.map} +0 -0
  136. /package/dist/{chunk-7OJUZ3L5.js.map → chunk-QGRIW7SE.js.map} +0 -0
  137. /package/dist/{chunk-SZXFWCKA.js.map → chunk-RKKAP4EY.js.map} +0 -0
  138. /package/dist/{chunk-JTS563OC.js.map → chunk-SJJ7QEFE.js.map} +0 -0
  139. /package/dist/{chunk-6UTOBSEA.js.map → chunk-SYIDD7CI.js.map} +0 -0
  140. /package/dist/{chunk-JNBUJKNG.js.map → chunk-X2GBLX3E.js.map} +0 -0
  141. /package/dist/{chunk-M4H2RYP4.js.map → chunk-XQH4LCZR.js.map} +0 -0
  142. /package/dist/{chunk-MH7KJQ4N.js.map → chunk-YXGZSVPY.js.map} +0 -0
  143. /package/dist/{chunk-JMWPBZLU.js.map → chunk-Z5HYCMDF.js.map} +0 -0
  144. /package/dist/{client-SJLHZDIC.js.map → client-UPXDV3SM.js.map} +0 -0
  145. /package/dist/{config-Q3ENZQYL.js.map → config-LAM4HUTA.js.map} +0 -0
  146. /package/dist/{config-mutate-NNAUMQ2Y.js.map → config-mutate-P4QLFUVH.js.map} +0 -0
  147. /package/dist/{config-mutator-2F2BJNMA.js.map → config-mutator-RIPSMYAO.js.map} +0 -0
  148. /package/dist/{contributions-SOUGZCAH.js.map → contributions-SHSEI3TX.js.map} +0 -0
  149. /package/dist/{doctor-H6I433KY.js.map → doctor-TLDBNHYM.js.map} +0 -0
  150. /package/dist/{grants-U2734ZHZ.js.map → grants-ZA35QVTX.js.map} +0 -0
  151. /package/dist/{hub-XFZFHLJK.js.map → hub-7Y6ZUVJV.js.map} +0 -0
  152. /package/dist/{promote-FQY3HNL6.js.map → promote-OBTQ3ZUN.js.map} +0 -0
  153. /package/dist/{query-LIII4CGT.js.map → query-K6NR3GQE.js.map} +0 -0
  154. /package/dist/{query-settings-6LHW2NCF.js.map → query-settings-NIZBB73K.js.map} +0 -0
  155. /package/dist/{registry-WQNBXOUL.js.map → registry-B7X6YGS7.js.map} +0 -0
  156. /package/dist/{request-planner-HYYT3W7X.js.map → request-planner-YDIX4BQW.js.map} +0 -0
  157. /package/dist/{review-candidates-JOCZEZ2L.js.map → review-candidates-3QCCHXWM.js.map} +0 -0
  158. /package/dist/{routing-D7W4BDER.js.map → routing-BGMIY5JY.js.map} +0 -0
  159. /package/dist/{schedule-tool-B4RDOKCN.js.map → schedule-tool-P6XM6W3S.js.map} +0 -0
  160. /package/dist/{scheduler-JHY767T4.js.map → scheduler-PUKN5YSL.js.map} +0 -0
  161. /package/dist/{seat-44NEMWB5.js.map → seat-OTAJJ5BP.js.map} +0 -0
  162. /package/dist/{select-5FMPLCCG.js.map → select-KKMXIVVL.js.map} +0 -0
  163. /package/dist/{set-enabled-GVQFNLOS.js.map → set-enabled-BNF427ZN.js.map} +0 -0
  164. /package/dist/{wiki-UMPPYYFR.js.map → tool-EA4FWTH6.js.map} +0 -0
  165. /package/dist/{wiki-enrich-UVCZ7GTW.js.map → wiki-J6MSHSVD.js.map} +0 -0
  166. /package/dist/{workspace-setup-VGXHYCD5.js.map → wiki-enrich-3Y3TZ6ZK.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as E}from"./chunk-IMLAPB7G.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{n as x}from"./chunk-OQQTV3OF.js";import{Ja as ne,Ka as re,Ma as oe,Na as ie,Ua as I,Za as Je}from"./chunk-4A6UVU2X.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(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 X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(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 tn(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 U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(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 ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{a as E}from"./chunk-IMLAPB7G.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{o as x}from"./chunk-BXK5S2KK.js";import{Ra as ne,Sa as re,Ua as oe,Va as ie,ab as I,fb as Je}from"./chunk-PZ2F6J2E.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(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 X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(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 tn(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 U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(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 ${U(e.cwd)} && ${U(e.node)} ${U(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??X)}</string>
@@ -35,4 +35,4 @@ function run(argv) {
35
35
  `),Dt(r,n)}var Ft=5*6e4;function Wr(e,t,n=Date.now()){let r=ee(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ft)?!1:r.items[`card:${t}`]?.state!=="failed"}var te=24*36e5;function Ue(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 jt(e,t,n,r){let o=Date.parse(e.expires),i=[w(e.ask,x.ask)];return e.choices?.length&&i.push(...e.choices.map((s,l)=>`${l+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${w(e.recommend,x.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,x.title),notes:i.join(`
36
36
  `),due:Ue(r,t,o),priority:Number.isFinite(o)&&o-r<=te?"high":"none"}}function Bt(e,t,n,r){let o=[w(e.question||e.text,x.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:Y(e,x.title).headline,notes:o.join(`
37
37
  `),due:Ue(r,t,i),priority:i!==void 0&&i-r<=te?"high":"none"}}async function qr(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),l={created:0,completed:0,dismissed:0,failed:0},a=ee(t);delete a.lastError;let c=u=>{a.lastError={at:s,message:u}},g=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>i&&g.set(`card:${u.id}`,jt(u,n,e.answerUrl,i));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&g.set(`request:${u.id}`,Bt(u,n,e.answerUrl,i))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Fe(t,a),l}let D=!0,h=new Map,Xe=async u=>{if(!h.has(u))try{h.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)),h.set(u,null),D=!1}return h.get(u)};for(let[u,p]of Object.entries(a.items)){if(p.state!=="open"||!p.id)continue;let d=await Xe(p.list);if(d)if(g.has(u))d.has(p.id)||(a.items[u]={...p,state:"dismissed",at:s},l.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(S){o(`[mirror] ${u}: could not complete its task: ${S?.message??S}`),c(String(S?.message??S));continue}a.items[u]={...p,state:"completed",at:s},l.completed++}}let R=null,W="",q=0,v=[];for(let[u,p]of g){let d=a.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=Z)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(f){o(`[mirror] could not make list "${n.list}": ${f?.message??f}`),W=String(f?.message??f),c(W),R=!1}let S=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:f}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});a.items[u]={id:f,list:n.list,state:"open",at:s,createdAt:s,failures:0},l.created++}catch(f){let P=String(f?.message??f);u.startsWith("card:")&&q++;let H=S+1;a.items[u]={list:n.list,state:"failed",at:s,failures:H,lastError:P},c(P),l.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${Z}): ${P}`),H===Z&&v.push({title:p.title,message:P})}}q&&o(`[mirror] ${q} card(s) could not be added to Reminders; the Mac popup shows them instead`);let Ge=a.failureToldAt?Date.parse(a.failureToldAt):NaN;if(v.length&&!(i-Ge<te)){let u=v[0],p=v.length>1?` (and ${v.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),a.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}D&&(a.checkedAt=s,a.cards=n.include.includes("card"));for(let[u,p]of Object.entries(a.items))p.state!=="open"&&!g.has(u)&&i-Date.parse(p.at)>Ht&&delete a.items[u];return Fe(t,a),l}var je=5*6e4;function Hr(e,t,n,r,o=Date.now()){let i=ee(e),s=a=>{let c=a?Date.parse(a):NaN;return c>=n&&c<r},l={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[a,c]of Object.entries(i.items))!c.id||!s(c.createdAt)||(a.startsWith("card:")?l.created.cards++:l.created.requests++);for(let a of t){if(!s(a.created_at))continue;l.raised++;let c=i.items[`card:${a.id}`];if(c?.id)continue;let g=Date.parse(a.created_at);if((a.status==="pending"?NaN:Date.parse(a.decided_at??""))-g<=je){l.closedFast++;continue}if(a.status==="pending"&&o-g<=je){l.tooNew++;continue}let h=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";l.missed.push({id:a.id,title:a.title,reason:h})}return l}function Fr(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{Nr as a,Me as b,V as c,Q as d,Ar as e,br as f,Tt as g,vr as h,kr as i,Rr as j,Y as k,w as l,Ct as m,Or as n,$ as o,ce as p,Ve as q,Xt as r,Yt as s,Zt as t,en as u,tn as v,nn as w,rn as x,on as y,sn as z,me as A,an as B,un as C,ln as D,cn as E,st as F,k as G,Se as H,z as I,Le as J,fr as K,gr as L,yr as M,ee as N,Wr as O,qr as P,Hr as Q,Fr as R};
38
- //# sourceMappingURL=chunk-U5DSMDCJ.js.map
38
+ //# sourceMappingURL=chunk-2F7KQ4DJ.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-T7SD5EVH.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-BLKXK27S.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-QEOGWSRR.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-64IVC2G6.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-Q3ENZQYL.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-5SQRJUAK.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-LAM4HUTA.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-2MAKXLK2.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-AU7SN4G3.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-BLKXK27S.js";import{b as Rt,f as Wr}from"./chunk-72SZI2UW.js";import{Na as je,Za as Pr}from"./chunk-4A6UVU2X.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-Q432O462.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-64IVC2G6.js";import{b as Rt,f as Wr}from"./chunk-72SZI2UW.js";import{Va as je,fb as Pr}from"./chunk-PZ2F6J2E.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-2KQECT4H.js.map
42
+ //# sourceMappingURL=chunk-3B7RH3IK.js.map
@@ -1,4 +1,4 @@
1
- import{jc as l,tc as m}from"./chunk-4A6UVU2X.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{Bc as m,rc as l}from"./chunk-PZ2F6J2E.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-2ZNYIHRB.js.map
4
+ //# sourceMappingURL=chunk-3C6UDZDX.js.map
@@ -1,2 +1,2 @@
1
- import{s as p}from"./chunk-AU7SN4G3.js";import{b as i,c as u,d as l,e as c}from"./chunk-LDSBFDYB.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-F32VADB7.js.map
1
+ import{s as p}from"./chunk-Q432O462.js";import{b as i,c as u,d as l,e as c}from"./chunk-LSFLSB7C.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-56UTQ4FU.js.map
@@ -1,4 +1,4 @@
1
- import{Ha as E,Ia as S,Ka as T,La as _,Ma as q,a as w,d as R,h,j,n as $,p as U}from"./chunk-4A6UVU2X.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-PZ2F6J2E.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{Ha as E,Ia as S,Ka as T,La as _,Ma as q,a as w,d as R,h,j,n as $,p as U}f
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-I4E6BH27.js.map
20
+ //# sourceMappingURL=chunk-5FFNFW4C.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/requests/goal-store.ts","../src/requests/checkers/count.ts","../src/numbers/goal-check.ts","../src/requests/today.ts","../src/requests/flow.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { DEFAULT_CHECKER_SETTINGS, describeCloseWhen, parseCloseWhen, readCloseWhen, type CheckerSettings, type CheckResult, type CloseWhen } from \"./checkers\"\nimport { describeCount, parseCountSpec, readCountSpec, type CountSpec } from \"./checkers/count\"\nimport type { RequestGoal } from \"./goals\"\nimport { describeNumberCheck, parseNumberCheck, readNumberCheck, type NumberCheck } from \"@/numbers/goal-check\"\n\n// --- A goal as its own record (#1568 part 3) ---\n//\n// Until now a goal was a label on a request: it existed while a request\n// named it (#1168). Crons need something lasting to point at, so a goal is\n// now a row of its own: a title, an owner agent, a state (active, done or\n// dropped), what \"done\" means in words, and optionally a check the daemon\n// runs itself (any loop checker, or an open count). Requests keep their\n// goal_id; accepting a request with a goal makes the record when it is\n// new. A goal is done when its check is met, or when its owner closes it.\n// A closed goal stays closed: a new goal needs a new id.\n\nexport const GOAL_STATES = [\"active\", \"done\", \"dropped\"] as const\nexport type GoalState = (typeof GOAL_STATES)[number]\n\nexport const DONE_WHEN_MAX = 300\nexport const GOAL_EVIDENCE_MAX = 500\n\n/** What closes a goal: a loop checker, an open count (#1568), or the\n * newest reading of a number crossing a threshold (#1826). */\nexport type GoalCheck = CloseWhen | ({ kind: \"count\" } & CountSpec) | NumberCheck\n\nexport interface GoalRecord {\n id: string\n title: string\n /** The agent that keeps it moving and may close it. */\n ownerAgent: string | null\n state: GoalState\n doneWhen: string | null\n check: GoalCheck | null\n /** Why it closed: the check's evidence, or the owner's words. */\n evidence: string | null\n /** What the check saw last time, and when. */\n lastCheck: string | null\n lastCheckAt: number | null\n createdAt: number\n updatedAt: number\n closedAt: number | null\n}\n\n/** Check the `check` (or closeWhen) of a goal: a spec, or why it is refused. */\nexport function parseGoalCheck(v: unknown, settings: CheckerSettings = DEFAULT_CHECKER_SETTINGS, now = Date.now()): GoalCheck | string {\n if (v && typeof v === \"object\" && !Array.isArray(v) && String((v as any).kind).trim().toLowerCase() === \"count\") {\n const spec = parseCountSpec(v as Record<string, unknown>)\n return typeof spec === \"string\" ? spec : { kind: \"count\", ...spec }\n }\n if (v && typeof v === \"object\" && !Array.isArray(v) && String((v as any).kind).trim().toLowerCase() === \"number\") {\n return parseNumberCheck(v as Record<string, unknown>)\n }\n const spec = parseCloseWhen(v, settings, now)\n if (typeof spec !== \"string\") return spec\n return /^closeWhen(\\.kind)? must be/.test(spec) ? \"check must be an object with a kind: url, issue, git-ancestor, reply, count or number\" : spec.replace(/^closeWhen/, \"check\")\n}\n\nfunction readGoalCheck(json: string | null): GoalCheck | null {\n if (!json) return null\n try {\n const raw = JSON.parse(json)\n if (raw?.kind === \"count\") {\n const spec = readCountSpec(json)\n return spec ? { kind: \"count\", ...spec } : null\n }\n if (raw?.kind === \"number\") return readNumberCheck(raw)\n } catch {\n return null\n }\n return readCloseWhen(json)\n}\n\nexport function describeGoalCheck(check: GoalCheck): string {\n return check.kind === \"count\" ? describeCount(check) : check.kind === \"number\" ? describeNumberCheck(check) : describeCloseWhen(check)\n}\n\nfunction toGoal(r: any): GoalRecord {\n return {\n id: r.id, title: r.title, ownerAgent: r.owner_agent ?? null, state: r.state, doneWhen: r.done_when ?? null,\n check: readGoalCheck(r.check_spec), evidence: r.evidence ?? null, lastCheck: r.last_check ?? null, lastCheckAt: r.last_check_at ?? null,\n createdAt: r.created_at, updatedAt: r.updated_at, closedAt: r.closed_at ?? null,\n }\n}\n\nexport interface GoalInput extends RequestGoal {\n ownerAgent?: string | null\n doneWhen?: string | null\n check?: GoalCheck | null\n}\n\nexport class GoalStore {\n constructor(private db: Database.Database) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS goals (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n owner_agent TEXT,\n state TEXT NOT NULL DEFAULT 'active',\n done_when TEXT,\n check_spec TEXT,\n evidence TEXT,\n last_check TEXT,\n last_check_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n closed_at INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_goals_state ON goals(state);\n `)\n }\n\n get(id: string): GoalRecord | null {\n const row = this.db.prepare(\"SELECT * FROM goals WHERE id = ?\").get(id)\n return row ? toGoal(row) : null\n }\n\n /** Most recently updated first. */\n list(states: readonly GoalState[] = GOAL_STATES, limit = 200): GoalRecord[] {\n const marks = states.map(() => \"?\").join(\", \")\n return (this.db.prepare(`SELECT * FROM goals WHERE state IN (${marks}) ORDER BY updated_at DESC, rowid DESC LIMIT ?`).all(...states, limit) as any[]).map(toGoal)\n }\n\n /** The record of a goal a request names on accept: made when it is new,\n * left as it is otherwise (its title and owner are the record's). */\n ensure(goal: RequestGoal, ownerAgent: string | null, now: number): GoalRecord {\n this.db.prepare(\n \"INSERT INTO goals (id, title, owner_agent, state, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?) ON CONFLICT(id) DO NOTHING\",\n ).run(goal.id, goal.title, ownerAgent, now, now)\n return this.get(goal.id)!\n }\n\n /** Make a goal, or change an active one: only the fields given change. */\n upsert(input: GoalInput, now: number): GoalRecord {\n const had = this.get(input.id)\n if (!had) {\n this.db.prepare(\n \"INSERT INTO goals (id, title, owner_agent, state, done_when, check_spec, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?, ?, ?)\",\n ).run(input.id, input.title, input.ownerAgent ?? null, input.doneWhen ?? null, input.check ? JSON.stringify(input.check) : null, now, now)\n } else {\n this.db.prepare(\n \"UPDATE goals SET title = ?, owner_agent = ?, done_when = ?, check_spec = ?, updated_at = ? WHERE id = ?\",\n ).run(\n input.title || had.title,\n input.ownerAgent !== undefined ? input.ownerAgent : had.ownerAgent,\n input.doneWhen !== undefined ? input.doneWhen : had.doneWhen,\n input.check !== undefined ? (input.check ? JSON.stringify(input.check) : null) : (had.check ? JSON.stringify(had.check) : null),\n now, input.id,\n )\n }\n return this.get(input.id)!\n }\n\n /** Close an active goal as done or dropped. False when it was not active. */\n close(id: string, state: Exclude<GoalState, \"active\">, evidence: string | null, now: number): boolean {\n const res = this.db.prepare(\n \"UPDATE goals SET state = ?, evidence = ?, closed_at = ?, updated_at = ? WHERE id = ? AND state = 'active'\",\n ).run(state, evidence ? evidence.slice(0, GOAL_EVIDENCE_MAX) : null, now, now, id)\n return res.changes > 0\n }\n\n /** What the check saw: not a change of the goal, so updated_at stays. */\n markChecked(id: string, detail: string, now: number): void {\n this.db.prepare(\"UPDATE goals SET last_check = ?, last_check_at = ? WHERE id = ?\").run(detail.slice(0, GOAL_EVIDENCE_MAX), now, id)\n }\n\n /** Active goals with a check last run at `before` or earlier (or never). */\n dueChecks(before: number): GoalRecord[] {\n return (this.db.prepare(\n \"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\",\n ).all(before) as any[]).map(toGoal)\n }\n}\n\nexport type GoalChecker = (check: GoalCheck) => Promise<CheckResult>\n\n/** Run the check of every active goal not checked for `everyMinutes`.\n * Met closes the goal as done with the check's evidence. Returns the ids\n * closed. One goal's failure never stops the others. */\nexport async function checkGoals(store: GoalStore, check: GoalChecker, everyMinutes: number, now: number, log: (msg: string) => void = () => {}): Promise<string[]> {\n const closed: string[] = []\n for (const g of store.dueChecks(now - everyMinutes * 60_000)) {\n let res: CheckResult\n try {\n res = await check(g.check!)\n } catch (e: any) {\n res = { verdict: \"unverifiable\", detail: String(e?.message ?? e) }\n }\n store.markChecked(g.id, res.detail, now)\n if (res.verdict === \"met\" && store.close(g.id, \"done\", `check: ${res.detail}`, now)) {\n closed.push(g.id)\n log(`[goals] ${g.id} done: ${res.detail}`)\n } else if (res.verdict === \"unverifiable\") {\n log(`[goals] ${g.id}: check failed: ${res.detail}`)\n }\n }\n return closed\n}\n\n/** The goal's state for a cron prompt or a plan turn: a few lines. */\nexport function goalBrief(g: GoalRecord, counts?: { open: number; done: number } | null): string {\n const lines = [`[Goal] ${g.title} (${g.id}): ${g.state}${g.ownerAgent ? `, owner ${g.ownerAgent}` : \"\"}.`]\n if (g.doneWhen) lines.push(`Done when: ${g.doneWhen}`)\n if (g.check) lines.push(`Check: ${describeGoalCheck(g.check)}${g.lastCheck ? `; last seen: ${g.lastCheck}${g.lastCheckAt ? ` (${new Date(g.lastCheckAt).toISOString().slice(0, 16).replace(\"T\", \" \")} UTC)` : \"\"}` : \"\"}`)\n if (counts) lines.push(`Requests under it: ${counts.open} open, ${counts.done} done.`)\n return lines.join(\"\\n\")\n}\n","import type { CheckResult } from \"./index\"\nimport { forgeHeaders, type ForgeConnectors } from \"./issue\"\n\n// --- count: how many issues or pull requests a project has open (#1568) ---\n//\n// A plan step can carry a count check (\"open issues in owner/repo = 0\").\n// The plan check reads the count through the GitHub or GitLab connector,\n// marks the step done when it is at or under `max`, and keeps the last\n// count so a turn that brought it down counts as progress. One read per\n// kind: GitHub's search total, GitLab's X-Total header.\n\nexport type CountWhat = \"issues\" | \"prs\" | \"all\"\n\nexport interface CountSpec {\n provider: \"github\" | \"gitlab\"\n /** \"owner/repo\" on GitHub, \"group/project\" on GitLab. */\n project: string\n what: CountWhat\n /** Done at this count or under. */\n max: number\n}\n\n/** Reads one open count, or says why it could not. */\nexport type ForgeCounter = (provider: \"github\" | \"gitlab\", project: string, kind: \"issues\" | \"prs\") => Promise<number | { error: string }>\n\nconst TIMEOUT_MS = 10_000\nconst WHATS: readonly CountWhat[] = [\"issues\", \"prs\", \"all\"]\nconst PROJECT_RE = /^[\\w.-]+(?:\\/[\\w.-]+)+$/\n\nconst str = (v: unknown) => (typeof v === \"string\" ? v.trim() : \"\")\n\nexport function parseCountSpec(raw: Record<string, unknown>): CountSpec | string {\n const provider = str(raw.provider).toLowerCase()\n if (provider !== \"github\" && provider !== \"gitlab\") return \"count.provider must be github or gitlab\"\n const project = str(raw.project)\n const parts = project.split(\"/\")\n if (!PROJECT_RE.test(project) || parts.some((p) => p === \".\" || p === \"..\") || (provider === \"github\" && parts.length !== 2)) {\n return provider === \"github\" ? 'count.project must be \"owner/repo\"' : 'count.project must be \"group/project\"'\n }\n const what = (str(raw.what) || \"issues\").toLowerCase()\n if (!(WHATS as readonly string[]).includes(what)) return `count.what must be one of ${WHATS.join(\", \")}`\n const max = raw.max === undefined || raw.max === null || raw.max === \"\" ? 0 : Number(raw.max)\n if (!Number.isInteger(max) || max < 0) return \"count.max must be a whole number, 0 or more\"\n return { provider, project, what: what as CountWhat, max }\n}\n\n/** A stored spec read back. Null when it is not one. */\nexport function readCountSpec(json: string | null | undefined): CountSpec | null {\n if (!json) return null\n try {\n const v = JSON.parse(json)\n if (!v || typeof v !== \"object\") return null\n const spec = parseCountSpec(v)\n return typeof spec === \"string\" ? null : spec\n } catch {\n return null\n }\n}\n\nconst whatWords = (w: CountWhat) => (w === \"issues\" ? \"open issues\" : w === \"prs\" ? \"open pull requests\" : \"open issues and pull requests\")\n\nexport function describeCount(spec: CountSpec): string {\n return `${whatWords(spec.what)} in ${spec.provider} ${spec.project} ≤ ${spec.max}`\n}\n\n/** The count now, and whether it is at or under max. Never throws. */\nexport async function checkCount(spec: CountSpec, counter: ForgeCounter | undefined): Promise<CheckResult & { count?: number }> {\n if (!counter) return { verdict: \"unverifiable\", detail: `no ${spec.provider} connector on this node` }\n try {\n const kinds: Array<\"issues\" | \"prs\"> = spec.what === \"all\" ? [\"issues\", \"prs\"] : [spec.what]\n let count = 0\n for (const kind of kinds) {\n const n = await counter(spec.provider, spec.project, kind)\n if (typeof n !== \"number\") return { verdict: \"unverifiable\", detail: `${spec.project}: ${n.error}` }\n count += n\n }\n const detail = `${count} ${whatWords(spec.what)} in ${spec.project}`\n return { verdict: count <= spec.max ? \"met\" : \"not_met\", detail, count }\n } catch (e: any) {\n return { verdict: \"unverifiable\", detail: `the count check failed: ${String(e?.message ?? e).slice(0, 200)}` }\n }\n}\n\n/** The counter over the REST APIs of GitHub and GitLab. */\nexport function forgeCounter(connectors: ForgeConnectors, doFetch: typeof fetch = fetch): ForgeCounter {\n return async (provider, project, kind) => {\n let url: string\n if (provider === \"github\") {\n const c = connectors.github\n if (!c) return { error: \"no github connector on this node (channels.github or requests.checkers.github)\" }\n const q = encodeURIComponent(`repo:${project} is:open is:${kind === \"prs\" ? \"pr\" : \"issue\"}`)\n url = `${c.apiUrl.replace(/\\/$/, \"\")}/search/issues?q=${q}&per_page=1`\n } else {\n const c = connectors.gitlab\n if (!c) return { error: \"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)\" }\n url = `${c.url.replace(/\\/$/, \"\")}/api/v4/projects/${encodeURIComponent(project)}/${kind === \"prs\" ? \"merge_requests\" : \"issues\"}?state=opened&per_page=1`\n }\n let res: Response\n try {\n res = await doFetch(url, { headers: forgeHeaders(provider, connectors), signal: AbortSignal.timeout(TIMEOUT_MS) })\n } catch (e: any) {\n return { error: `could not be reached: ${String(e?.message ?? e).slice(0, 200)}` }\n }\n if (!res.ok) return { error: res.status === 404 ? \"not found (or not visible to the connector)\" : `HTTP ${res.status}` }\n if (provider === \"gitlab\") {\n const total = Number(res.headers.get(\"x-total\"))\n return Number.isInteger(total) && total >= 0 ? total : { error: \"no X-Total in the answer\" }\n }\n const body: any = await res.json().catch(() => null)\n const total = Number(body?.total_count)\n return Number.isInteger(total) && total >= 0 ? total : { error: \"no total_count in the answer\" }\n }\n}\n","import type { CheckResult } from \"@/requests/checkers\"\nimport { describePeriod, formatValue, parseNumberId } from \"./model\"\nimport type { NumberStore } from \"./store\"\n\n// --- The `number` check of a goal (#1826) ---\n//\n// {kind:\"number\", number:\"<id>\", atLeast:1000} or {…, atMost:2}: met when\n// the newest reading of the number crosses the threshold. A goal can close\n// itself on a number this way. No reading (none yet, or the newest read\n// failed) is unverifiable, never a 0.\n\nexport interface NumberCheck {\n kind: \"number\"\n number: string\n atLeast?: number\n atMost?: number\n}\n\nexport function parseNumberCheck(raw: Record<string, unknown>): NumberCheck | string {\n const id = parseNumberId(raw.number ?? raw.id)\n if (typeof id !== \"string\") return `check.number: ${id.error}`\n const has = (k: string) => raw[k] !== undefined && raw[k] !== null && raw[k] !== \"\"\n if (has(\"atLeast\") === has(\"atMost\")) return \"a number check needs one of atLeast or atMost: the threshold its reading must cross\"\n const key = has(\"atLeast\") ? \"atLeast\" : \"atMost\"\n const value = Number(raw[key])\n if (!Number.isFinite(value)) return `check.${key} must be a number`\n return { kind: \"number\", number: id, [key]: value }\n}\n\nexport function readNumberCheck(v: any): NumberCheck | null {\n if (!v || typeof v !== \"object\" || v.kind !== \"number\") return null\n const spec = parseNumberCheck(v)\n return typeof spec === \"string\" ? null : spec\n}\n\nexport function describeNumberCheck(c: NumberCheck): string {\n return c.atLeast !== undefined ? `number ${c.number} reads ≥ ${formatValue(c.atLeast)}` : `number ${c.number} reads ≤ ${formatValue(c.atMost!)}`\n}\n\n/** The newest reading against the threshold. Never throws. */\nexport function checkNumber(c: NumberCheck, store: NumberStore | undefined): CheckResult {\n if (!store) return { verdict: \"unverifiable\", detail: \"this node keeps no numbers\" }\n const n = store.get(c.number)\n if (!n) return { verdict: \"unverifiable\", detail: `no number \"${c.number}\"` }\n const latest = store.readings(c.number, 1)[0]\n if (!latest || latest.value === null) {\n return { verdict: \"unverifiable\", detail: `${c.number}: no reading${latest?.error ? ` (${latest.error})` : \"\"}` }\n }\n const met = c.atLeast !== undefined ? latest.value >= c.atLeast : latest.value <= c.atMost!\n const detail = `${n.name}: ${formatValue(latest.value, n.unit)} for ${describePeriod({ start: latest.periodStart, end: latest.periodEnd })}`\n return { verdict: met ? \"met\" : \"not_met\", detail }\n}\n","import type { RequestRecord } from \"./store\"\n\n// --- \"What did I ask today, and where did it land\" (#394, 1c C) ---\n//\n// One row per request made since 00:00 Tunis: time, first words, state,\n// owner, and where it landed. A request with nowhere it landed goes red, at\n// the top. No model: the Secretary reads it out, the Desk shows it.\n\nexport const TODAY_ZONE = \"Africa/Tunis\"\n\nexport interface Landed { kind: string; ref: string }\n\nexport interface TodayRow {\n id: string\n /** HH:MM, Tunis time. */\n time: string\n words: string\n state: string\n owner: string\n landed: Landed[]\n noHome: boolean\n}\n\n/** Epoch ms of the last 00:00 in `zone` at or before `now`. */\nexport function startOfDay(now: number, zone = TODAY_ZONE): number {\n const parts = Object.fromEntries(\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: zone, hour12: false, hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" })\n .formatToParts(new Date(now)).map((p) => [p.type, p.value]),\n )\n const elapsed = ((Number(parts.hour) % 24) * 3600 + Number(parts.minute) * 60 + Number(parts.second)) * 1000 + (now % 1000)\n return now - elapsed\n}\n\nconst clock = (ms: number, zone: string) =>\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: zone, hour12: false, hour: \"2-digit\", minute: \"2-digit\" }).format(new Date(ms))\n\n/** The first `n` words of a request, on one line. */\nexport function firstWords(text: string, n = 10): string {\n const words = text.replace(/\\s+/g, \" \").trim().split(\" \")\n return words.slice(0, n).join(\" \") + (words.length > n ? \" …\" : \"\")\n}\n\n/** Link kinds that say where the work lives: a home (#394), or an\n * approval card put to the owner. Runs, delegations and workflows do not. */\nconst LANDING_LINKS = new Set([\"issue\", \"idea\", \"approval\", \"erp\", \"card\"])\n\nexport function todayRows(\n items: Array<RequestRecord & { links?: Array<{ kind: string; ref: string }> }>,\n opts: { hasPlan?: (id: string) => boolean; zone?: string } = {},\n): TodayRow[] {\n const rows = items.map((r): TodayRow => {\n const landed: Landed[] = []\n const add = (kind: string, ref: string) => { if (!landed.some((l) => l.kind === kind && l.ref === ref)) landed.push({ kind, ref }) }\n for (const l of r.links ?? []) if (LANDING_LINKS.has(l.kind)) add(l.kind, l.ref)\n if (r.home) add(r.home.kind, r.home.link)\n if (opts.hasPlan?.(r.id)) add(\"plan\", r.id)\n if (r.evidence) add(\"evidence\", r.evidence)\n return {\n id: r.id, time: clock(r.createdAt, opts.zone ?? TODAY_ZONE), words: firstWords(r.text), state: r.state, owner: r.agentId,\n // Declined or dropped: closed on purpose, nothing was to land.\n landed, noHome: landed.length === 0 && r.state !== \"declined\" && r.state !== \"dropped\",\n }\n })\n // Red first; each group in the order asked.\n return [...rows.filter((r) => r.noHome), ...rows.filter((r) => !r.noHome)]\n}\n","import { startOfDay, TODAY_ZONE } from \"./today\"\nimport type { RequestStore } from \"./store\"\n\n// --- The daily flow rate of requests (#1542) ---\n//\n// Every request asked in a day (the owner's day, `requests.flow.timeZone`),\n// and where each one stands now:\n// asked requests made that day (candidates left out)\n// done closed as done\n// dropped declined or dropped: each carries its reason, listed beside\n// the rate so a wrong drop can be seen\n// moving in progress, or waiting on another agent\n// waiting waiting on the owner\n// stuck needs attention\n// rate (done + dropped) / asked; null on a day nothing was asked\n// resent resent once by the requests check (resend.ts), and how many\n// of those are done now\n// Read only, recomputed on every call: a request closed later moves the\n// day it was asked. No model.\n\nexport interface FlowSettings {\n timeZone: string\n days: number\n}\n\nexport const DEFAULT_FLOW: FlowSettings = { timeZone: TODAY_ZONE, days: 7 }\n\n/** Days one report may cover: closed requests age out after retentionDays. */\nexport const FLOW_DAYS_MAX = 90\n\n/** Drop reasons listed per day. */\nconst REASONS_MAX = 5\nconst REASON_WORDS = 120\n\nexport interface FlowDay {\n /** YYYY-MM-DD in the zone. */\n day: string\n /** Epoch ms of the day's 00:00 in the zone. */\n start: number\n asked: number\n done: number\n dropped: number\n moving: number\n waiting: number\n stuck: number\n rate: number | null\n /** Most frequent reasons first; `more` counts the drops not listed. */\n dropReasons: Array<{ reason: string; count: number }>\n moreReasons: number\n resent: number\n resentDone: number\n}\n\nexport interface FlowReport {\n zone: string\n /** Oldest first; the last one is today. */\n days: FlowDay[]\n today: FlowDay\n}\n\nconst dayKey = (ms: number, zone: string) =>\n new Intl.DateTimeFormat(\"en-CA\", { timeZone: zone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\" }).format(new Date(ms))\n\nfunction emptyDay(start: number, zone: string): FlowDay {\n return { day: dayKey(start, zone), start, asked: 0, done: 0, dropped: 0, moving: 0, waiting: 0, stuck: 0, rate: null, dropReasons: [], moreReasons: 0, resent: 0, resentDone: 0 }\n}\n\nexport function flowReport(store: RequestStore, opts: { days?: number; zone?: string; now?: number } = {}): FlowReport {\n const zone = opts.zone ?? DEFAULT_FLOW.timeZone\n const count = Math.min(Math.max(Math.floor(opts.days ?? DEFAULT_FLOW.days), 1), FLOW_DAYS_MAX)\n const now = opts.now ?? Date.now()\n // Walked back one 00:00 at a time: a day across a clock change is 23 or 25 h.\n const starts = [startOfDay(now, zone)]\n while (starts.length < count) starts.unshift(startOfDay(starts[0] - 1, zone))\n const days = starts.map((s) => emptyDay(s, zone))\n const reasons = days.map(() => new Map<string, number>())\n let i = 0\n for (const r of store.flowRows(starts[0])) {\n while (i + 1 < days.length && r.createdAt >= days[i + 1].start) i++\n const d = days[i]\n d.asked++\n if (r.state === \"done\") d.done++\n else if (r.state === \"declined\" || r.state === \"dropped\") {\n d.dropped++\n const why = (r.closeReason ?? \"\").replace(/\\s+/g, \" \").trim()\n const key = why.length > REASON_WORDS ? `${why.slice(0, REASON_WORDS - 1)}…` : why || \"no reason given\"\n reasons[i].set(key, (reasons[i].get(key) ?? 0) + 1)\n } else if (r.state === \"in_progress\" || r.state === \"waiting_other\") d.moving++\n else if (r.state === \"waiting_owner\") d.waiting++\n else if (r.state === \"needs_attention\") d.stuck++\n if (r.resentAt !== null) {\n d.resent++\n if (r.state === \"done\") d.resentDone++\n }\n }\n days.forEach((d, n) => {\n d.rate = d.asked ? (d.done + d.dropped) / d.asked : null\n const sorted = [...reasons[n]].sort((a, b) => b[1] - a[1])\n d.dropReasons = sorted.slice(0, REASONS_MAX).map(([reason, c]) => ({ reason, count: c }))\n d.moreReasons = sorted.slice(REASONS_MAX).reduce((sum, [, c]) => sum + c, 0)\n })\n return { zone, days, today: days[days.length - 1] }\n}\n\nconst pct = (rate: number | null) => (rate === null ? \"–\" : `${Math.round(rate * 100)}%`)\n\n/** Today's figure, then one line per day, oldest first: what the CLI\n * prints and the agentx_request tool answers. */\nexport function describeFlow(f: FlowReport): string {\n const t = f.today\n const lines = [\n `Today (${t.day}, ${f.zone}): ${t.asked ? `${t.done + t.dropped} of ${t.asked} closed, ${pct(t.rate)}` : \"nothing asked yet\"}.`,\n ` ${t.done} done, ${t.dropped} dropped, ${t.moving} moving, ${t.waiting} waiting on the owner, ${t.stuck} stuck.` +\n (t.resent ? ` ${t.resent} resent once on its own, ${t.resentDone} of them done.` : \"\"),\n ]\n if (t.dropReasons.length) {\n lines.push(\" Dropped because:\")\n for (const r of t.dropReasons) lines.push(` ${r.count} × ${r.reason}`)\n if (t.moreReasons) lines.push(` ${t.moreReasons} more`)\n }\n if (f.days.length > 1) {\n lines.push(\"\", \"Day asked done dropped moving waiting stuck rate\")\n for (const d of f.days) {\n const cells = [d.asked, d.done, d.dropped, d.moving, d.waiting, d.stuck].map(String)\n lines.push(`${d.day} ${cells[0].padStart(5)} ${cells[1].padStart(4)} ${cells[2].padStart(7)} ${cells[3].padStart(6)} ${cells[4].padStart(7)} ${cells[5].padStart(5)} ${pct(d.rate).padStart(4)}`)\n }\n }\n return lines.join(\"\\n\")\n}\n"],"mappings":"yGACAA,ICAAC,IAwBA,IAAMC,EAAa,IACbC,EAA8B,CAAC,SAAU,MAAO,KAAK,EACrDC,EAAa,0BAEbC,EAAOC,GAAgB,OAAOA,GAAM,SAAWA,EAAE,KAAK,EAAI,GAEzD,SAASC,EAAeC,EAAkD,CAC/E,IAAMC,EAAWJ,EAAIG,EAAI,QAAQ,EAAE,YAAY,EAC/C,GAAIC,IAAa,UAAYA,IAAa,SAAU,MAAO,0CAC3D,IAAMC,EAAUL,EAAIG,EAAI,OAAO,EACzBG,EAAQD,EAAQ,MAAM,GAAG,EAC/B,GAAI,CAACN,EAAW,KAAKM,CAAO,GAAKC,EAAM,KAAMC,GAAMA,IAAM,KAAOA,IAAM,IAAI,GAAMH,IAAa,UAAYE,EAAM,SAAW,EACxH,OAAOF,IAAa,SAAW,qCAAuC,wCAExE,IAAMI,GAAQR,EAAIG,EAAI,IAAI,GAAK,UAAU,YAAY,EACrD,GAAI,CAAEL,EAA4B,SAASU,CAAI,EAAG,MAAO,6BAA6BV,EAAM,KAAK,IAAI,IACrG,IAAMW,EAAMN,EAAI,MAAQ,QAAaA,EAAI,MAAQ,MAAQA,EAAI,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AM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAML,EAAIV,EAAE,IAAI,EAAE,SAAS,CAAC,GAAG,GAG3M,OAAOc,EAAM,KAAK;AAAA,CAAI,CACxB","names":["init_checkers","init_issue","TIMEOUT_MS","WHATS","PROJECT_RE","str","v","parseCountSpec","raw","provider","project","parts","p","what","max","readCountSpec","json","spec","whatWords","w","describeCount","checkCount","counter","kinds","count","kind","n","detail","e","forgeCounter","connectors","doFetch","url","c","q","res","forgeHeaders","total","body","init_model","parseNumberCheck","raw","id","parseNumberId","has","k","key","value","readNumberCheck","v","spec","describeNumberCheck","c","formatValue","checkNumber","store","n","latest","met","detail","describePeriod","GOAL_STATES","DONE_WHEN_MAX","GOAL_EVIDENCE_MAX","parseGoalCheck","v","settings","DEFAULT_CHECKER_SETTINGS","now","spec","parseCountSpec","parseNumberCheck","parseCloseWhen","readGoalCheck","json","raw","readCountSpec","readNumberCheck","readCloseWhen","describeGoalCheck","check","describeCount","describeNumberCheck","describeCloseWhen","toGoal","r","GoalStore","db","id","row","states","limit","marks","goal","ownerAgent","input","had","state","evidence","detail","before","checkGoals","store","everyMinutes","log","closed","g","res","e","goalBrief","counts","lines","TODAY_ZONE","startOfDay","now","zone","parts","p","elapsed","clock","ms","firstWords","text","n","words","LANDING_LINKS","todayRows","items","opts","rows","r","landed","add","kind","ref","l","DEFAULT_FLOW","TODAY_ZONE","FLOW_DAYS_MAX","REASONS_MAX","REASON_WORDS","dayKey","ms","zone","emptyDay","start","flowReport","store","opts","count","now","starts","startOfDay","days","s","reasons","i","r","d","why","key","n","sorted","a","b","reason","c","sum","pct","rate","describeFlow","f","lines","cells"]}
1
+ {"version":3,"sources":["../src/requests/goal-store.ts","../src/requests/checkers/count.ts","../src/numbers/goal-check.ts","../src/requests/today.ts","../src/requests/flow.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { DEFAULT_CHECKER_SETTINGS, describeCloseWhen, parseCloseWhen, readCloseWhen, type CheckerSettings, type CheckResult, type CloseWhen } from \"./checkers\"\nimport { describeCount, parseCountSpec, readCountSpec, type CountSpec } from \"./checkers/count\"\nimport type { RequestGoal } from \"./goals\"\nimport { describeNumberCheck, parseNumberCheck, readNumberCheck, type NumberCheck } from \"@/numbers/goal-check\"\n\n// --- A goal as its own record (#1568 part 3) ---\n//\n// Until now a goal was a label on a request: it existed while a request\n// named it (#1168). Crons need something lasting to point at, so a goal is\n// now a row of its own: a title, an owner agent, a state (active, done or\n// dropped), what \"done\" means in words, and optionally a check the daemon\n// runs itself (any loop checker, or an open count). Requests keep their\n// goal_id; accepting a request with a goal makes the record when it is\n// new. A goal is done when its check is met, or when its owner closes it.\n// A closed goal stays closed: a new goal needs a new id.\n\nexport const GOAL_STATES = [\"active\", \"done\", \"dropped\"] as const\nexport type GoalState = (typeof GOAL_STATES)[number]\n\nexport const DONE_WHEN_MAX = 300\nexport const GOAL_EVIDENCE_MAX = 500\n\n/** What closes a goal: a loop checker, an open count (#1568), or the\n * newest reading of a number crossing a threshold (#1826). */\nexport type GoalCheck = CloseWhen | ({ kind: \"count\" } & CountSpec) | NumberCheck\n\nexport interface GoalRecord {\n id: string\n title: string\n /** The agent that keeps it moving and may close it. */\n ownerAgent: string | null\n state: GoalState\n doneWhen: string | null\n check: GoalCheck | null\n /** Why it closed: the check's evidence, or the owner's words. */\n evidence: string | null\n /** What the check saw last time, and when. */\n lastCheck: string | null\n lastCheckAt: number | null\n createdAt: number\n updatedAt: number\n closedAt: number | null\n}\n\n/** Check the `check` (or closeWhen) of a goal: a spec, or why it is refused. */\nexport function parseGoalCheck(v: unknown, settings: CheckerSettings = DEFAULT_CHECKER_SETTINGS, now = Date.now()): GoalCheck | string {\n if (v && typeof v === \"object\" && !Array.isArray(v) && String((v as any).kind).trim().toLowerCase() === \"count\") {\n const spec = parseCountSpec(v as Record<string, unknown>)\n return typeof spec === \"string\" ? spec : { kind: \"count\", ...spec }\n }\n if (v && typeof v === \"object\" && !Array.isArray(v) && String((v as any).kind).trim().toLowerCase() === \"number\") {\n return parseNumberCheck(v as Record<string, unknown>)\n }\n const spec = parseCloseWhen(v, settings, now)\n if (typeof spec !== \"string\") return spec\n return /^closeWhen(\\.kind)? must be/.test(spec) ? \"check must be an object with a kind: url, issue, git-ancestor, reply, count or number\" : spec.replace(/^closeWhen/, \"check\")\n}\n\nfunction readGoalCheck(json: string | null): GoalCheck | null {\n if (!json) return null\n try {\n const raw = JSON.parse(json)\n if (raw?.kind === \"count\") {\n const spec = readCountSpec(json)\n return spec ? { kind: \"count\", ...spec } : null\n }\n if (raw?.kind === \"number\") return readNumberCheck(raw)\n } catch {\n return null\n }\n return readCloseWhen(json)\n}\n\nexport function describeGoalCheck(check: GoalCheck): string {\n return check.kind === \"count\" ? describeCount(check) : check.kind === \"number\" ? describeNumberCheck(check) : describeCloseWhen(check)\n}\n\nfunction toGoal(r: any): GoalRecord {\n return {\n id: r.id, title: r.title, ownerAgent: r.owner_agent ?? null, state: r.state, doneWhen: r.done_when ?? null,\n check: readGoalCheck(r.check_spec), evidence: r.evidence ?? null, lastCheck: r.last_check ?? null, lastCheckAt: r.last_check_at ?? null,\n createdAt: r.created_at, updatedAt: r.updated_at, closedAt: r.closed_at ?? null,\n }\n}\n\nexport interface GoalInput extends RequestGoal {\n ownerAgent?: string | null\n doneWhen?: string | null\n check?: GoalCheck | null\n}\n\nexport class GoalStore {\n constructor(private db: Database.Database) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS goals (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n owner_agent TEXT,\n state TEXT NOT NULL DEFAULT 'active',\n done_when TEXT,\n check_spec TEXT,\n evidence TEXT,\n last_check TEXT,\n last_check_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n closed_at INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_goals_state ON goals(state);\n `)\n }\n\n get(id: string): GoalRecord | null {\n const row = this.db.prepare(\"SELECT * FROM goals WHERE id = ?\").get(id)\n return row ? toGoal(row) : null\n }\n\n /** Most recently updated first. */\n list(states: readonly GoalState[] = GOAL_STATES, limit = 200): GoalRecord[] {\n const marks = states.map(() => \"?\").join(\", \")\n return (this.db.prepare(`SELECT * FROM goals WHERE state IN (${marks}) ORDER BY updated_at DESC, rowid DESC LIMIT ?`).all(...states, limit) as any[]).map(toGoal)\n }\n\n /** The record of a goal a request names on accept: made when it is new,\n * left as it is otherwise (its title and owner are the record's). */\n ensure(goal: RequestGoal, ownerAgent: string | null, now: number): GoalRecord {\n this.db.prepare(\n \"INSERT INTO goals (id, title, owner_agent, state, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?) ON CONFLICT(id) DO NOTHING\",\n ).run(goal.id, goal.title, ownerAgent, now, now)\n return this.get(goal.id)!\n }\n\n /** Make a goal, or change an active one: only the fields given change. */\n upsert(input: GoalInput, now: number): GoalRecord {\n const had = this.get(input.id)\n if (!had) {\n this.db.prepare(\n \"INSERT INTO goals (id, title, owner_agent, state, done_when, check_spec, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?, ?, ?)\",\n ).run(input.id, input.title, input.ownerAgent ?? null, input.doneWhen ?? null, input.check ? JSON.stringify(input.check) : null, now, now)\n } else {\n this.db.prepare(\n \"UPDATE goals SET title = ?, owner_agent = ?, done_when = ?, check_spec = ?, updated_at = ? WHERE id = ?\",\n ).run(\n input.title || had.title,\n input.ownerAgent !== undefined ? input.ownerAgent : had.ownerAgent,\n input.doneWhen !== undefined ? input.doneWhen : had.doneWhen,\n input.check !== undefined ? (input.check ? JSON.stringify(input.check) : null) : (had.check ? JSON.stringify(had.check) : null),\n now, input.id,\n )\n }\n return this.get(input.id)!\n }\n\n /** Close an active goal as done or dropped. False when it was not active. */\n close(id: string, state: Exclude<GoalState, \"active\">, evidence: string | null, now: number): boolean {\n const res = this.db.prepare(\n \"UPDATE goals SET state = ?, evidence = ?, closed_at = ?, updated_at = ? WHERE id = ? AND state = 'active'\",\n ).run(state, evidence ? evidence.slice(0, GOAL_EVIDENCE_MAX) : null, now, now, id)\n return res.changes > 0\n }\n\n /** What the check saw: not a change of the goal, so updated_at stays. */\n markChecked(id: string, detail: string, now: number): void {\n this.db.prepare(\"UPDATE goals SET last_check = ?, last_check_at = ? WHERE id = ?\").run(detail.slice(0, GOAL_EVIDENCE_MAX), now, id)\n }\n\n /** Active goals with a check last run at `before` or earlier (or never). */\n dueChecks(before: number): GoalRecord[] {\n return (this.db.prepare(\n \"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\",\n ).all(before) as any[]).map(toGoal)\n }\n}\n\nexport type GoalChecker = (check: GoalCheck) => Promise<CheckResult>\n\n/** Run the check of every active goal not checked for `everyMinutes`.\n * Met closes the goal as done with the check's evidence. Returns the ids\n * closed. One goal's failure never stops the others. */\nexport async function checkGoals(store: GoalStore, check: GoalChecker, everyMinutes: number, now: number, log: (msg: string) => void = () => {}): Promise<string[]> {\n const closed: string[] = []\n for (const g of store.dueChecks(now - everyMinutes * 60_000)) {\n let res: CheckResult\n try {\n res = await check(g.check!)\n } catch (e: any) {\n res = { verdict: \"unverifiable\", detail: String(e?.message ?? e) }\n }\n store.markChecked(g.id, res.detail, now)\n if (res.verdict === \"met\" && store.close(g.id, \"done\", `check: ${res.detail}`, now)) {\n closed.push(g.id)\n log(`[goals] ${g.id} done: ${res.detail}`)\n } else if (res.verdict === \"unverifiable\") {\n log(`[goals] ${g.id}: check failed: ${res.detail}`)\n }\n }\n return closed\n}\n\n/** The goal's state for a cron prompt or a plan turn: a few lines. */\nexport function goalBrief(g: GoalRecord, counts?: { open: number; done: number } | null): string {\n const lines = [`[Goal] ${g.title} (${g.id}): ${g.state}${g.ownerAgent ? `, owner ${g.ownerAgent}` : \"\"}.`]\n if (g.doneWhen) lines.push(`Done when: ${g.doneWhen}`)\n if (g.check) lines.push(`Check: ${describeGoalCheck(g.check)}${g.lastCheck ? `; last seen: ${g.lastCheck}${g.lastCheckAt ? ` (${new Date(g.lastCheckAt).toISOString().slice(0, 16).replace(\"T\", \" \")} UTC)` : \"\"}` : \"\"}`)\n if (counts) lines.push(`Requests under it: ${counts.open} open, ${counts.done} done.`)\n return lines.join(\"\\n\")\n}\n","import type { CheckResult } from \"./index\"\nimport { forgeHeaders, type ForgeConnectors } from \"./issue\"\n\n// --- count: how many issues or pull requests a project has open (#1568) ---\n//\n// A plan step can carry a count check (\"open issues in owner/repo = 0\").\n// The plan check reads the count through the GitHub or GitLab connector,\n// marks the step done when it is at or under `max`, and keeps the last\n// count so a turn that brought it down counts as progress. One read per\n// kind: GitHub's search total, GitLab's X-Total header.\n\nexport type CountWhat = \"issues\" | \"prs\" | \"all\"\n\nexport interface CountSpec {\n provider: \"github\" | \"gitlab\"\n /** \"owner/repo\" on GitHub, \"group/project\" on GitLab. */\n project: string\n what: CountWhat\n /** Done at this count or under. */\n max: number\n}\n\n/** Reads one open count, or says why it could not. */\nexport type ForgeCounter = (provider: \"github\" | \"gitlab\", project: string, kind: \"issues\" | \"prs\") => Promise<number | { error: string }>\n\nconst TIMEOUT_MS = 10_000\nconst WHATS: readonly CountWhat[] = [\"issues\", \"prs\", \"all\"]\nconst PROJECT_RE = /^[\\w.-]+(?:\\/[\\w.-]+)+$/\n\nconst str = (v: unknown) => (typeof v === \"string\" ? v.trim() : \"\")\n\nexport function parseCountSpec(raw: Record<string, unknown>): CountSpec | string {\n const provider = str(raw.provider).toLowerCase()\n if (provider !== \"github\" && provider !== \"gitlab\") return \"count.provider must be github or gitlab\"\n const project = str(raw.project)\n const parts = project.split(\"/\")\n if (!PROJECT_RE.test(project) || parts.some((p) => p === \".\" || p === \"..\") || (provider === \"github\" && parts.length !== 2)) {\n return provider === \"github\" ? 'count.project must be \"owner/repo\"' : 'count.project must be \"group/project\"'\n }\n const what = (str(raw.what) || \"issues\").toLowerCase()\n if (!(WHATS as readonly string[]).includes(what)) return `count.what must be one of ${WHATS.join(\", \")}`\n const max = raw.max === undefined || raw.max === null || raw.max === \"\" ? 0 : Number(raw.max)\n if (!Number.isInteger(max) || max < 0) return \"count.max must be a whole number, 0 or more\"\n return { provider, project, what: what as CountWhat, max }\n}\n\n/** A stored spec read back. Null when it is not one. */\nexport function readCountSpec(json: string | null | undefined): CountSpec | null {\n if (!json) return null\n try {\n const v = JSON.parse(json)\n if (!v || typeof v !== \"object\") return null\n const spec = parseCountSpec(v)\n return typeof spec === \"string\" ? null : spec\n } catch {\n return null\n }\n}\n\nconst whatWords = (w: CountWhat) => (w === \"issues\" ? \"open issues\" : w === \"prs\" ? \"open pull requests\" : \"open issues and pull requests\")\n\nexport function describeCount(spec: CountSpec): string {\n return `${whatWords(spec.what)} in ${spec.provider} ${spec.project} ≤ ${spec.max}`\n}\n\n/** The count now, and whether it is at or under max. Never throws. */\nexport async function checkCount(spec: CountSpec, counter: ForgeCounter | undefined): Promise<CheckResult & { count?: number }> {\n if (!counter) return { verdict: \"unverifiable\", detail: `no ${spec.provider} connector on this node` }\n try {\n const kinds: Array<\"issues\" | \"prs\"> = spec.what === \"all\" ? [\"issues\", \"prs\"] : [spec.what]\n let count = 0\n for (const kind of kinds) {\n const n = await counter(spec.provider, spec.project, kind)\n if (typeof n !== \"number\") return { verdict: \"unverifiable\", detail: `${spec.project}: ${n.error}` }\n count += n\n }\n const detail = `${count} ${whatWords(spec.what)} in ${spec.project}`\n return { verdict: count <= spec.max ? \"met\" : \"not_met\", detail, count }\n } catch (e: any) {\n return { verdict: \"unverifiable\", detail: `the count check failed: ${String(e?.message ?? e).slice(0, 200)}` }\n }\n}\n\n/** The counter over the REST APIs of GitHub and GitLab. */\nexport function forgeCounter(connectors: ForgeConnectors, doFetch: typeof fetch = fetch): ForgeCounter {\n return async (provider, project, kind) => {\n let url: string\n if (provider === \"github\") {\n const c = connectors.github\n if (!c) return { error: \"no github connector on this node (channels.github or requests.checkers.github)\" }\n const q = encodeURIComponent(`repo:${project} is:open is:${kind === \"prs\" ? \"pr\" : \"issue\"}`)\n url = `${c.apiUrl.replace(/\\/$/, \"\")}/search/issues?q=${q}&per_page=1`\n } else {\n const c = connectors.gitlab\n if (!c) return { error: \"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)\" }\n url = `${c.url.replace(/\\/$/, \"\")}/api/v4/projects/${encodeURIComponent(project)}/${kind === \"prs\" ? \"merge_requests\" : \"issues\"}?state=opened&per_page=1`\n }\n let res: Response\n try {\n res = await doFetch(url, { headers: forgeHeaders(provider, connectors), signal: AbortSignal.timeout(TIMEOUT_MS) })\n } catch (e: any) {\n return { error: `could not be reached: ${String(e?.message ?? e).slice(0, 200)}` }\n }\n if (!res.ok) return { error: res.status === 404 ? \"not found (or not visible to the connector)\" : `HTTP ${res.status}` }\n if (provider === \"gitlab\") {\n const total = Number(res.headers.get(\"x-total\"))\n return Number.isInteger(total) && total >= 0 ? total : { error: \"no X-Total in the answer\" }\n }\n const body: any = await res.json().catch(() => null)\n const total = Number(body?.total_count)\n return Number.isInteger(total) && total >= 0 ? total : { error: \"no total_count in the answer\" }\n }\n}\n","import type { CheckResult } from \"@/requests/checkers\"\nimport { describePeriod, formatValue, parseNumberId } from \"./model\"\nimport type { NumberStore } from \"./store\"\n\n// --- The `number` check of a goal (#1826) ---\n//\n// {kind:\"number\", number:\"<id>\", atLeast:1000} or {…, atMost:2}: met when\n// the newest reading of the number crosses the threshold. A goal can close\n// itself on a number this way. No reading (none yet, or the newest read\n// failed) is unverifiable, never a 0.\n\nexport interface NumberCheck {\n kind: \"number\"\n number: string\n atLeast?: number\n atMost?: number\n}\n\nexport function parseNumberCheck(raw: Record<string, unknown>): NumberCheck | string {\n const id = parseNumberId(raw.number ?? raw.id)\n if (typeof id !== \"string\") return `check.number: ${id.error}`\n const has = (k: string) => raw[k] !== undefined && raw[k] !== null && raw[k] !== \"\"\n if (has(\"atLeast\") === has(\"atMost\")) return \"a number check needs one of atLeast or atMost: the threshold its reading must cross\"\n const key = has(\"atLeast\") ? \"atLeast\" : \"atMost\"\n const value = Number(raw[key])\n if (!Number.isFinite(value)) return `check.${key} must be a number`\n return { kind: \"number\", number: id, [key]: value }\n}\n\nexport function readNumberCheck(v: any): NumberCheck | null {\n if (!v || typeof v !== \"object\" || v.kind !== \"number\") return null\n const spec = parseNumberCheck(v)\n return typeof spec === \"string\" ? null : spec\n}\n\nexport function describeNumberCheck(c: NumberCheck): string {\n return c.atLeast !== undefined ? `number ${c.number} reads ≥ ${formatValue(c.atLeast)}` : `number ${c.number} reads ≤ ${formatValue(c.atMost!)}`\n}\n\n/** The newest reading against the threshold. Never throws. */\nexport function checkNumber(c: NumberCheck, store: NumberStore | undefined): CheckResult {\n if (!store) return { verdict: \"unverifiable\", detail: \"this node keeps no numbers\" }\n const n = store.get(c.number)\n if (!n) return { verdict: \"unverifiable\", detail: `no number \"${c.number}\"` }\n const latest = store.readings(c.number, 1)[0]\n if (!latest || latest.value === null) {\n return { verdict: \"unverifiable\", detail: `${c.number}: no reading${latest?.error ? ` (${latest.error})` : \"\"}` }\n }\n const met = c.atLeast !== undefined ? latest.value >= c.atLeast : latest.value <= c.atMost!\n const detail = `${n.name}: ${formatValue(latest.value, n.unit)} for ${describePeriod({ start: latest.periodStart, end: latest.periodEnd })}`\n return { verdict: met ? \"met\" : \"not_met\", detail }\n}\n","import type { RequestRecord } from \"./store\"\n\n// --- \"What did I ask today, and where did it land\" (#394, 1c C) ---\n//\n// One row per request made since 00:00 Tunis: time, first words, state,\n// owner, and where it landed. A request with nowhere it landed goes red, at\n// the top. No model: the Secretary reads it out, the Desk shows it.\n\nexport const TODAY_ZONE = \"Africa/Tunis\"\n\nexport interface Landed { kind: string; ref: string }\n\nexport interface TodayRow {\n id: string\n /** HH:MM, Tunis time. */\n time: string\n words: string\n state: string\n owner: string\n landed: Landed[]\n noHome: boolean\n}\n\n/** Epoch ms of the last 00:00 in `zone` at or before `now`. */\nexport function startOfDay(now: number, zone = TODAY_ZONE): number {\n const parts = Object.fromEntries(\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: zone, hour12: false, hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" })\n .formatToParts(new Date(now)).map((p) => [p.type, p.value]),\n )\n const elapsed = ((Number(parts.hour) % 24) * 3600 + Number(parts.minute) * 60 + Number(parts.second)) * 1000 + (now % 1000)\n return now - elapsed\n}\n\nconst clock = (ms: number, zone: string) =>\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: zone, hour12: false, hour: \"2-digit\", minute: \"2-digit\" }).format(new Date(ms))\n\n/** The first `n` words of a request, on one line. */\nexport function firstWords(text: string, n = 10): string {\n const words = text.replace(/\\s+/g, \" \").trim().split(\" \")\n return words.slice(0, n).join(\" \") + (words.length > n ? \" …\" : \"\")\n}\n\n/** Link kinds that say where the work lives: a home (#394), or an\n * approval card put to the owner. Runs, delegations and workflows do not. */\nconst LANDING_LINKS = new Set([\"issue\", \"idea\", \"approval\", \"erp\", \"card\"])\n\nexport function todayRows(\n items: Array<RequestRecord & { links?: Array<{ kind: string; ref: string }> }>,\n opts: { hasPlan?: (id: string) => boolean; zone?: string } = {},\n): TodayRow[] {\n const rows = items.map((r): TodayRow => {\n const landed: Landed[] = []\n const add = (kind: string, ref: string) => { if (!landed.some((l) => l.kind === kind && l.ref === ref)) landed.push({ kind, ref }) }\n for (const l of r.links ?? []) if (LANDING_LINKS.has(l.kind)) add(l.kind, l.ref)\n if (r.home) add(r.home.kind, r.home.link)\n if (opts.hasPlan?.(r.id)) add(\"plan\", r.id)\n if (r.evidence) add(\"evidence\", r.evidence)\n return {\n id: r.id, time: clock(r.createdAt, opts.zone ?? TODAY_ZONE), words: firstWords(r.text), state: r.state, owner: r.agentId,\n // Declined or dropped: closed on purpose, nothing was to land.\n landed, noHome: landed.length === 0 && r.state !== \"declined\" && r.state !== \"dropped\",\n }\n })\n // Red first; each group in the order asked.\n return [...rows.filter((r) => r.noHome), ...rows.filter((r) => !r.noHome)]\n}\n","import { startOfDay, TODAY_ZONE } from \"./today\"\nimport type { RequestStore } from \"./store\"\n\n// --- The daily flow rate of requests (#1542) ---\n//\n// Every request asked in a day (the owner's day, `requests.flow.timeZone`),\n// and where each one stands now:\n// asked requests made that day (candidates left out)\n// done closed as done\n// dropped declined or dropped: each carries its reason, listed beside\n// the rate so a wrong drop can be seen\n// moving in progress, or waiting on another agent\n// waiting waiting on the owner\n// stuck needs attention\n// rate (done + dropped) / asked; null on a day nothing was asked\n// resent resent once by the requests check (resend.ts), and how many\n// of those are done now\n// Read only, recomputed on every call: a request closed later moves the\n// day it was asked. No model.\n\nexport interface FlowSettings {\n timeZone: string\n days: number\n}\n\nexport const DEFAULT_FLOW: FlowSettings = { timeZone: TODAY_ZONE, days: 7 }\n\n/** Days one report may cover: closed requests age out after retentionDays. */\nexport const FLOW_DAYS_MAX = 90\n\n/** Drop reasons listed per day. */\nconst REASONS_MAX = 5\nconst REASON_WORDS = 120\n\nexport interface FlowDay {\n /** YYYY-MM-DD in the zone. */\n day: string\n /** Epoch ms of the day's 00:00 in the zone. */\n start: number\n asked: number\n done: number\n dropped: number\n moving: number\n waiting: number\n stuck: number\n rate: number | null\n /** Most frequent reasons first; `more` counts the drops not listed. */\n dropReasons: Array<{ reason: string; count: number }>\n moreReasons: number\n resent: number\n resentDone: number\n}\n\nexport interface FlowReport {\n zone: string\n /** Oldest first; the last one is today. */\n days: FlowDay[]\n today: FlowDay\n}\n\nconst dayKey = (ms: number, zone: string) =>\n new Intl.DateTimeFormat(\"en-CA\", { timeZone: zone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\" }).format(new Date(ms))\n\nfunction emptyDay(start: number, zone: string): FlowDay {\n return { day: dayKey(start, zone), start, asked: 0, done: 0, dropped: 0, moving: 0, waiting: 0, stuck: 0, rate: null, dropReasons: [], moreReasons: 0, resent: 0, resentDone: 0 }\n}\n\nexport function flowReport(store: RequestStore, opts: { days?: number; zone?: string; now?: number } = {}): FlowReport {\n const zone = opts.zone ?? DEFAULT_FLOW.timeZone\n const count = Math.min(Math.max(Math.floor(opts.days ?? DEFAULT_FLOW.days), 1), FLOW_DAYS_MAX)\n const now = opts.now ?? Date.now()\n // Walked back one 00:00 at a time: a day across a clock change is 23 or 25 h.\n const starts = [startOfDay(now, zone)]\n while (starts.length < count) starts.unshift(startOfDay(starts[0] - 1, zone))\n const days = starts.map((s) => emptyDay(s, zone))\n const reasons = days.map(() => new Map<string, number>())\n let i = 0\n for (const r of store.flowRows(starts[0])) {\n while (i + 1 < days.length && r.createdAt >= days[i + 1].start) i++\n const d = days[i]\n d.asked++\n if (r.state === \"done\") d.done++\n else if (r.state === \"declined\" || r.state === \"dropped\") {\n d.dropped++\n const why = (r.closeReason ?? \"\").replace(/\\s+/g, \" \").trim()\n const key = why.length > REASON_WORDS ? `${why.slice(0, REASON_WORDS - 1)}…` : why || \"no reason given\"\n reasons[i].set(key, (reasons[i].get(key) ?? 0) + 1)\n } else if (r.state === \"in_progress\" || r.state === \"waiting_other\") d.moving++\n else if (r.state === \"waiting_owner\") d.waiting++\n else if (r.state === \"needs_attention\") d.stuck++\n if (r.resentAt !== null) {\n d.resent++\n if (r.state === \"done\") d.resentDone++\n }\n }\n days.forEach((d, n) => {\n d.rate = d.asked ? (d.done + d.dropped) / d.asked : null\n const sorted = [...reasons[n]].sort((a, b) => b[1] - a[1])\n d.dropReasons = sorted.slice(0, REASONS_MAX).map(([reason, c]) => ({ reason, count: c }))\n d.moreReasons = sorted.slice(REASONS_MAX).reduce((sum, [, c]) => sum + c, 0)\n })\n return { zone, days, today: days[days.length - 1] }\n}\n\nconst pct = (rate: number | null) => (rate === null ? \"–\" : `${Math.round(rate * 100)}%`)\n\n/** Today's figure, then one line per day, oldest first: what the CLI\n * prints and the agentx_request tool answers. */\nexport function describeFlow(f: FlowReport): string {\n const t = f.today\n const lines = [\n `Today (${t.day}, ${f.zone}): ${t.asked ? `${t.done + t.dropped} of ${t.asked} closed, ${pct(t.rate)}` : \"nothing asked yet\"}.`,\n ` ${t.done} done, ${t.dropped} dropped, ${t.moving} moving, ${t.waiting} waiting on the owner, ${t.stuck} stuck.` +\n (t.resent ? ` ${t.resent} resent once on its own, ${t.resentDone} of them done.` : \"\"),\n ]\n if (t.dropReasons.length) {\n lines.push(\" Dropped because:\")\n for (const r of t.dropReasons) lines.push(` ${r.count} × ${r.reason}`)\n if (t.moreReasons) lines.push(` ${t.moreReasons} more`)\n }\n if (f.days.length > 1) {\n lines.push(\"\", \"Day asked done dropped moving waiting stuck rate\")\n for (const d of f.days) {\n const cells = [d.asked, d.done, d.dropped, d.moving, d.waiting, d.stuck].map(String)\n lines.push(`${d.day} ${cells[0].padStart(5)} ${cells[1].padStart(4)} ${cells[2].padStart(7)} ${cells[3].padStart(6)} ${cells[4].padStart(7)} ${cells[5].padStart(5)} ${pct(d.rate).padStart(4)}`)\n }\n }\n return lines.join(\"\\n\")\n}\n"],"mappings":"mHACAA,ICAAC,IAwBA,IAAMC,EAAa,IACbC,EAA8B,CAAC,SAAU,MAAO,KAAK,EACrDC,EAAa,0BAEbC,EAAOC,GAAgB,OAAOA,GAAM,SAAWA,EAAE,KAAK,EAAI,GAEzD,SAASC,EAAeC,EAAkD,CAC/E,IAAMC,EAAWJ,EAAIG,EAAI,QAAQ,EAAE,YAAY,EAC/C,GAAIC,IAAa,UAAYA,IAAa,SAAU,MAAO,0CAC3D,IAAMC,EAAUL,EAAIG,EAAI,OAAO,EACzBG,EAAQD,EAAQ,MAAM,GAAG,EAC/B,GAAI,CAACN,EAAW,KAAKM,CAAO,GAAKC,EAAM,KAAMC,GAAMA,IAAM,KAAOA,IAAM,IAAI,GAAMH,IAAa,UAAYE,EAAM,SAAW,EACxH,OAAOF,IAAa,SAAW,qCAAuC,wCAExE,IAAMI,GAAQR,EAAIG,EAAI,IAAI,GAAK,UAAU,YAAY,EACrD,GAAI,CAAEL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AAQA,EAAE,QAASA,EAAE,KAAK,EAAE,IAAI,MAAM,EACnFc,EAAM,KAAK,GAAGd,EAAE,QAAQe,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAML,EAAIV,EAAE,IAAI,EAAE,SAAS,CAAC,GAAG,GAG3M,OAAOc,EAAM,KAAK;AAAA,CAAI,CACxB","names":["init_checkers","init_issue","TIMEOUT_MS","WHATS","PROJECT_RE","str","v","parseCountSpec","raw","provider","project","parts","p","what","max","readCountSpec","json","spec","whatWords","w","describeCount","checkCount","counter","kinds","count","kind","n","detail","e","forgeCounter","connectors","doFetch","url","c","q","res","forgeHeaders","total","body","init_model","parseNumberCheck","raw","id","parseNumberId","has","k","key","value","readNumberCheck","v","spec","describeNumberCheck","c","formatValue","checkNumber","store","n","latest","met","detail","describePeriod","GOAL_STATES","DONE_WHEN_MAX","GOAL_EVIDENCE_MAX","parseGoalCheck","v","settings","DEFAULT_CHECKER_SETTINGS","now","spec","parseCountSpec","parseNumberCheck","parseCloseWhen","readGoalCheck","json","raw","readCountSpec","readNumberCheck","readCloseWhen","describeGoalCheck","check","describeCount","describeNumberCheck","describeCloseWhen","toGoal","r","GoalStore","db","id","row","states","limit","marks","goal","ownerAgent","input","had","state","evidence","detail","before","checkGoals","store","everyMinutes","log","closed","g","res","e","goalBrief","counts","lines","TODAY_ZONE","startOfDay","now","zone","parts","p","elapsed","clock","ms","firstWords","text","n","words","LANDING_LINKS","todayRows","items","opts","rows","r","landed","add","kind","ref","l","DEFAULT_FLOW","TODAY_ZONE","FLOW_DAYS_MAX","REASONS_MAX","REASON_WORDS","dayKey","ms","zone","emptyDay","start","flowReport","store","opts","count","now","starts","startOfDay","days","s","reasons","i","r","d","why","key","n","sorted","a","b","reason","c","sum","pct","rate","describeFlow","f","lines","cells"]}
@@ -1,4 +1,4 @@
1
- import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{sc as tt,tc as nt}from"./chunk-4A6UVU2X.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
1
+ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Ac as tt,Bc as nt}from"./chunk-PZ2F6J2E.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function Ot(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
114
- //# sourceMappingURL=chunk-BLKXK27S.js.map
114
+ //# sourceMappingURL=chunk-64IVC2G6.js.map
@@ -1,4 +1,4 @@
1
- import{e as g}from"./chunk-5SQRJUAK.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-2MAKXLK2.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-TO6T6AQY.js.map
17
+ //# sourceMappingURL=chunk-AOPNASCE.js.map
@@ -0,0 +1,13 @@
1
+ import{c as A,d as q,f as F,g as P,h as B}from"./chunk-4NZ4T3TQ.js";import{a as y,b as oe}from"./chunk-7I7IEX4S.js";import{existsSync as fe,linkSync as he,mkdirSync as ee,readdirSync as we,readFileSync as ye,renameSync as ke,unlinkSync as me,writeFileSync as te}from"fs";import{resolve as re}from"path";oe();import{appendFileSync as se,existsSync as ae,mkdirSync as ce,readFileSync as O,writeFileSync as W}from"fs";import{resolve as v}from"path";var K=500,M=200,I=e=>v(e,".agentx","approvals"),j=e=>v(I(e),"_answered.jsonl"),ue=e=>v(I(e),"_answered.since"),C=e=>e&&e.length>M?e.slice(0,M-1)+"\u2026":e;function U(e,t){try{de(e);let n={...t,title:C(t.title)??""};t.choice&&(n.choice=C(t.choice)),t.text?n.text=C(t.text):delete n.text;let r=j(e);se(r,JSON.stringify(n)+`
2
+ `);let i=O(r,"utf-8").split(`
3
+ `).filter(Boolean);i.length>K&&W(r,i.slice(-K).join(`
4
+ `)+`
5
+ `)}catch(n){y.warn(`[approvals] answered list not written for ${t.key}: ${n?.message??n}`)}}function de(e){let t=ue(e);try{let r=O(t,"utf-8").trim();if(r)return r}catch{}let n=new Date().toISOString();try{ce(I(e),{recursive:!0}),W(t,n+`
6
+ `)}catch(r){y.warn(`[approvals] answered start not written: ${r?.message??r}`)}return n}function Te(e,t=50){let n=j(e);if(!ae(n))return[];let r=[],i;try{i=O(n,"utf-8").split(`
7
+ `).filter(Boolean)}catch(o){return y.warn(`[approvals] answered list not read: ${o?.message??o}`),[]}for(let o=i.length-1;o>=0&&r.length<t;o--)try{let s=JSON.parse(i[o]);s&&typeof s.key=="string"&&typeof s.at=="string"&&r.push(s)}catch{}return r}function Y(e,t){let n=[`This card was about the tracked number \`${e.numberId}\`, which missed its target twice in a row.`];return t.status==="decided"&&t.verdict==="yes"?(n.push("The question above gives both readings and the target. Find out why it misses, and change what you do, or propose a new target or source if those are wrong.","Say in one short message what you changed and when the next reading will show it."),e.reviewer&&e.reviewer!==t.raised_by&&n.push(`${e.reviewer} reviews your follow-up.`)):n.push("Change nothing for now. No new card comes until the number meets its target and then misses twice again."),n}function Ae(e){let t=e.origin?.kind==="number"?e.origin:void 0;if(!t?.reviewer||t.reviewer===e.raised_by||e.status!=="decided"||e.verdict!=="yes")return null;let n=[`[Number review] The operator said YES on "${e.title}" (${e.id}): ${e.raised_by} looks into why the tracked number \`${t.numberId}\` missed its target twice.`,`You are the reviewer for numbers. Check that ${e.raised_by} says what it changed, and look at the next reading of \`${t.numberId}\`.`];return e.note&&n.push(`Operator note: ${e.note}`),n.push("Do not change the number yourself; ask its owner."),{agentId:t.reviewer,text:n.join(`
8
+ `)}}function D(e){return e?.kind==="retro"||e?.kind==="retro-check"}var V={keep:"Keep it",loosen:"Loosen it",remove:"Remove it"};function J(e,t,n){let r=`guard rule \`${e.ruleId}\` in \`${e.file}\``,i=[`This was a monthly review of ${r}, added by the retro on run ${e.taskId}. It fires often on runs that went well.`];return!(t.status==="decided"&&t.verdict==="yes")||t.choice===V.keep||!t.choice?(i.push("Change nothing: the rule stays as it is."),i):(i.push(t.choice===V.remove?`The operator chose to remove it. Delete ${r} as a pull request.`:`The operator chose to loosen it. Narrow ${r} (a tighter match, or \`applies_to\`) so it stops firing on good work, keep its \`retro:${e.taskId}\` tag, and open it as a pull request.`),t.choice_suggested&&i.push(G),n&&i.push("The operator's note:",n),i.push("Do not change the live policy directly: the operator reviews the pull request first."),i)}var G="(The operator gave a plain yes, taken as the suggested option.)";function E(e){return e.status==="decided"&&e.verdict==="yes"&&!!e.choice&&e.choice!==N}function z(e,t,n){let r=[`This was a retro card about run ${e.taskId} (\`agentx trace show ${e.taskId}\`).`];if(!E(t))return r.push("Change nothing. Do not propose these fixes again on your own."),r;r.push(`The operator picked this fix: ${t.choice}`),t.choice_suggested&&r.push(G);let i=e.specs?.[(t.choices??[]).indexOf(t.choice)];return i&&r.push("Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):",i),n&&r.push("The operator's note on the fix:",n),r.push("Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.","Do not apply it to a live system directly. Tag what you add with `retro:"+e.taskId+"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list."),r}var N="None of these";function H(e,t){let n=e.list?` in the "${e.list}" list`:"",r=[`This card came from the operator's reminder "${e.title}"${n} (id ${e.id}).`];return r.push(t?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),r}var u={title:120,ask:300,answers:3},R=["resurface","bring-back","weekly","cleanup"],k={perDay:5,resurface:3},le=[/\bhttps?:\/\/\S+/gi,/(?:[\w.-]+\/)*[\w.-]+[#!]\d+\b/g,/[#!]\d+\b/g,/\b[0-9A-HJKMNP-TV-Z]{26}\b/gi,/\b(?:req|dlg|snd)-[\w-]+/gi,/\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,}\b/gi];function ge(e){return le.reduce((t,n)=>t.replace(n," "),e)}function X(e){let t=ge(e);return t===e||t.split(/\s+/).filter(r=>/\p{L}/u.test(r)).length>=2?null:`title is only a reference ("${e.trim()}"); say what it is in plain words, and put the link in the body or source`}function Q(e){let t=typeof e.title=="string"?e.title:"",n=typeof e.ask=="string"?e.ask:"";if(!t.trim())return"title is missing: say what it is in plain words";if(t.length>u.title)return`title is longer than ${u.title} characters`;let r=X(t);return r||(n.trim()?n.length>u.ask?`ask is longer than ${u.ask} characters`:(n.match(/\?/g)??[]).length>1?"ask holds more than one question: one card asks one thing":(e.choices?.length??0)>u.answers?`more than ${u.answers} choices`:null:"ask is missing: one card asks one thing")}function Fe(e,t){if(e.length>u.title)return`title is longer than ${u.title} characters`;let n=X(e);return n||(t.length>u.ask?`message is longer than ${u.ask} characters`:null)}function Pe(e,t){let n=t?.trim().replace(/\s+/g," ")||"nothing, FYI";return`${e}
9
+ To do: ${n}`}function pe(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function Z(e,t,n){let r=pe(n),i=e.filter(o=>o.followup&&Date.parse(o.created_at)>=r);return i.length>=k.perDay?`the follow-up screen budget is used up today (${k.perDay} cards): raise it again tomorrow`:t==="resurface"&&i.filter(o=>o.followup==="resurface").length>=k.resurface?`${k.resurface} resurface cards were already raised today: raise it again tomorrow`:null}function Be(e,t){let n=e.title?.trim();return e.origin?.kind==="request"?[`[screen gate] Request ${e.id}${n?` ("${n}")`:""} was not shown to the owner: ${t}.`,`It is still on his list. Say what it is: agentx_request {action:"describe", id:"${e.id}", headline:"<a few plain words>", need:"<what you need from him>"}.`].join(" "):[`[screen gate] Your card ${e.id}${n?` ("${n}")`:""} was not shown to the owner: ${t}.`,"It is still in his inbox, unchanged. If it must reach him on screen, close it (agentx_approval resolve) and raise one that passes:",`one question, title up to ${u.title} characters, ask up to ${u.ask}, at most ${u.answers} choices.`].join(" ")}var ne=["discard","keep","pause"];function T(e){return e==="approve"?"keep":ne.includes(e)?e:null}var g={title:120,ask:300,recommend:300,source:500,note:500,resolution:300,pendingPerAgent:25},xe={defaultExpiryDays:3,maxExpiryDays:30};function x(e){return re(e,".agentx","approvals")}var be=/^[a-z0-9][a-z0-9-]{0,80}$/;function ie(e){return be.test(e)}function L(e,t){if(!ie(t))throw new Error(`invalid card id: ${t}`);return re(x(e),`${t}.json`)}function _e(e,t){let n=new Date(e).toISOString().slice(0,10),r=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${r||"card"}-${Math.random().toString(36).slice(2,6).padEnd(4,"0")}`}function b(e,t){ee(x(e),{recursive:!0});let n=L(e,t.id),r=`${n}.${process.pid}.tmp`;te(r,JSON.stringify(t,null,2)+`
10
+ `),ke(r,n)}function $e(e,t){ee(x(e),{recursive:!0});for(let n=1;;n++){let r=n===1?t:{...t,id:`${t.id}-${n}`},i=L(e,r.id),o=`${i}.${process.pid}.tmp`;te(o,JSON.stringify(r,null,2)+`
11
+ `);try{return he(o,i),r}catch(s){if(s.code!=="EEXIST")throw s}finally{me(o)}}}function _(e,t){if(!ie(t))return null;try{let n=JSON.parse(ye(L(e,t),"utf-8")),r=n.if_silent==="approve"||n.outcome==="approve";return{...n,if_silent:T(n.if_silent)??"keep",...n.outcome?{outcome:T(n.outcome)??"keep"}:{},...r?{if_silent_asked:"approve"}:{}}}catch{return null}}function m(e,t){let n=x(e);if(!fe(n))return[];let r=[];for(let i of we(n).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=_(e,i.slice(0,-5));o&&(!t||o.status===t)&&r.push(o)}return r}function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function Se(e,t,n){let r=t+n.maxExpiryDays*864e5,i,o=a(e);if(!o)i=t+n.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=t+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=t?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,r)).toISOString()}}function Ce(e,t={}){let n=t.now??Date.now(),r=t.settings??xe,i=a(e.title),o=a(e.ask),s=a(e.recommend),d=a(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!d)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>g.title)return{ok:!1,error:`title is longer than ${g.title} characters`};if(o.length>g.ask)return{ok:!1,error:`ask is longer than ${g.ask} characters`};if(s.length>g.recommend)return{ok:!1,error:`recommend is longer than ${g.recommend} characters`};let l=a(e.if_silent).toLowerCase(),p=T(l);if(!p)return{ok:!1,error:`if_silent must be one of ${ne.join(", ")}`};let c=Se(e.expires,n,r);if(!c.ok)return c;let h=a(e.source);if(h.length>g.source)return{ok:!1,error:`source is longer than ${g.source} characters`};if(h&&/^[a-z][a-z0-9+.-]*:/i.test(h)&&!/^https?:\/\//i.test(h))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let $=A(e);if(!$.ok)return $;let w=a(e.followup).toLowerCase();if(w&&!R.includes(w))return{ok:!1,error:`followup must be one of ${R.join(", ")}`};let S,f=e.reply;return f&&typeof f=="object"&&a(f.channel)&&a(f.chatId)&&(S={channel:a(f.channel),chatId:a(f.chatId),...a(f.accountId)?{accountId:a(f.accountId)}:{}}),{ok:!0,card:{id:_e(n,i),title:i,ask:o,recommend:s,if_silent:p,...l==="approve"?{if_silent_asked:"approve"}:{},expires:c.at,...h?{source:h}:{},raised_by:d,...t.node?{node:t.node}:{},created_at:new Date(n).toISOString(),...S?{reply:S}:{},...$.value,...t.origin?{origin:t.origin}:{},...w?{followup:w}:{},...t.popupOnly?{popup_only:!0}:{},status:"pending"}}}function Oe(e,t){if(!(!t.source||t.origin))return e.find(n=>!n.origin&&n.source===t.source&&n.raised_by===t.raised_by&&(n.node??"")===(t.node??""))}function Je(e,t,n={}){let r=Ce(t,n);if(!r.ok)return r;let i=Q(r.card);if(i)return{ok:!1,error:i};if(r.card.followup){let c=Z(m(e),r.card.followup,n.now??Date.now());if(c)return{ok:!1,error:c}}let o=m(e,"pending"),s=Oe(o,r.card);if(s)return{ok:!1,error:`a card from you on this source is still pending: ${s.id}. Wait for its answer, or resolve it first and then raise the new one.`};let d=c=>D(c.origin),l=d(r.card),p=o.filter(c=>c.raised_by===r.card.raised_by&&d(c)===l).length;if(p>=g.pendingPerAgent){let c=l?"retro cards":"cards";return{ok:!1,error:`${r.card.raised_by} already has ${p} ${c} waiting; wait for decisions before raising more`}}return{ok:!0,card:$e(e,r.card)}}var ve="this card takes a yes only in the popup on the home machine; here it can only be answered no";function Ge(e,t,n,r={}){let i=_(e,t);if(!i)return{ok:!1,error:`no card "${t}"`};if(i.status!=="pending")return{ok:!1,error:`card "${t}" is already ${i.status}`};if(i.popup_only&&n==="yes"&&!r.popup)return{ok:!1,error:ve};let o=F(i,n,r);if(!o.ok)return o;let s=n==="yes"&&P(o.choice)&&!D(i.origin),d=s?"no":n,l=a(r.note).slice(0,g.note),p={...i,status:"decided",verdict:d,decided_by:r.by??"operator",...r.popup?{decided_from:"popup"}:{},decided_at:new Date(r.now??Date.now()).toISOString(),...l?{note:l}:{},...o.choice?{choice:o.choice}:{},...o.suggested?{choice_suggested:!0}:{},...o.text&&!s?{text:o.text}:{}};return b(e,p),{ok:!0,card:p}}var Ie=new Set([void 0,"reminder"]);function ze(e,t,n){let r=_(e,t);if(!r)return{ok:!1,status:404,error:`no card "${t}"`};if(r.raised_by!==n.by||(r.node??"")!==(n.node??"")){let d=r.node?`${r.raised_by} on node "${r.node}"`:r.raised_by,l=r.node?"it closes it through its own node's daemon":"it closes it from one of its running turns";return{ok:!1,status:403,error:`card "${t}" was raised by another agent (${d}): only that agent can close it (${l}), or the operator answers it in Approvals`}}if(!Ie.has(r.origin?.kind))return{ok:!1,status:409,error:`card "${t}" is answered by the operator only`};if(r.status!=="pending")return{ok:!1,status:409,error:`card "${t}" is already ${r.status}`};let i=a(n.reason);if(!i)return{ok:!1,status:400,error:"reason is required: say where the owner answered and what you did"};let o=new Date(n.now??Date.now()).toISOString(),s={...r,status:"resolved",decided_by:n.by,decided_at:o,resolution:i.slice(0,g.resolution),agent_notified_at:o};return b(e,s),U(e,{key:`card:${t}`,kind:"card",title:r.title,raised_by:r.raised_by,answer:"closed",text:s.resolution,by:n.node?`${n.by} on ${n.node}`:n.by,at:o}),{ok:!0,card:s}}function He(e,t=Date.now()){let n=[];for(let r of m(e,"pending")){if(Date.parse(r.expires)>t)continue;let i={...r,status:"expired",outcome:r.if_silent,decided_by:"expiry",decided_at:new Date(t).toISOString()};b(e,i),n.push(i)}return n}function Xe(e){return m(e).filter(t=>t.status!=="pending"&&!t.agent_notified_at)}function Qe(e,t,n=Date.now()){let r=_(e,t);!r||r.agent_notified_at||b(e,{...r,agent_notified_at:new Date(n).toISOString()})}var De="A no does not by itself undo anything you already did. If you already carried this out (for example because the owner approved it in chat), do not reverse it: ask the requester one clear question first.";function Ze(e){let t=e.origin?.kind==="retro"?e.origin:void 0,n=e.status==="decided"?e.verdict==="yes"?t&&!E(e)?`The operator picked "${N}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,r=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,n],i=e.origin?.kind==="retro-check"?e.origin:void 0;if(e.status==="decided"&&e.verdict==="yes"&&!t&&!i&&r.push(...B(e)),e.status==="decided"&&e.verdict==="no"&&e.choice&&!t&&!i&&r.push(`Chosen: ${e.choice} (this option means no; do not send or do it)`),e.note&&r.push(`Operator note: ${e.note}`),e.status==="decided"&&e.verdict==="no"&&!t&&!i&&r.push(De),e.source&&r.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&r.push(...H(e.origin,e.status==="decided"&&e.verdict==="yes")),e.origin?.kind==="number"&&r.push(...Y(e.origin,e)),t||i){let o=l=>l.replace(/\s+/g," ").trim(),s=q(e.draft,e.choice),d=e.text&&o(e.text)!==o(s)?e.text:void 0;r.push(...t?z(t,e,d):J(i,e,d))}return e.reply&&r.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&r.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),r.push("Act on this result now. Do not raise the same card again."),r.join(`
12
+ `)}export{U as a,de as b,Te as c,Ae as d,D as e,V as f,E as g,N as h,X as i,Q as j,Fe as k,Pe as l,Be as m,ne as n,g as o,x as p,ie as q,b as r,_ as s,m as t,Je as u,Ge as v,ze as w,He as x,Xe as y,Qe as z,Ze as A};
13
+ //# sourceMappingURL=chunk-BXK5S2KK.js.map