agentix-cli 0.166.0 → 0.168.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 (184) hide show
  1. package/README.md +2 -2
  2. package/dist/{App-UOZT7MWS.js → App-GK5F6QMB.js} +2 -2
  3. package/dist/{ChatApp-N7REHHH3.js → ChatApp-4HHJB4HM.js} +2 -2
  4. package/dist/absorb-eval-PO7TUGT2.js +2 -0
  5. package/dist/agent-6WKET7JZ.js +2 -0
  6. package/dist/{board-dashboard-4C77NLY5.js → board-dashboard-ESAX2ZFV.js} +436 -403
  7. package/dist/board-dashboard-ESAX2ZFV.js.map +1 -0
  8. package/dist/{chunk-NHWYEIET.js → chunk-5PEXL5LD.js} +6 -6
  9. package/dist/{chunk-L7RPH3T7.js → chunk-5QI7XFTA.js} +2 -2
  10. package/dist/{chunk-TCC56PYX.js → chunk-BAXGL6TY.js} +2 -2
  11. package/dist/{chunk-JMZNI257.js → chunk-BRQKV4FC.js} +2 -2
  12. package/dist/{chunk-B7QHC7N4.js → chunk-CBXPIKPJ.js} +2 -2
  13. package/dist/{chunk-33KKV3YU.js → chunk-COMJ7R5T.js} +2 -2
  14. package/dist/{chunk-6QLRRSKU.js → chunk-DCIYOPJF.js} +15 -15
  15. package/dist/chunk-DCIYOPJF.js.map +1 -0
  16. package/dist/{chunk-7FH2FEFA.js → chunk-DCJHCUEQ.js} +2 -2
  17. package/dist/{chunk-QLJ3OMPL.js → chunk-E67Z6OYF.js} +2 -2
  18. package/dist/chunk-E7Y4G3FK.js +185 -0
  19. package/dist/chunk-E7Y4G3FK.js.map +1 -0
  20. package/dist/{chunk-XQ2EFLQW.js → chunk-EEM433JK.js} +28 -28
  21. package/dist/{chunk-XQ2EFLQW.js.map → chunk-EEM433JK.js.map} +1 -1
  22. package/dist/chunk-FEA3XMVU.js +580 -0
  23. package/dist/chunk-FEA3XMVU.js.map +1 -0
  24. package/dist/chunk-GZIHLADX.js +4 -0
  25. package/dist/chunk-GZIHLADX.js.map +1 -0
  26. package/dist/{chunk-G3T73GGF.js → chunk-HFSPH5WM.js} +2 -2
  27. package/dist/{chunk-XJYGMCAV.js → chunk-HRN4WKSJ.js} +363 -304
  28. package/dist/chunk-HRN4WKSJ.js.map +1 -0
  29. package/dist/{chunk-IJZNM5PS.js → chunk-JKMFMW3E.js} +2 -2
  30. package/dist/chunk-KMPUUH5R.js +137 -0
  31. package/dist/chunk-KMPUUH5R.js.map +1 -0
  32. package/dist/{chunk-YKHK47G5.js → chunk-KWY5IBII.js} +2 -2
  33. package/dist/{chunk-TM2TPQKH.js → chunk-LE3BXIUF.js} +2 -2
  34. package/dist/chunk-LXW7H4D4.js +2 -0
  35. package/dist/chunk-LXW7H4D4.js.map +1 -0
  36. package/dist/chunk-NKCS6EZ7.js +92 -0
  37. package/dist/chunk-NKCS6EZ7.js.map +1 -0
  38. package/dist/{chunk-BQXKTQCX.js → chunk-PIJ6ECBC.js} +2 -2
  39. package/dist/chunk-RX5O5637.js +7 -0
  40. package/dist/chunk-RX5O5637.js.map +1 -0
  41. package/dist/{chunk-LQTTLXZY.js → chunk-S34KFBMJ.js} +3 -3
  42. package/dist/{chunk-XML72AUF.js → chunk-TVGVQABC.js} +2 -2
  43. package/dist/{chunk-7O43PB6O.js → chunk-U4PICSLC.js} +2 -2
  44. package/dist/{chunk-AFLZHY5Y.js → chunk-U5SJLLXH.js} +2 -2
  45. package/dist/{chunk-LM3K7U6H.js → chunk-UF5TWOKL.js} +15 -15
  46. package/dist/chunk-UF5TWOKL.js.map +1 -0
  47. package/dist/chunk-UKKOBMOP.js +8 -0
  48. package/dist/chunk-UKKOBMOP.js.map +1 -0
  49. package/dist/{chunk-BNOGNRAM.js → chunk-VD2P4GWU.js} +2 -2
  50. package/dist/{chunk-64POGFQZ.js → chunk-YQM6VR6U.js} +2 -2
  51. package/dist/{chunk-QGKNDGH5.js → chunk-Z6ZR2ELO.js} +2 -2
  52. package/dist/{chunk-SXKC2LH7.js → chunk-ZTIOHZIL.js} +2 -2
  53. package/dist/cli.js +1 -1
  54. package/dist/client-DOIYODET.js +2 -0
  55. package/dist/{compaction-VN3M5YGZ.js → compaction-26OHHULF.js} +3 -3
  56. package/dist/config-3UBJRE5R.js +2 -0
  57. package/dist/config-mutate-ZRPDYJKN.js +2 -0
  58. package/dist/config-mutator-B5MR3V4B.js +2 -0
  59. package/dist/{context-planner-2XBAPQ3S.js → context-planner-CVCRW5TV.js} +2 -2
  60. package/dist/{contributions-MUCJKT73.js → contributions-2CJFYRZ7.js} +2 -2
  61. package/dist/{doctor-2N2MX5YP.js → doctor-OQZMDL5S.js} +2 -2
  62. package/dist/{follow-up-tool-W64LMQQN.js → follow-up-tool-PQUPXQQT.js} +2 -2
  63. package/dist/{grants-YGA654NI.js → grants-4O2VF2YX.js} +2 -2
  64. package/dist/heal-ZS56MC4A.js +2 -0
  65. package/dist/hub-LOW7KS5N.js +2 -0
  66. package/dist/index.d.ts +563 -3
  67. package/dist/index.js +1 -1
  68. package/dist/index.js.map +1 -1
  69. package/dist/memory-extract-NLVLQE7V.js +2 -0
  70. package/dist/{program-6YMRDLHO.js → program-7W2LJKDN.js} +298 -273
  71. package/dist/program-7W2LJKDN.js.map +1 -0
  72. package/dist/{promote-OUSVJZ64.js → promote-ZWQAL3RE.js} +2 -2
  73. package/dist/{providers-VVT2OBXA.js → providers-F5GDJSYD.js} +2 -2
  74. package/dist/push-bridge-NR7SLHGX.js +1 -1
  75. package/dist/query-N4EJ24LW.js +2 -0
  76. package/dist/{query-settings-2TNLXEL5.js → query-settings-RZV5ELLC.js} +2 -2
  77. package/dist/registry-EBYOZK3P.js +2 -0
  78. package/dist/{request-planner-7HEHLPA3.js → request-planner-KCG6QB6M.js} +2 -2
  79. package/dist/{review-candidates-NJNMSOCX.js → review-candidates-3GHWVJQ3.js} +2 -2
  80. package/dist/routing-XULOU6BI.js +2 -0
  81. package/dist/schedule-tool-ALZXDGGC.js +2 -0
  82. package/dist/scheduler-SCVCNKJC.js +2 -0
  83. package/dist/{seat-CAYDECW2.js → seat-PD7W3KAN.js} +2 -2
  84. package/dist/{select-QUVE6RN2.js → select-Z3YXBGUP.js} +2 -2
  85. package/dist/{set-enabled-BWJN4IVG.js → set-enabled-NJYJWDWH.js} +2 -2
  86. package/dist/sprint-tool-OLHZZAK3.js +7 -0
  87. package/dist/sprint-tool-OLHZZAK3.js.map +1 -0
  88. package/dist/tool-7IKZO33P.js +4 -0
  89. package/dist/tool-7IKZO33P.js.map +1 -0
  90. package/dist/{tool-FZ4UXMON.js → tool-EVQBMGJV.js} +2 -2
  91. package/dist/{tool-UC7OZWIB.js → tool-XH5QN6JM.js} +2 -2
  92. package/dist/wiki-BPOTYAQV.js +2 -0
  93. package/dist/wiki-enrich-JCNGRYQZ.js +2 -0
  94. package/package.json +1 -1
  95. package/dist/absorb-eval-MT3ZDYBM.js +0 -2
  96. package/dist/agent-SUAQ7EBM.js +0 -2
  97. package/dist/board-dashboard-4C77NLY5.js.map +0 -1
  98. package/dist/chunk-2QNT5JDS.js +0 -4
  99. package/dist/chunk-2QNT5JDS.js.map +0 -1
  100. package/dist/chunk-6QLRRSKU.js.map +0 -1
  101. package/dist/chunk-7UIK4S6T.js +0 -128
  102. package/dist/chunk-7UIK4S6T.js.map +0 -1
  103. package/dist/chunk-A2D3PNDA.js +0 -578
  104. package/dist/chunk-A2D3PNDA.js.map +0 -1
  105. package/dist/chunk-AE3U4GR6.js +0 -181
  106. package/dist/chunk-AE3U4GR6.js.map +0 -1
  107. package/dist/chunk-APPTSTL5.js +0 -2
  108. package/dist/chunk-APPTSTL5.js.map +0 -1
  109. package/dist/chunk-B6GVATMI.js +0 -92
  110. package/dist/chunk-B6GVATMI.js.map +0 -1
  111. package/dist/chunk-LM3K7U6H.js.map +0 -1
  112. package/dist/chunk-XJYGMCAV.js.map +0 -1
  113. package/dist/chunk-YQ25AGX6.js +0 -8
  114. package/dist/chunk-YQ25AGX6.js.map +0 -1
  115. package/dist/client-6ZHYSQU6.js +0 -2
  116. package/dist/config-WCEFYQL4.js +0 -2
  117. package/dist/config-mutate-LW366SKL.js +0 -2
  118. package/dist/config-mutator-NRHZ2XH3.js +0 -2
  119. package/dist/heal-KCM6JYUK.js +0 -2
  120. package/dist/hub-4ODFNGHL.js +0 -2
  121. package/dist/memory-extract-4JFORU2K.js +0 -2
  122. package/dist/program-6YMRDLHO.js.map +0 -1
  123. package/dist/query-QVK5EN3P.js +0 -2
  124. package/dist/registry-BYIWNEFL.js +0 -2
  125. package/dist/routing-HCSXNUOY.js +0 -2
  126. package/dist/schedule-tool-LJYBLCLV.js +0 -2
  127. package/dist/scheduler-74MXJLQS.js +0 -2
  128. package/dist/wiki-KNSPJT2O.js +0 -2
  129. package/dist/wiki-enrich-RVRTAQQF.js +0 -2
  130. /package/dist/{App-UOZT7MWS.js.map → App-GK5F6QMB.js.map} +0 -0
  131. /package/dist/{ChatApp-N7REHHH3.js.map → ChatApp-4HHJB4HM.js.map} +0 -0
  132. /package/dist/{absorb-eval-MT3ZDYBM.js.map → absorb-eval-PO7TUGT2.js.map} +0 -0
  133. /package/dist/{agent-SUAQ7EBM.js.map → agent-6WKET7JZ.js.map} +0 -0
  134. /package/dist/{chunk-NHWYEIET.js.map → chunk-5PEXL5LD.js.map} +0 -0
  135. /package/dist/{chunk-L7RPH3T7.js.map → chunk-5QI7XFTA.js.map} +0 -0
  136. /package/dist/{chunk-TCC56PYX.js.map → chunk-BAXGL6TY.js.map} +0 -0
  137. /package/dist/{chunk-JMZNI257.js.map → chunk-BRQKV4FC.js.map} +0 -0
  138. /package/dist/{chunk-B7QHC7N4.js.map → chunk-CBXPIKPJ.js.map} +0 -0
  139. /package/dist/{chunk-33KKV3YU.js.map → chunk-COMJ7R5T.js.map} +0 -0
  140. /package/dist/{chunk-7FH2FEFA.js.map → chunk-DCJHCUEQ.js.map} +0 -0
  141. /package/dist/{chunk-QLJ3OMPL.js.map → chunk-E67Z6OYF.js.map} +0 -0
  142. /package/dist/{chunk-G3T73GGF.js.map → chunk-HFSPH5WM.js.map} +0 -0
  143. /package/dist/{chunk-IJZNM5PS.js.map → chunk-JKMFMW3E.js.map} +0 -0
  144. /package/dist/{chunk-YKHK47G5.js.map → chunk-KWY5IBII.js.map} +0 -0
  145. /package/dist/{chunk-TM2TPQKH.js.map → chunk-LE3BXIUF.js.map} +0 -0
  146. /package/dist/{chunk-BQXKTQCX.js.map → chunk-PIJ6ECBC.js.map} +0 -0
  147. /package/dist/{chunk-LQTTLXZY.js.map → chunk-S34KFBMJ.js.map} +0 -0
  148. /package/dist/{chunk-XML72AUF.js.map → chunk-TVGVQABC.js.map} +0 -0
  149. /package/dist/{chunk-7O43PB6O.js.map → chunk-U4PICSLC.js.map} +0 -0
  150. /package/dist/{chunk-AFLZHY5Y.js.map → chunk-U5SJLLXH.js.map} +0 -0
  151. /package/dist/{chunk-BNOGNRAM.js.map → chunk-VD2P4GWU.js.map} +0 -0
  152. /package/dist/{chunk-64POGFQZ.js.map → chunk-YQM6VR6U.js.map} +0 -0
  153. /package/dist/{chunk-QGKNDGH5.js.map → chunk-Z6ZR2ELO.js.map} +0 -0
  154. /package/dist/{chunk-SXKC2LH7.js.map → chunk-ZTIOHZIL.js.map} +0 -0
  155. /package/dist/{client-6ZHYSQU6.js.map → client-DOIYODET.js.map} +0 -0
  156. /package/dist/{compaction-VN3M5YGZ.js.map → compaction-26OHHULF.js.map} +0 -0
  157. /package/dist/{config-WCEFYQL4.js.map → config-3UBJRE5R.js.map} +0 -0
  158. /package/dist/{config-mutate-LW366SKL.js.map → config-mutate-ZRPDYJKN.js.map} +0 -0
  159. /package/dist/{config-mutator-NRHZ2XH3.js.map → config-mutator-B5MR3V4B.js.map} +0 -0
  160. /package/dist/{context-planner-2XBAPQ3S.js.map → context-planner-CVCRW5TV.js.map} +0 -0
  161. /package/dist/{contributions-MUCJKT73.js.map → contributions-2CJFYRZ7.js.map} +0 -0
  162. /package/dist/{doctor-2N2MX5YP.js.map → doctor-OQZMDL5S.js.map} +0 -0
  163. /package/dist/{follow-up-tool-W64LMQQN.js.map → follow-up-tool-PQUPXQQT.js.map} +0 -0
  164. /package/dist/{grants-YGA654NI.js.map → grants-4O2VF2YX.js.map} +0 -0
  165. /package/dist/{heal-KCM6JYUK.js.map → heal-ZS56MC4A.js.map} +0 -0
  166. /package/dist/{hub-4ODFNGHL.js.map → hub-LOW7KS5N.js.map} +0 -0
  167. /package/dist/{memory-extract-4JFORU2K.js.map → memory-extract-NLVLQE7V.js.map} +0 -0
  168. /package/dist/{promote-OUSVJZ64.js.map → promote-ZWQAL3RE.js.map} +0 -0
  169. /package/dist/{providers-VVT2OBXA.js.map → providers-F5GDJSYD.js.map} +0 -0
  170. /package/dist/{query-QVK5EN3P.js.map → query-N4EJ24LW.js.map} +0 -0
  171. /package/dist/{query-settings-2TNLXEL5.js.map → query-settings-RZV5ELLC.js.map} +0 -0
  172. /package/dist/{registry-BYIWNEFL.js.map → registry-EBYOZK3P.js.map} +0 -0
  173. /package/dist/{request-planner-7HEHLPA3.js.map → request-planner-KCG6QB6M.js.map} +0 -0
  174. /package/dist/{review-candidates-NJNMSOCX.js.map → review-candidates-3GHWVJQ3.js.map} +0 -0
  175. /package/dist/{routing-HCSXNUOY.js.map → routing-XULOU6BI.js.map} +0 -0
  176. /package/dist/{schedule-tool-LJYBLCLV.js.map → schedule-tool-ALZXDGGC.js.map} +0 -0
  177. /package/dist/{scheduler-74MXJLQS.js.map → scheduler-SCVCNKJC.js.map} +0 -0
  178. /package/dist/{seat-CAYDECW2.js.map → seat-PD7W3KAN.js.map} +0 -0
  179. /package/dist/{select-QUVE6RN2.js.map → select-Z3YXBGUP.js.map} +0 -0
  180. /package/dist/{set-enabled-BWJN4IVG.js.map → set-enabled-NJYJWDWH.js.map} +0 -0
  181. /package/dist/{tool-FZ4UXMON.js.map → tool-EVQBMGJV.js.map} +0 -0
  182. /package/dist/{tool-UC7OZWIB.js.map → tool-XH5QN6JM.js.map} +0 -0
  183. /package/dist/{wiki-KNSPJT2O.js.map → wiki-BPOTYAQV.js.map} +0 -0
  184. /package/dist/{wiki-enrich-RVRTAQQF.js.map → wiki-enrich-JCNGRYQZ.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{V as B,W as J,X,Y as K,aa as N,fa as Oe}from"./chunk-B6GVATMI.js";import{existsSync as Q,readFileSync as Ie}from"node:fs";import{dirname as A,join as h}from"node:path";import{fileURLToPath as Ee}from"node:url";import{homedir as Ce}from"node:os";var M="tn.acme.agentx.voice",gt="AgentX Desktop.app",Y="AgentX Helper.app";function yt(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function ht(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function T(e){return`'${e.replace(/'/g,"'\\''")}'`}var Z="/usr/bin:/bin:/usr/sbin:/sbin";function wt(e,t){return t||[...new Set([...e?[A(e)]:[],...Z.split(":")])].join(":")}function R(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function St(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?R(t[1]):Z}var xt=e=>/agentx\.voice.*\.plist$/.test(e);function vt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,u)=>s.file<u.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],u=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!u||!R(u).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:R(s)}):n={file:o,label:R(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function ee(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function bt(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${T(e.cwd)} && ${T(e.node)} ${T(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{V as B,W as J,X,Y as K,aa as N,fa as Oe}from"./chunk-NKCS6EZ7.js";import{existsSync as Q,readFileSync as Ie}from"node:fs";import{dirname as A,join as h}from"node:path";import{fileURLToPath as Ee}from"node:url";import{homedir as Ce}from"node:os";var M="tn.acme.agentx.voice",gt="AgentX Desktop.app",Y="AgentX Helper.app";function yt(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function ht(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function T(e){return`'${e.replace(/'/g,"'\\''")}'`}var Z="/usr/bin:/bin:/usr/sbin:/sbin";function wt(e,t){return t||[...new Set([...e?[A(e)]:[],...Z.split(":")])].join(":")}function R(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function St(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?R(t[1]):Z}var xt=e=>/agentx\.voice.*\.plist$/.test(e);function vt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,u)=>s.file<u.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],u=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!u||!R(u).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:R(s)}):n={file:o,label:R(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function ee(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function bt(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${T(e.cwd)} && ${T(e.node)} ${T(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <plist version="1.0"><dict>
4
4
  <key>Label</key><string>${t(e.label??M)}</string>
@@ -33,4 +33,4 @@ function run(argv) {
33
33
  `),it(r,n)}var ut=5*6e4;function Cn(e,t,n=Date.now()){let r=Ae(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=ut)?!1:r.items[`card:${t}`]?.state!=="failed"}var U=24*36e5;function Re(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function lt(e,t,n,r){let o=Date.parse(e.expires),i=[f(e.ask,y.ask)];return e.choices?.length&&i.push(...e.choices.map((s,u)=>`${u+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${f(e.recommend,y.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:f(e.title,y.title),notes:i.join(`
34
34
  `),due:Re(r,t,o),priority:Number.isFinite(o)&&o-r<=U?"high":"none"}}function ct(e,t,n,r){let o=[f(e.question||e.text,y.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:W(e,y.title).headline,notes:o.join(`
35
35
  `),due:Re(r,t,i),priority:i!==void 0&&i-r<=U?"high":"none"}}async function Tn(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),u={created:0,completed:0,dismissed:0,failed:0},l=Ae(t);delete l.lastError;let p=a=>{l.lastError={at:s,message:a}},S=new Map;try{if(n.include.includes("card"))for(let a of e.cards())a.status==="pending"&&Date.parse(a.expires)>i&&S.set(`card:${a.id}`,lt(a,n,e.answerUrl,i));if(n.include.includes("request"))for(let a of e.requests())a.state==="waiting_owner"&&S.set(`request:${a.id}`,ct(a,n,e.answerUrl,i))}catch(a){return o(`[mirror] could not read what is waiting: ${a?.message??a}`),p(String(a?.message??a)),Ne(t,l),u}let G=!0,v=new Map,Pe=async a=>{if(!v.has(a))try{v.set(a,new Set((await r.listOpen(a)).map(c=>c.id)))}catch(c){o(`[mirror] could not read list "${a}": ${c?.message??c}`),p(String(c?.message??c)),v.set(a,null),G=!1}return v.get(a)};for(let[a,c]of Object.entries(l.items)){if(c.state!=="open"||!c.id)continue;let d=await Pe(c.list);if(d)if(S.has(a))d.has(c.id)||(l.items[a]={...c,state:"dismissed",at:s},u.dismissed++,o(`[mirror] ${a}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(c.id))try{await r.complete(c.id)}catch(g){o(`[mirror] ${a}: could not complete its task: ${g?.message??g}`),p(String(g?.message??g));continue}l.items[a]={...c,state:"completed",at:s},u.completed++}}let E=null,x=[];for(let[a,c]of S){let d=l.items[a];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=j)continue;if(E===null)try{await r.ensureList(n.list),E=!0}catch(m){o(`[mirror] could not make list "${n.list}": ${m?.message??m}`),p(String(m?.message??m)),E=!1}let g=d?.state==="failed"?d.failures:0;try{let{id:m}=await r.add({list:n.list,title:c.title,notes:c.notes,due:c.due,priority:c.priority});l.items[a]={id:m,list:n.list,state:"open",at:s,failures:0},u.created++}catch(m){let b=String(m?.message??m),C=g+1;l.items[a]={list:n.list,state:"failed",at:s,failures:C,lastError:b},p(b),u.failed++,o(`[mirror] ${a}: could not add to Reminders (${C}/${j}): ${b}`),C===j&&x.push({title:c.title,message:b})}}let $e=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(x.length&&!(i-$e<U)){let a=x[0],c=x.length>1?` (and ${x.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${a.title}${c}: ${f(a.message,200)}. Still on the Desk.`),l.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}G&&(l.checkedAt=s,l.cards=n.include.includes("card"));for(let[a,c]of Object.entries(l.items))c.state!=="open"&&!S.has(a)&&i-Date.parse(c.at)>at&&delete l.items[a];return Ne(t,l),u}export{gn as a,he as b,H as c,F as d,yn as e,hn as f,Ze as g,wn as h,Sn as i,xn as j,W as k,f as l,Rn as m,gt as n,Y as o,yt as p,ht as q,wt as r,St as s,xt as t,vt as u,ee as v,bt as w,Nt as x,Te as y,Me as z,_e as A,_ as B,se as C,q as D,ye as E,un as F,ln as G,cn as H,Ae as I,Cn as J,Tn as K};
36
- //# sourceMappingURL=chunk-BQXKTQCX.js.map
36
+ //# sourceMappingURL=chunk-PIJ6ECBC.js.map
@@ -0,0 +1,7 @@
1
+ import{createHash as Q,randomBytes as P}from"crypto";import{existsSync as Z,mkdirSync as tt,readdirSync as et,readFileSync as rt,renameSync as _,unlinkSync as nt,writeFileSync as st}from"fs";import{resolve as L}from"path";import{existsSync as x,mkdirSync as R,readFileSync as S,renameSync as O,writeFileSync as F}from"fs";import{dirname as N,resolve as v}from"path";var I="calendar.md";var ct=["# Content calendar","","One row per planned post. The agent adds next week's rows every Monday and updates the status.","","| Date | Platform | Topic | Status |","|------|----------|-------|--------|",""].join(`
2
+ `);function h(e){return v(e,I)}var j=/^\s*\|(.*)\|\s*$/,X=/^\d{4}-\d{2}-\d{2}$/;function y(e){let t=j.exec(e);return t?t[1].split("|").map(o=>o.trim()):null}function B(e){let t=[];for(let o of e.split(`
3
+ `)){let r=y(o);!r||r.length<4||!X.test(r[0])||t.push({date:r[0],platform:r[1].toLowerCase(),topic:r[2],status:r[3].toLowerCase()||"planned"})}return t}function ft(e){let t=h(e);if(!x(t))return null;try{return B(S(t,"utf-8"))}catch{return null}}function dt(e,t,o=7){let r=t.toISOString().slice(0,10),n=new Date(t.getTime()+o*864e5).toISOString().slice(0,10);return e.filter(a=>a.date>=r&&a.date<n).sort((a,l)=>a.date.localeCompare(l.date))}function g(e,t,o,r){let n=h(e);if(!x(n))return!1;let a;try{a=S(n,"utf-8")}catch{return!1}let l=!1,s=a.split(`
4
+ `).map(c=>{if(l)return c;let f=y(c);return!f||f.length<4||f[0]!==t||f[1].toLowerCase()!==o.toLowerCase()?c:(l=!0,f[3]=r,`| ${f.join(" | ")} |`)});if(!l)return!1;R(N(n),{recursive:!0});let i=`${n}.${process.pid}.tmp`;return F(i,s.join(`
5
+ `)),O(i,n),!0}import{existsSync as V,readdirSync as W,readFileSync as H,statSync as J}from"fs";import{resolve as w}from"path";var U="voice",z=/\.(md|markdown|txt)$/i,Y=200,q=2e4,C=240;function G(e){return w(e,U)}function D(e){let t=G(e);if(!V(t))return[];let o=[];for(let r of W(t).filter(n=>z.test(n)&&!n.startsWith(".")).sort()){let n=w(t,r);try{if(!J(n).isFile())continue;let a=H(n,"utf-8").slice(0,q).trim();a&&o.push({file:r,text:a})}catch{}if(o.length>=Y)break}return o}function k(e){return new Set(e.toLowerCase().match(/[\p{L}\p{N}]{4,}/gu)??[])}function K(e){let t=e.replace(/\s+/g," ").trim();return t.length>C?`${t.slice(0,C-1)}\u2026`:t}function mt(e,t="",o=3){let r=k(t);return D(e).map(n=>{let a=k(n.text),l=0;for(let s of r)a.has(s)&&l++;return{file:n.file,score:l,excerpt:K(n.text)}}).sort((n,a)=>a.score-n.score||n.file.localeCompare(a.file)).slice(0,Math.max(1,o))}function A(e,t){let o=new Set(D(e).map(r=>r.file));return t.filter(r=>!o.has(r))}var E=["linkedin","x"],b={linkedin:"LinkedIn",x:"X"},p={linkedin:3e3,x:280},$=10;function m(e){return L(e,".agentx","content","drafts")}var ot=e=>/^[a-z0-9-]{8,64}$/.test(e),u=(e,t)=>L(m(e),`${t}.json`);function T(e,t){tt(m(e),{recursive:!0});let o=u(e,t.id),r=`${o}.${process.pid}.tmp`;st(r,JSON.stringify(t,null,2)+`
6
+ `,{mode:384}),_(r,o)}var d=e=>typeof e=="string"?e.trim():"";function at(e){return Q("sha256").update(e).digest("hex").slice(0,16)}function wt(e,t,o=Date.now()){let r=d(t.platform).toLowerCase();if(!E.includes(r))return{ok:!1,error:`platform must be one of: ${E.join(", ")}`};let n=d(t.text);if(!n)return{ok:!1,error:"text is empty: give the whole post"};if(n.length>p[r])return{ok:!1,error:`the post is ${n.length} characters; ${b[r]} takes ${p[r]} at most`};let a=Array.isArray(t.samples)?Array.from(new Set(t.samples.map(d).filter(Boolean))):d(t.samples).split(",").map(f=>f.trim()).filter(Boolean);if(a.length===0)return{ok:!1,error:"samples is empty: name the files in voice/ this draft follows (add the owner's past posts there first)"};if(a.length>$)return{ok:!1,error:`name ${$} samples at most`};let l=A(t.workspace,a);if(l.length)return{ok:!1,error:`not in voice/: ${l.join(", ")}`};let s=d(t.date);if(s&&!/^\d{4}-\d{2}-\d{2}$/.test(s))return{ok:!1,error:"date must look like 2026-11-02"};let i=d(t.topic).slice(0,200),c={id:`${o.toString(36)}-${P(4).toString("hex")}`,status:"pending",created_at:new Date(o).toISOString(),agent:t.agent,platform:r,text:n,samples:a,...i?{topic:i}:{},...s?{date:s}:{},workspace:t.workspace};return T(e,c),s&&g(t.workspace,s,r,"drafted"),{ok:!0,draft:c}}function M(e,t){if(!ot(t))return null;try{return JSON.parse(rt(u(e,t),"utf-8"))}catch{return null}}function Dt(e,t){let o=m(e);return Z(o)?et(o).filter(r=>r.endsWith(".json")).map(r=>M(e,r.slice(0,-5))).filter(r=>!!r&&(!t||r.status===t)).sort((r,n)=>r.created_at.localeCompare(n.created_at)):[]}async function At(e,t,o,r){let n=M(e,t);if(!n||n.status!=="pending")return{ok:!1,error:`no content draft "${t}" is waiting`};if(o==="yes"&&r.seen!==void 0&&r.seen!==at(n.text))return{ok:!1,error:`content draft "${t}" changed since it was shown: reload and read it again before saying yes`};let a=r.text?.trim();if(o==="yes"&&a!==void 0){if(!a)return{ok:!1,error:"the edited post is empty"};if(a.length>p[n.platform])return{ok:!1,error:`the edited post is ${a.length} characters; ${b[n.platform]} takes ${p[n.platform]} at most`}}let l=`${u(e,t)}.${process.pid}.${P(3).toString("hex")}.claim`;try{_(u(e,t),l)}catch{return{ok:!1,error:`content draft "${t}" is already being decided`}}let s={...n,...o==="yes"&&a?{text:a}:{},decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(o==="no")s.status="rejected";else{let i=await r.publish(s).catch(c=>({ok:!1,error:String(c?.message??c)}));i.ok&&i.posted?(s.status="posted",i.url&&(s.url=i.url)):i.ok?(s.status="ready",s.file=i.file):(s.status="failed",s.error=i.error,i.file&&(s.file=i.file))}T(e,s);try{nt(l)}catch{}if(s.date){let i=s.status==="posted"?"posted":s.status==="rejected"?"skipped":"ready";g(s.workspace,s.date,s.platform,i)}return s.status==="failed"?{ok:!1,error:s.error??"publish failed"}:{ok:!0,draft:s}}export{ct as a,h as b,ft as c,dt as d,G as e,D as f,mt as g,b as h,ot as i,at as j,wt as k,M as l,Dt as m,At as n};
7
+ //# sourceMappingURL=chunk-RX5O5637.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/content/drafts.ts","../src/content/calendar.ts","../src/content/voice.ts"],"sourcesContent":["import { createHash, randomBytes } from \"crypto\"\nimport { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { setCalendarStatus } from \"./calendar\"\nimport { missingSamples } from \"./voice\"\n\n// --- Content drafts waiting for the owner ---\n//\n// The agent never publishes. Its post is saved here and listed in the\n// Approvals inbox as `content:<id>`. Only the owner's yes (CLI or\n// dashboard, see approvals/inbox.ts) publishes it: through the agent's\n// LinkedIn or X connector when one is set, else as a ready-to-paste file\n// (publish.ts).\n//\n// Every draft names the voice samples it followed (voice.ts): a draft that\n// names none, or a file that is not in voice/, is refused.\n//\n// One JSON file per draft under .agentx/content/drafts/, because the CLI,\n// the dashboard and the daemon are separate processes. Deciding first\n// renames the file away, so two clicks on \"yes\" publish once.\n\nexport const CONTENT_PLATFORMS = [\"linkedin\", \"x\"] as const\nexport type ContentPlatform = (typeof CONTENT_PLATFORMS)[number]\n\nexport const PLATFORM_LABEL: Record<ContentPlatform, string> = { linkedin: \"LinkedIn\", x: \"X\" }\n\n/** Longest post each platform takes. */\nexport const PLATFORM_MAX: Record<ContentPlatform, number> = { linkedin: 3000, x: 280 }\n\nexport const MAX_SAMPLES_NAMED = 10\n\nexport type ContentDraftStatus = \"pending\" | \"posted\" | \"ready\" | \"rejected\" | \"failed\"\n\nexport interface ContentDraft {\n id: string\n status: ContentDraftStatus\n created_at: string\n agent: string\n platform: ContentPlatform\n text: string\n /** Files in voice/ the draft follows. */\n samples: string[]\n topic?: string\n /** The calendar date it is planned for (YYYY-MM-DD). */\n date?: string\n /** The agent's workspace: where its samples, calendar and ready files live. */\n workspace: string\n decided_by?: string\n decided_at?: string\n /** Posted: the post's address, when the platform gave one. */\n url?: string\n /** Ready, or failed: the ready-to-paste file. */\n file?: string\n error?: string\n}\n\nexport type PublishResult =\n | { ok: true; posted: true; url?: string }\n | { ok: true; posted: false; file: string }\n | { ok: false; error: string; file?: string }\n\nexport type PublishContent = (draft: ContentDraft) => Promise<PublishResult>\n\nexport function contentDraftsDir(root: string): string {\n return resolve(root, \".agentx\", \"content\", \"drafts\")\n}\n\nexport const isValidContentDraftId = (id: string): boolean => /^[a-z0-9-]{8,64}$/.test(id)\nconst fileFor = (root: string, id: string): string => resolve(contentDraftsDir(root), `${id}.json`)\n\nfunction save(root: string, draft: ContentDraft): void {\n mkdirSync(contentDraftsDir(root), { recursive: true })\n const path = fileFor(root, draft.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(draft, null, 2) + \"\\n\", { mode: 0o600 })\n renameSync(tmp, path)\n}\n\nexport interface ContentDraftInput {\n agent: string\n workspace: string\n platform: unknown\n text: unknown\n samples: unknown\n topic?: unknown\n date?: unknown\n}\n\nconst str = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\")\n\n/** A short fingerprint of a post's text. The Approvals page sends back the\n * one it showed, so a yes never publishes text the owner did not see. */\nexport function contentTextHash(text: string): string {\n return createHash(\"sha256\").update(text).digest(\"hex\").slice(0, 16)\n}\n\n/** Check and save a new draft. Every refusal says what to fix. */\nexport function createContentDraft(\n root: string,\n input: ContentDraftInput,\n now = Date.now(),\n): { ok: true; draft: ContentDraft } | { ok: false; error: string } {\n const platform = str(input.platform).toLowerCase() as ContentPlatform\n if (!CONTENT_PLATFORMS.includes(platform)) return { ok: false, error: `platform must be one of: ${CONTENT_PLATFORMS.join(\", \")}` }\n const text = str(input.text)\n if (!text) return { ok: false, error: \"text is empty: give the whole post\" }\n if (text.length > PLATFORM_MAX[platform]) {\n return { ok: false, error: `the post is ${text.length} characters; ${PLATFORM_LABEL[platform]} takes ${PLATFORM_MAX[platform]} at most` }\n }\n const samples = Array.isArray(input.samples)\n ? Array.from(new Set(input.samples.map(str).filter(Boolean)))\n : str(input.samples).split(\",\").map((s) => s.trim()).filter(Boolean)\n if (samples.length === 0) {\n return { ok: false, error: \"samples is empty: name the files in voice/ this draft follows (add the owner's past posts there first)\" }\n }\n if (samples.length > MAX_SAMPLES_NAMED) return { ok: false, error: `name ${MAX_SAMPLES_NAMED} samples at most` }\n const missing = missingSamples(input.workspace, samples)\n if (missing.length) return { ok: false, error: `not in voice/: ${missing.join(\", \")}` }\n const date = str(input.date)\n if (date && !/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) return { ok: false, error: \"date must look like 2026-11-02\" }\n const topic = str(input.topic).slice(0, 200)\n\n const draft: ContentDraft = {\n id: `${now.toString(36)}-${randomBytes(4).toString(\"hex\")}`,\n status: \"pending\",\n created_at: new Date(now).toISOString(),\n agent: input.agent,\n platform,\n text,\n samples,\n ...(topic ? { topic } : {}),\n ...(date ? { date } : {}),\n workspace: input.workspace,\n }\n save(root, draft)\n if (date) setCalendarStatus(input.workspace, date, platform, \"drafted\")\n return { ok: true, draft }\n}\n\nexport function readContentDraft(root: string, id: string): ContentDraft | null {\n if (!isValidContentDraftId(id)) return null\n try { return JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as ContentDraft } catch { return null }\n}\n\nexport function listContentDrafts(root: string, status?: ContentDraftStatus): ContentDraft[] {\n const dir = contentDraftsDir(root)\n if (!existsSync(dir)) return []\n return readdirSync(dir)\n .filter((f) => f.endsWith(\".json\"))\n .map((f) => readContentDraft(root, f.slice(0, -5)))\n .filter((d): d is ContentDraft => !!d && (!status || d.status === status))\n .sort((a, b) => a.created_at.localeCompare(b.created_at))\n}\n\n/**\n * The owner's answer. Yes publishes the draft (as edited with `text`, when\n * given), no drops it. With `seen` (the contentTextHash of the text the\n * owner was shown), a yes is refused when the draft changed since.\n * Operator surfaces only: never reachable by an agent.\n */\nexport async function decideContentDraft(\n root: string,\n id: string,\n verdict: \"yes\" | \"no\",\n opts: { by?: string; now?: number; text?: string; seen?: string; publish: PublishContent },\n): Promise<{ ok: true; draft: ContentDraft } | { ok: false; error: string }> {\n const draft = readContentDraft(root, id)\n if (!draft || draft.status !== \"pending\") return { ok: false, error: `no content draft \"${id}\" is waiting` }\n if (verdict === \"yes\" && opts.seen !== undefined && opts.seen !== contentTextHash(draft.text)) {\n return { ok: false, error: `content draft \"${id}\" changed since it was shown: reload and read it again before saying yes` }\n }\n const edited = opts.text?.trim()\n if (verdict === \"yes\" && edited !== undefined) {\n if (!edited) return { ok: false, error: \"the edited post is empty\" }\n if (edited.length > PLATFORM_MAX[draft.platform]) {\n return { ok: false, error: `the edited post is ${edited.length} characters; ${PLATFORM_LABEL[draft.platform]} takes ${PLATFORM_MAX[draft.platform]} at most` }\n }\n }\n // Claim it: only one caller's rename succeeds.\n const claim = `${fileFor(root, id)}.${process.pid}.${randomBytes(3).toString(\"hex\")}.claim`\n try { renameSync(fileFor(root, id), claim) } catch {\n return { ok: false, error: `content draft \"${id}\" is already being decided` }\n }\n const decided: ContentDraft = {\n ...draft,\n ...(verdict === \"yes\" && edited ? { text: edited } : {}),\n decided_by: opts.by ?? \"operator\",\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n }\n if (verdict === \"no\") {\n decided.status = \"rejected\"\n } else {\n const r = await opts.publish(decided).catch((e: any): PublishResult => ({ ok: false, error: String(e?.message ?? e) }))\n if (r.ok && r.posted) { decided.status = \"posted\"; if (r.url) decided.url = r.url }\n else if (r.ok) { decided.status = \"ready\"; decided.file = r.file }\n else { decided.status = \"failed\"; decided.error = r.error; if (r.file) decided.file = r.file }\n }\n save(root, decided)\n try { unlinkSync(claim) } catch { /* already gone */ }\n if (decided.date) {\n const status = decided.status === \"posted\" ? \"posted\" : decided.status === \"rejected\" ? \"skipped\" : \"ready\"\n setCalendarStatus(decided.workspace, decided.date, decided.platform, status)\n }\n return decided.status === \"failed\" ? { ok: false, error: decided.error ?? \"publish failed\" } : { ok: true, draft: decided }\n}\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\n\n// --- The content calendar: <workspace>/calendar.md ---\n//\n// A plain Markdown table the owner can read and edit by hand, and the\n// agent fills each week on its schedule:\n//\n// | Date | Platform | Topic | Status |\n// |------------|----------|-------------------------|---------|\n// | 2026-11-02 | linkedin | What we learned in March | planned |\n//\n// The status moves on its own as a post goes through: planned → drafted\n// (the agent raised a draft) → posted, or ready (saved to paste by hand),\n// or skipped (the owner said no). Lines that are not table rows are kept\n// as they are.\n\nexport const CALENDAR_FILE = \"calendar.md\"\n\nexport const CALENDAR_STATUSES = [\"planned\", \"drafted\", \"posted\", \"ready\", \"skipped\"] as const\nexport type CalendarStatus = (typeof CALENDAR_STATUSES)[number]\n\nexport interface CalendarEntry {\n date: string\n platform: string\n topic: string\n status: string\n}\n\nexport const CALENDAR_TEMPLATE = [\n \"# Content calendar\",\n \"\",\n \"One row per planned post. The agent adds next week's rows every Monday and updates the status.\",\n \"\",\n \"| Date | Platform | Topic | Status |\",\n \"|------|----------|-------|--------|\",\n \"\",\n].join(\"\\n\")\n\nexport function calendarPath(workspace: string): string {\n return resolve(workspace, CALENDAR_FILE)\n}\n\nconst ROW = /^\\s*\\|(.*)\\|\\s*$/\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/\n\nfunction cells(line: string): string[] | null {\n const m = ROW.exec(line)\n return m ? m[1].split(\"|\").map((c) => c.trim()) : null\n}\n\n/** The rows of a calendar, in file order. Header and divider rows are not entries. */\nexport function parseCalendar(text: string): CalendarEntry[] {\n const out: CalendarEntry[] = []\n for (const line of text.split(\"\\n\")) {\n const c = cells(line)\n if (!c || c.length < 4 || !DATE.test(c[0])) continue\n out.push({ date: c[0], platform: c[1].toLowerCase(), topic: c[2], status: c[3].toLowerCase() || \"planned\" })\n }\n return out\n}\n\nexport function readCalendar(workspace: string): CalendarEntry[] | null {\n const path = calendarPath(workspace)\n if (!existsSync(path)) return null\n try { return parseCalendar(readFileSync(path, \"utf-8\")) } catch { return null }\n}\n\n/** Rows from `from` (inclusive) for `days` days, by date. */\nexport function upcoming(entries: CalendarEntry[], from: Date, days = 7): CalendarEntry[] {\n const start = from.toISOString().slice(0, 10)\n const end = new Date(from.getTime() + days * 86_400_000).toISOString().slice(0, 10)\n return entries.filter((e) => e.date >= start && e.date < end).sort((a, b) => a.date.localeCompare(b.date))\n}\n\n/**\n * Set the status of the row for `date` and `platform`, keeping every other\n * line as it is. False when there is no calendar or no such row.\n */\nexport function setCalendarStatus(workspace: string, date: string, platform: string, status: CalendarStatus): boolean {\n const path = calendarPath(workspace)\n if (!existsSync(path)) return false\n let text: string\n try { text = readFileSync(path, \"utf-8\") } catch { return false }\n let changed = false\n const lines = text.split(\"\\n\").map((line) => {\n if (changed) return line\n const c = cells(line)\n if (!c || c.length < 4 || c[0] !== date || c[1].toLowerCase() !== platform.toLowerCase()) return line\n changed = true\n c[3] = status\n return `| ${c.join(\" | \")} |`\n })\n if (!changed) return false\n mkdirSync(dirname(path), { recursive: true })\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, lines.join(\"\\n\"))\n renameSync(tmp, path)\n return true\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Voice samples: the owner's past posts, in the agent's workspace ---\n//\n// The owner drops past posts into <workspace>/voice/, one post per\n// .md or .txt file. The agent reads the ones closest to the topic before it\n// writes, and every draft names the files it followed (drafts.ts refuses a\n// draft that names none, or names a file that is not there).\n\nexport const VOICE_DIR = \"voice\"\n\nconst SAMPLE_EXT = /\\.(md|markdown|txt)$/i\nconst MAX_SAMPLES = 200\nconst MAX_SAMPLE_BYTES = 20_000\nconst EXCERPT = 240\n\nexport interface VoiceSample {\n /** File name inside voice/. */\n file: string\n text: string\n}\n\nexport interface PickedSample {\n file: string\n /** Words the sample shares with the topic. */\n score: number\n excerpt: string\n}\n\nexport function voiceDir(workspace: string): string {\n return resolve(workspace, VOICE_DIR)\n}\n\n/** Every sample in voice/, by file name. Missing folder: none. */\nexport function listSamples(workspace: string): VoiceSample[] {\n const dir = voiceDir(workspace)\n if (!existsSync(dir)) return []\n const out: VoiceSample[] = []\n for (const file of readdirSync(dir).filter((f) => SAMPLE_EXT.test(f) && !f.startsWith(\".\")).sort()) {\n const path = resolve(dir, file)\n try {\n if (!statSync(path).isFile()) continue\n const text = readFileSync(path, \"utf-8\").slice(0, MAX_SAMPLE_BYTES).trim()\n if (text) out.push({ file, text })\n } catch { /* unreadable: skip */ }\n if (out.length >= MAX_SAMPLES) break\n }\n return out\n}\n\nfunction words(s: string): Set<string> {\n return new Set((s.toLowerCase().match(/[\\p{L}\\p{N}]{4,}/gu) ?? []))\n}\n\nfunction excerpt(text: string): string {\n const flat = text.replace(/\\s+/g, \" \").trim()\n return flat.length > EXCERPT ? `${flat.slice(0, EXCERPT - 1)}…` : flat\n}\n\n/**\n * The samples to follow for a topic: the ones sharing the most words with\n * it, then by file name. With no topic, the first `n` by file name.\n */\nexport function pickSamples(workspace: string, topic = \"\", n = 3): PickedSample[] {\n const want = words(topic)\n return listSamples(workspace)\n .map((s) => {\n const have = words(s.text)\n let score = 0\n for (const w of want) if (have.has(w)) score++\n return { file: s.file, score, excerpt: excerpt(s.text) }\n })\n .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file))\n .slice(0, Math.max(1, n))\n}\n\n/** The named files that are not samples in voice/. */\nexport function missingSamples(workspace: string, files: string[]): string[] {\n const have = new Set(listSamples(workspace).map((s) => s.file))\n return files.filter((f) => !have.has(f))\n}\n"],"mappings":"AAAA,OAAS,cAAAA,EAAY,eAAAC,MAAmB,SACxC,OAAS,cAAAC,EAAY,aAAAC,GAAW,eAAAC,GAAa,gBAAAC,GAAc,cAAAC,EAAY,cAAAC,GAAY,iBAAAC,OAAqB,KACxG,OAAS,WAAAC,MAAe,OCFxB,OAAS,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KAC/E,OAAS,WAAAC,EAAS,WAAAC,MAAe,OAgB1B,IAAMC,EAAgB,cAYtB,IAAMC,GAAoB,CAC/B,qBACA,GACA,iGACA,GACA,u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WAAa,UAAY,QACpGjB,EAAkBiB,EAAQ,UAAWA,EAAQ,KAAMA,EAAQ,SAAUb,CAAM,EAE7E,OAAOa,EAAQ,SAAW,SAAW,CAAE,GAAI,GAAO,MAAOA,EAAQ,OAAS,gBAAiB,EAAI,CAAE,GAAI,GAAM,MAAOA,CAAQ,CAC5H","names":["createHash","randomBytes","existsSync","mkdirSync","readdirSync","readFileSync","renameSync","unlinkSync","writeFileSync","resolve","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","resolve","CALENDAR_FILE","CALENDAR_TEMPLATE","calendarPath","workspace","resolve","CALENDAR_FILE","ROW","DATE","cells","line","m","c","parseCalendar","text","out","readCalendar","path","existsSync","readFileSync","upcoming","entries","from","days","start","end","e","b","setCalendarStatus","date","platform","status","changed","lines","mkdirSync","dirname","tmp","writeFileSync","renameSync","existsSync","readdirSync","readFileSync","statSync","resolve","VOICE_DIR","SAMPLE_EXT","MAX_SAMPLES","MAX_SAMPLE_BYTES","EXCERPT","voiceDir","workspace","listSamples","dir","out","file","f","path","text","words","s","excerpt","flat","pickSamples","topic","n","want","have","score","w","a","b","missingSamples","files","CONTENT_PLATFORMS","PLATFORM_LABEL","PLATFORM_MAX","MAX_SAMPLES_NAMED","contentDraftsDir","root","resolve","isValidContentDraftId","id","fileFor","save","draft","mkdirSync","path","tmp","writeFileSync","renameSync","str","v","contentTextHash","text","createHash","createContentDraft","input","now","platform","samples","s","missing","missingSamples","date","topic","randomBytes","setCalendarStatus","readContentDraft","readFileSync","listContentDrafts","status","dir","existsSync","readdirSync","f","d","a","b","decideContentDraft","verdict","opts","edited","claim","decided","r","e","unlinkSync"]}
@@ -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 j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-IJZNM5PS.js";import{a as H}from"./chunk-LUOW2YHY.js";import{y as N,z as ot}from"./chunk-QGKNDGH5.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
1
+ import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-JKMFMW3E.js";import{a as H}from"./chunk-LUOW2YHY.js";import{y as N,z as ot}from"./chunk-Z6ZR2ELO.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{b as E,c as L}from"./chunk-QOYAX2FT.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
2
2
 
3
3
  ## Shared wiki (other agents' articles)
4
4
 
@@ -51,5 +51,5 @@ ${o}
51
51
 
52
52
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
53
 
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-WCEFYQL4.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-LQTTLXZY.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-3UBJRE5R.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-S34KFBMJ.js.map
@@ -1,4 +1,4 @@
1
- import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-IJZNM5PS.js";import{y as C,z as K}from"./chunk-QGKNDGH5.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
1
+ import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-JKMFMW3E.js";import{y as C,z as K}from"./chunk-Z6ZR2ELO.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
4
4
  `));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
105
- //# sourceMappingURL=chunk-XML72AUF.js.map
105
+ //# sourceMappingURL=chunk-TVGVQABC.js.map
@@ -1,4 +1,4 @@
1
- import{a as h}from"./chunk-XML72AUF.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
1
+ import{a as h}from"./chunk-TVGVQABC.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
2
2
  `),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
3
3
  `),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
4
- //# sourceMappingURL=chunk-7O43PB6O.js.map
4
+ //# sourceMappingURL=chunk-U4PICSLC.js.map
@@ -1,4 +1,4 @@
1
- import{c as w}from"./chunk-33KKV3YU.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
1
+ import{c as w}from"./chunk-COMJ7R5T.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
2
2
  ${a.content}`),t.previous??""].join(`
3
3
  `),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
4
4
  `).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
33
33
  {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
34
34
  `)+`
35
35
  `}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
36
- //# sourceMappingURL=chunk-AFLZHY5Y.js.map
36
+ //# sourceMappingURL=chunk-U5SJLLXH.js.map