agentix-cli 0.126.2 → 0.128.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 (152) hide show
  1. package/dist/{App-BUYK4EGC.js → App-BOLQUKCN.js} +2 -2
  2. package/dist/{ChatApp-ZS6EPDDK.js → ChatApp-72HXQV24.js} +2 -2
  3. package/dist/absorb-eval-O3HA6XA5.js +2 -0
  4. package/dist/{agent-WJTYM5HR.js → agent-S2DXXALS.js} +2 -2
  5. package/dist/{board-dashboard-DQR2OSV7.js → board-dashboard-ZKXXK5CG.js} +303 -228
  6. package/dist/board-dashboard-ZKXXK5CG.js.map +1 -0
  7. package/dist/chunk-2SV4RKRW.js +128 -0
  8. package/dist/chunk-2SV4RKRW.js.map +1 -0
  9. package/dist/{chunk-WUDVBPQV.js → chunk-4V7SWL2S.js} +2 -2
  10. package/dist/chunk-52SIHG45.js +4 -0
  11. package/dist/chunk-52SIHG45.js.map +1 -0
  12. package/dist/chunk-5DAEJF5S.js +36 -0
  13. package/dist/chunk-5DAEJF5S.js.map +1 -0
  14. package/dist/{chunk-GUQDPA6R.js → chunk-6GGGXCOY.js} +2 -2
  15. package/dist/{chunk-JIXNSA67.js → chunk-6KIUVVKX.js} +2 -2
  16. package/dist/{chunk-O4XEQTEN.js → chunk-C5MTLW7O.js} +3 -3
  17. package/dist/chunk-C5MTLW7O.js.map +1 -0
  18. package/dist/{chunk-FHBPKMCF.js → chunk-D2WX3BET.js} +2 -2
  19. package/dist/chunk-DN3RLR5Z.js +17 -0
  20. package/dist/chunk-DN3RLR5Z.js.map +1 -0
  21. package/dist/{chunk-Z7XXUYBB.js → chunk-DQ2LNQ2D.js} +33 -35
  22. package/dist/chunk-DQ2LNQ2D.js.map +1 -0
  23. package/dist/{chunk-UUVFH7BO.js → chunk-EJT4MA3J.js} +102 -102
  24. package/dist/chunk-EJT4MA3J.js.map +1 -0
  25. package/dist/chunk-FSW4FUMW.js +55 -0
  26. package/dist/chunk-FSW4FUMW.js.map +1 -0
  27. package/dist/chunk-FXBMFGOV.js +6 -0
  28. package/dist/chunk-FXBMFGOV.js.map +1 -0
  29. package/dist/{chunk-WMTGAVPW.js → chunk-HKW56YZK.js} +2 -2
  30. package/dist/{chunk-VXKNB4AW.js → chunk-LDS4SZBU.js} +2 -2
  31. package/dist/chunk-MRYA4J5F.js +54 -0
  32. package/dist/chunk-MRYA4J5F.js.map +1 -0
  33. package/dist/{chunk-LVV7JBHM.js → chunk-O2BS6N3T.js} +2 -2
  34. package/dist/{chunk-ZQWWMAMJ.js → chunk-P4XGM7ZM.js} +2 -2
  35. package/dist/{chunk-D6SWAB5J.js → chunk-QACEFESP.js} +32 -32
  36. package/dist/chunk-QACEFESP.js.map +1 -0
  37. package/dist/{chunk-6GLJIA25.js → chunk-QFZU5CEO.js} +2 -2
  38. package/dist/{chunk-FVG2BADS.js → chunk-QQFURUMS.js} +2 -2
  39. package/dist/chunk-QUXMLLX5.js +2 -0
  40. package/dist/chunk-QUXMLLX5.js.map +1 -0
  41. package/dist/{chunk-CY6ABHF2.js → chunk-TG6CT54D.js} +2 -2
  42. package/dist/chunk-TPNTFCSQ.js +4 -0
  43. package/dist/chunk-TPNTFCSQ.js.map +1 -0
  44. package/dist/{chunk-56KNKUFF.js → chunk-VD7IO653.js} +3 -3
  45. package/dist/{chunk-56KNKUFF.js.map → chunk-VD7IO653.js.map} +1 -1
  46. package/dist/{chunk-JUIL2EW3.js → chunk-YWKLUQDC.js} +2 -2
  47. package/dist/chunk-Z3W7D5RR.js +4 -0
  48. package/dist/chunk-Z3W7D5RR.js.map +1 -0
  49. package/dist/{chunk-QQYXYJOG.js → chunk-ZLC4TSXF.js} +2 -2
  50. package/dist/cli.js +1 -1
  51. package/dist/{client-PO5LDFS4.js → client-VBV7Q43P.js} +2 -2
  52. package/dist/config-52C3DJD2.js +2 -0
  53. package/dist/config-mutate-DKQESY6F.js +2 -0
  54. package/dist/config-mutator-BF4D4QGN.js +2 -0
  55. package/dist/contributions-5OEZWYXI.js +57 -0
  56. package/dist/contributions-5OEZWYXI.js.map +1 -0
  57. package/dist/doctor-VLRC4HW2.js +2 -0
  58. package/dist/{follow-up-tool-AIOLNUF7.js → follow-up-tool-235LDEMP.js} +2 -2
  59. package/dist/{follow-up-tool-AIOLNUF7.js.map → follow-up-tool-235LDEMP.js.map} +1 -1
  60. package/dist/hub-5QK7KYTZ.js +2 -0
  61. package/dist/index.d.ts +339 -50
  62. package/dist/index.js +1 -1
  63. package/dist/index.js.map +1 -1
  64. package/dist/notes-YLTNRMB5.js +2 -0
  65. package/dist/notes-settings-X63D5HPM.js +2 -0
  66. package/dist/{program-LGCT7FFJ.js → program-MVD57PKP.js} +236 -232
  67. package/dist/program-MVD57PKP.js.map +1 -0
  68. package/dist/{promote-MQYJMGGZ.js → promote-UPPQ4BQE.js} +2 -2
  69. package/dist/query-XQS5JN6E.js +2 -0
  70. package/dist/registry-MOMTLJ6R.js +2 -0
  71. package/dist/{request-planner-XYHM26CO.js → request-planner-QGZJEAKY.js} +2 -2
  72. package/dist/{review-candidates-XRBAMRBH.js → review-candidates-PAKF2JQF.js} +2 -2
  73. package/dist/{rotation-memo-6UW6DTBQ.js → rotation-memo-7VLREGS6.js} +2 -2
  74. package/dist/routing-JG3EV4O4.js +2 -0
  75. package/dist/schedule-tool-O7ZZ2A7X.js +2 -0
  76. package/dist/scheduler-LMPBAA34.js +2 -0
  77. package/dist/scheduler-LMPBAA34.js.map +1 -0
  78. package/dist/score-KDNIUTNV.js +3 -0
  79. package/dist/score-KDNIUTNV.js.map +1 -0
  80. package/dist/{seat-LKBZ6SDS.js → seat-JN3IVZ3G.js} +2 -2
  81. package/dist/seat-JN3IVZ3G.js.map +1 -0
  82. package/dist/{select-BSC3TFMZ.js → select-ZMMRFMNO.js} +2 -2
  83. package/dist/{set-enabled-YWXWSKME.js → set-enabled-7Y3TW6Z4.js} +2 -2
  84. package/dist/{tool-FZEC5FQX.js → tool-OCYXCDOK.js} +2 -2
  85. package/dist/{tool-FZEC5FQX.js.map → tool-OCYXCDOK.js.map} +1 -1
  86. package/dist/{tool-5JTCSRTW.js → tool-S7QI6HRA.js} +2 -2
  87. package/dist/{tool-5JTCSRTW.js.map → tool-S7QI6HRA.js.map} +1 -1
  88. package/dist/wiki-OCLFFZG6.js +2 -0
  89. package/dist/wiki-OCLFFZG6.js.map +1 -0
  90. package/package.json +1 -1
  91. package/dist/absorb-eval-5Y5IZWW2.js +0 -2
  92. package/dist/board-dashboard-DQR2OSV7.js.map +0 -1
  93. package/dist/chunk-2C3X6DVD.js +0 -49
  94. package/dist/chunk-2C3X6DVD.js.map +0 -1
  95. package/dist/chunk-2W3X6H7Z.js +0 -51
  96. package/dist/chunk-2W3X6H7Z.js.map +0 -1
  97. package/dist/chunk-46JKX6CT.js +0 -54
  98. package/dist/chunk-46JKX6CT.js.map +0 -1
  99. package/dist/chunk-5DFUUYEA.js +0 -126
  100. package/dist/chunk-5DFUUYEA.js.map +0 -1
  101. package/dist/chunk-D6SWAB5J.js.map +0 -1
  102. package/dist/chunk-O4XEQTEN.js.map +0 -1
  103. package/dist/chunk-UUVFH7BO.js.map +0 -1
  104. package/dist/chunk-YNA5T43U.js +0 -4
  105. package/dist/chunk-YNA5T43U.js.map +0 -1
  106. package/dist/chunk-Z7XXUYBB.js.map +0 -1
  107. package/dist/config-L2RQ6EJX.js +0 -2
  108. package/dist/config-mutator-44OAOZXM.js +0 -2
  109. package/dist/doctor-AU5TCOSG.js +0 -2
  110. package/dist/hub-53YQQCVA.js +0 -2
  111. package/dist/program-LGCT7FFJ.js.map +0 -1
  112. package/dist/query-DNJONEKC.js +0 -2
  113. package/dist/registry-5A3SLBVJ.js +0 -2
  114. package/dist/routing-OMIWZKNC.js +0 -2
  115. package/dist/schedule-tool-YRANRFHO.js +0 -2
  116. package/dist/scheduler-L4P4Z55R.js +0 -2
  117. package/dist/wiki-BT3H2WCD.js +0 -2
  118. /package/dist/{App-BUYK4EGC.js.map → App-BOLQUKCN.js.map} +0 -0
  119. /package/dist/{ChatApp-ZS6EPDDK.js.map → ChatApp-72HXQV24.js.map} +0 -0
  120. /package/dist/{absorb-eval-5Y5IZWW2.js.map → absorb-eval-O3HA6XA5.js.map} +0 -0
  121. /package/dist/{agent-WJTYM5HR.js.map → agent-S2DXXALS.js.map} +0 -0
  122. /package/dist/{chunk-WUDVBPQV.js.map → chunk-4V7SWL2S.js.map} +0 -0
  123. /package/dist/{chunk-GUQDPA6R.js.map → chunk-6GGGXCOY.js.map} +0 -0
  124. /package/dist/{chunk-JIXNSA67.js.map → chunk-6KIUVVKX.js.map} +0 -0
  125. /package/dist/{chunk-FHBPKMCF.js.map → chunk-D2WX3BET.js.map} +0 -0
  126. /package/dist/{chunk-WMTGAVPW.js.map → chunk-HKW56YZK.js.map} +0 -0
  127. /package/dist/{chunk-VXKNB4AW.js.map → chunk-LDS4SZBU.js.map} +0 -0
  128. /package/dist/{chunk-LVV7JBHM.js.map → chunk-O2BS6N3T.js.map} +0 -0
  129. /package/dist/{chunk-ZQWWMAMJ.js.map → chunk-P4XGM7ZM.js.map} +0 -0
  130. /package/dist/{chunk-6GLJIA25.js.map → chunk-QFZU5CEO.js.map} +0 -0
  131. /package/dist/{chunk-FVG2BADS.js.map → chunk-QQFURUMS.js.map} +0 -0
  132. /package/dist/{chunk-CY6ABHF2.js.map → chunk-TG6CT54D.js.map} +0 -0
  133. /package/dist/{chunk-JUIL2EW3.js.map → chunk-YWKLUQDC.js.map} +0 -0
  134. /package/dist/{chunk-QQYXYJOG.js.map → chunk-ZLC4TSXF.js.map} +0 -0
  135. /package/dist/{client-PO5LDFS4.js.map → client-VBV7Q43P.js.map} +0 -0
  136. /package/dist/{config-L2RQ6EJX.js.map → config-52C3DJD2.js.map} +0 -0
  137. /package/dist/{config-mutator-44OAOZXM.js.map → config-mutate-DKQESY6F.js.map} +0 -0
  138. /package/dist/{doctor-AU5TCOSG.js.map → config-mutator-BF4D4QGN.js.map} +0 -0
  139. /package/dist/{hub-53YQQCVA.js.map → doctor-VLRC4HW2.js.map} +0 -0
  140. /package/dist/{promote-MQYJMGGZ.js.map → hub-5QK7KYTZ.js.map} +0 -0
  141. /package/dist/{query-DNJONEKC.js.map → notes-YLTNRMB5.js.map} +0 -0
  142. /package/dist/{registry-5A3SLBVJ.js.map → notes-settings-X63D5HPM.js.map} +0 -0
  143. /package/dist/{routing-OMIWZKNC.js.map → promote-UPPQ4BQE.js.map} +0 -0
  144. /package/dist/{schedule-tool-YRANRFHO.js.map → query-XQS5JN6E.js.map} +0 -0
  145. /package/dist/{scheduler-L4P4Z55R.js.map → registry-MOMTLJ6R.js.map} +0 -0
  146. /package/dist/{request-planner-XYHM26CO.js.map → request-planner-QGZJEAKY.js.map} +0 -0
  147. /package/dist/{review-candidates-XRBAMRBH.js.map → review-candidates-PAKF2JQF.js.map} +0 -0
  148. /package/dist/{rotation-memo-6UW6DTBQ.js.map → rotation-memo-7VLREGS6.js.map} +0 -0
  149. /package/dist/{seat-LKBZ6SDS.js.map → routing-JG3EV4O4.js.map} +0 -0
  150. /package/dist/{wiki-BT3H2WCD.js.map → schedule-tool-O7ZZ2A7X.js.map} +0 -0
  151. /package/dist/{select-BSC3TFMZ.js.map → select-ZMMRFMNO.js.map} +0 -0
  152. /package/dist/{set-enabled-YWXWSKME.js.map → set-enabled-7Y3TW6Z4.js.map} +0 -0
@@ -1,49 +0,0 @@
1
- import{c as R}from"./chunk-56KNKUFF.js";import{a as O,b as j,c as E,d as T,e as D,j as _}from"./chunk-VXKNB4AW.js";import{y as M,z as F}from"./chunk-JUIL2EW3.js";import{b as S,c as P}from"./chunk-QOYAX2FT.js";import{readFileSync as G,existsSync as J}from"fs";F();import{resolve as $}from"path";import{execSync as K}from"child_process";async function it(r,e,i,t={}){let h=t.selectorModel??"haiku",m=t.synthModel??"sonnet",o=t.maxCandidates??3,c=t.maxHops??2,n=t.maxArticles??8,u=t.timeoutMs??6e4,g=t.log??console.error.bind(console,"[wiki-query]"),p=t.messagePath?.length?t.messagePath:void 0,s=t.graphWeight??x,a=$(e.baseDir,"_index.md");if(!J(a))return b("no-catalog",r,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let d=G(a,"utf-8"),v=Date.now(),f=[],y="";try{let l=await Y(r,N(e),i,o,p,s);l?(f=l,y=`[wiki-rerank seat] ${l.map(k=>k.title).join(" | ")}`):(y=await I(U(r,d,o,p),h,u),f=V(y))}catch(l){return g("selector failed:",l?.message),{...b("error",r,`Selector: ${l?.message||"unknown"}`),trace:{selectorMs:Date.now()-v,synthesisMs:0,selectorOutput:y}}}let A=Date.now()-v;if(f.length===0)return{...b("no-candidates",r,"Selector returned no candidates."),trace:{selectorMs:A,synthesisMs:0,selectorOutput:y}};let w=Q(f,e,i,c,n);if(w.length===0)return{...b("no-candidates",r,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:A,synthesisMs:0,selectorOutput:y}};let C=Date.now(),W="";try{W=await I(z(r,w),m,u*2)}catch(l){return g("synthesis failed:",l?.message),{...b("error",r,`Synthesis: ${l?.message||"unknown"}`),candidates:f,walked:w.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:A,synthesisMs:Date.now()-C,selectorOutput:y}}}let L=Date.now()-C;return{answer:W.trim(),citations:w.map(l=>({title:l.meta.title,path:l.path,type:l.meta.type})),candidates:f,walked:w.map(l=>({title:l.meta.title,path:l.path,type:l.meta.type,hop:l.hop??0})),status:"ok",trace:{selectorMs:A,synthesisMs:L,selectorOutput:y}}}async function st(r,e,i,t={}){let h=t.maxCandidates??3,m=t.graphWeight??x,o=t.messagePath?.length?t.messagePath:void 0,c=t.pool??N(e);if(c.length===0||!r.trim())return[];let n=await Y(r,c,i,h,o,m,t.stage??"retrieve");if(!n){let u=new Set(P(r,S(c.map(H))).map(g=>g.docIndex));n=B(r,c,o,m).filter(g=>u.has(g)).slice(0,h).map(g=>({title:c[g].title,path:c[g].path}))}return n.length===0?[]:Q(n,e,i,t.maxHops??1,t.maxArticles??6)}function N(r){try{return(r.rebuildIndex().articles??[]).filter(e=>e.path&&!e.path.includes("/_versions/"))}catch{return[]}}function b(r,e,i){return{answer:"",citations:[],candidates:[],walked:[],status:r,error:i}}function Q(r,e,i,t,h){let m=new Map;for(let n of e.listArticles(i||""))m.set(n.meta.title.toLowerCase(),n.path);let o=new Map,c=[];for(let n of r)o.has(n.path)||c.push({path:n.path,hop:0});for(;c.length&&o.size<h;){let n=c.shift();if(o.has(n.path)||n.hop>t)continue;let u=i?e.readArticleAs(n.path,i):e.readArticle(n.path);if(u&&(o.set(n.path,{...u,hop:n.hop}),!(n.hop>=t)))for(let g of u.meta.related||[]){let p=m.get(g.toLowerCase());p&&!o.has(p)&&c.push({path:p,hop:n.hop+1})}}return Array.from(o.values())}async function Y(r,e,i,t,h,m=x,o="catalog-selector"){try{if(e.length<2)return null;let n=B(r,e,h,m).slice(0,j).map(s=>({id:`k${s}`,title:e[s].title||e[s].path,tags:e[s].tags,excerpt:[e[s].type?`type: ${e[s].type}`:"",(e[s].related??[]).length?`related: ${(e[s].related??[]).join(", ")}`:"",(e[s].graphPath??[]).length?`graph: ${(e[s].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),u=await M(O,E({query:r,candidates:n,excerptChars:300}),T(n),{features:{agent:i??"unknown",stage:o}});if(!u||u.mode!=="active")return null;let p=D(u.answers,n).ranked.slice(0,t).map(s=>e[Number(s.slice(1))]).filter(Boolean).map(s=>({title:s.title,path:s.path}));return p.length>0?p:null}catch{return null}}var x=.6;function B(r,e,i,t=x){let h=P(r,S(e.map(H))),m=h.reduce((a,d)=>Math.max(a,d.score),0),o=new Map(h.map(a=>[a.docIndex,m>0?a.score/m:0])),c=!!i?.length,n=a=>c&&a.graphPath?.length?_(i,a.graphPath):0,u=(a,d)=>d.score-a.score||a.i-d.i,g=e.map((a,d)=>({i:d,score:(o.get(d)??0)*(1+t*n(a))})).filter(a=>o.has(a.i)).sort(u),p=e.map((a,d)=>({i:d,score:n(a)})).filter(a=>!o.has(a.i)&&a.score>0).sort(u),s=[...g,...p].map(a=>a.i);for(let a=0;a<e.length;a++)s.includes(a)||s.push(a);return s}function H(r){return[r.title,(r.tags??[]).join(" "),(r.related??[]).join(" ")].join(" ")}function U(r,e,i,t){let h=t?.length?`
2
- ## Intent
3
-
4
- The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
5
- `:"";return`You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.
6
-
7
- ## Question
8
-
9
- ${r}
10
- ${h}
11
- ## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
12
-
13
- ${e}
14
-
15
- ## Your task
16
-
17
- Pick up to ${i} articles from the catalog that are most likely to answer the question. Prefer:
18
- - Articles whose title directly names a subject in the question.
19
- - Articles of the right type (e.g. a "who owns X" question \u2192 person or project; a "what happened on DATE" \u2192 event).
20
- - Articles whose wikilinks suggest they sit at the center of a relevant subgraph.
21
-
22
- Return ONLY valid JSON, no markdown fencing, no prose:
23
-
24
- [
25
- {"title": "Exact Article Title", "path": "path/from/catalog.md"},
26
- ...
27
- ]
28
-
29
- If none of the articles match, return [].`}function z(r,e){let i=e.map(t=>{let h=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]`,m=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[h,m,"",t.content].filter(Boolean).join(`
30
- `)}).join(`
31
-
32
- ---
33
-
34
- `);return`You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.
35
-
36
- ## Question
37
-
38
- ${r}
39
-
40
- ## Articles (${e.length} walked from the catalog)
41
-
42
- ${i}
43
-
44
- ## Your task
45
-
46
- Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
47
-
48
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function V(r){let e=r.match(/\[[\s\S]*?\]/);if(!e)return[];try{let i=JSON.parse(e[0]);return Array.isArray(i)?i.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function I(r,e,i){let{writeFileSync:t,mkdirSync:h,rmSync:m}=await import("fs"),{tmpdir:o}=await import("os"),c=$(o(),`agentx-wiki-query-${process.pid}`);h(c,{recursive:!0});let n=$(c,`prompt-${Date.now()}.txt`);t(n,r);try{let u=`cat '${n}' | claude -p - --output-format json --max-turns 1 --model ${e} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,g=K(u,{env:R(),encoding:"utf-8",timeout:i,maxBuffer:4*1024*1024});try{let p=JSON.parse(g);return String(p.result||p.content||"")}catch{return g}}finally{try{m(n,{force:!0})}catch{}}}export{it as a,st as b,N as c,x as d,B as e};
49
- //# sourceMappingURL=chunk-2C3X6DVD.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/wiki/query.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { buildIndex, scoreAll } from \"@/memory/bm25\"\nimport { askSeat } from \"@/decisions/seat\"\nimport { ancestryScore } from \"@/graph\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"@/decisions/seats/wiki-rerank\"\nimport { claudeCliEnv } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle, WikiIndex } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\n/**\n * Agentic wiki query — the \"Farzapedia-faithful\" retrieval path.\n *\n * Two LLM calls + a deterministic graph walk:\n * 1. Selector (cheap): read `_index.md` + question → pick up to `maxCandidates`\n * candidate articles by title + type.\n * 2. Walk (pure code): starting from candidates, follow `related` wikilinks\n * up to `maxHops`, capped at `maxArticles` total.\n * 3. Synthesis (main): answer the question from the walked subgraph.\n *\n * Returns an answer with citations and a trace of which articles were walked,\n * so callers can audit the retrieval path.\n */\n\nexport interface AgenticQueryOptions {\n /** Candidate-selection model (cheap). Defaults to \"haiku\". */\n selectorModel?: string\n /** Synthesis model (main). Defaults to \"sonnet\". */\n synthModel?: string\n /** Number of candidates the selector is asked to return. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from candidates. Default 2. */\n maxHops?: number\n /** Hard cap on total articles walked. Default 8. */\n maxArticles?: number\n /** Timeout per LLM call, ms. Default 60_000. */\n timeoutMs?: number\n /** Logger — defaults to console.error. */\n log?: (...args: unknown[]) => void\n /** Intent-graph path the question's request was classified under.\n * Articles on the same branch rank higher in candidate selection. */\n messagePath?: string[]\n /** Weight of the branch match against the text match, 0–1. Default 0.6\n * (`graph.retrievalWeights.graph`). */\n graphWeight?: number\n}\n\nexport interface AgenticQueryResult {\n answer: string\n citations: Array<{ title: string; path: string; type?: string }>\n /** Titles/paths the selector picked. */\n candidates: Array<{ title: string; path: string }>\n /** Full article subgraph the walk produced. */\n walked: Array<{ title: string; path: string; type?: string; hop: number }>\n /** \"no-catalog\" | \"no-candidates\" | \"ok\" */\n status: \"ok\" | \"no-catalog\" | \"no-candidates\" | \"error\"\n /** For operator debugging only. */\n trace?: {\n selectorMs: number\n synthesisMs: number\n selectorOutput?: string\n }\n error?: string\n}\n\n/**\n * Run an agentic query against a specific agent's WikiStore.\n *\n * `requesterId` is used for permission checks — only articles the requester\n * can read will be included in the synthesis input.\n */\nexport async function agenticQuery(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: AgenticQueryOptions = {},\n): Promise<AgenticQueryResult> {\n const selectorModel = opts.selectorModel ?? \"haiku\"\n const synthModel = opts.synthModel ?? \"sonnet\"\n const maxCandidates = opts.maxCandidates ?? 3\n const maxHops = opts.maxHops ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const timeoutMs = opts.timeoutMs ?? 60_000\n const log = opts.log ?? console.error.bind(console, \"[wiki-query]\")\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n\n // --- Step 1: Load the catalog ---\n const catalogPath = resolve(store.baseDir, \"_index.md\")\n if (!existsSync(catalogPath)) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const catalog = readFileSync(catalogPath, \"utf-8\")\n\n // --- Step 2: Selector — pick candidates ---\n const selectorStart = Date.now()\n let candidates: Array<{ title: string; path: string }> = []\n let selectorOutput = \"\"\n try {\n const viaSeat = await selectCandidatesViaSeat(question, catalogPool(store), requesterId, maxCandidates, messagePath, graphWeight)\n if (viaSeat) {\n candidates = viaSeat\n selectorOutput = `[wiki-rerank seat] ${viaSeat.map((c) => c.title).join(\" | \")}`\n } else {\n selectorOutput = await runClaude(\n buildSelectorPrompt(question, catalog, maxCandidates, messagePath),\n selectorModel,\n timeoutMs,\n )\n candidates = parseCandidates(selectorOutput)\n }\n } catch (e: any) {\n log(\"selector failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Selector: ${e?.message || \"unknown\"}`), trace: { selectorMs: Date.now() - selectorStart, synthesisMs: 0, selectorOutput } }\n }\n const selectorMs = Date.now() - selectorStart\n\n if (candidates.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Selector returned no candidates.\"), trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 3: Walk the subgraph via `related` wikilinks ---\n const walked = walkSubgraph(candidates, store, requesterId, maxHops, maxArticles)\n\n if (walked.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Candidates did not resolve to readable articles.\"), candidates, trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 4: Synthesize the answer ---\n const synthStart = Date.now()\n let answer = \"\"\n try {\n answer = await runClaude(\n buildSynthesisPrompt(question, walked),\n synthModel,\n timeoutMs * 2,\n )\n } catch (e: any) {\n log(\"synthesis failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Synthesis: ${e?.message || \"unknown\"}`), candidates, walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })), trace: { selectorMs, synthesisMs: Date.now() - synthStart, selectorOutput } }\n }\n const synthesisMs = Date.now() - synthStart\n\n return {\n answer: answer.trim(),\n citations: walked.map(a => ({ title: a.meta.title, path: a.path, type: a.meta.type })),\n candidates,\n walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })),\n status: \"ok\",\n trace: { selectorMs, synthesisMs, selectorOutput },\n }\n}\n\nexport interface RetrieveOptions {\n /** Articles picked before the walk. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from the picked articles. Default 1. */\n maxHops?: number\n /** Hard cap on articles returned. Default 6. */\n maxArticles?: number\n messagePath?: string[]\n graphWeight?: number\n /** The catalog to pick from. Pass it when retrieving many times in a row,\n * so the index is not rebuilt for every call. */\n pool?: CatalogEntry[]\n /** Seat telemetry label. */\n stage?: string\n}\n\n/**\n * The retrieval half of agenticQuery, without the synthesis call: BM25\n * shortlist, rerank seat, then the `related` wikilink walk. Returns the\n * walked articles, hop 0 first.\n *\n * When the seat is off or fails, the BM25 order decides on its own, and\n * only articles the text matched are picked: an article chosen for\n * nothing but its catalog position is noise here, not a candidate. There\n * is no CLI fallback, so this never spends an LLM call.\n */\nexport async function retrieveArticles(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: RetrieveOptions = {},\n): Promise<Array<WikiArticle & { hop: number }>> {\n const maxCandidates = opts.maxCandidates ?? 3\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const pool = opts.pool ?? catalogPool(store)\n if (pool.length === 0 || !question.trim()) return []\n\n let candidates = await selectCandidatesViaSeat(\n question, pool, requesterId, maxCandidates, messagePath, graphWeight, opts.stage ?? \"retrieve\",\n )\n if (!candidates) {\n const matched = new Set(scoreAll(question, buildIndex(pool.map(catalogDoc))).map((r) => r.docIndex))\n candidates = rankCatalogPool(question, pool, messagePath, graphWeight)\n .filter((i) => matched.has(i))\n .slice(0, maxCandidates)\n .map((i) => ({ title: pool[i].title, path: pool[i].path }))\n }\n if (candidates.length === 0) return []\n return walkSubgraph(candidates, store, requesterId, opts.maxHops ?? 1, opts.maxArticles ?? 6)\n}\n\nexport type CatalogEntry = WikiIndex[\"articles\"][number]\n\n/** The catalog retrieval picks from: every indexed article but old versions. */\nexport function catalogPool(store: WikiStore): CatalogEntry[] {\n try {\n return (store.rebuildIndex().articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n } catch {\n return []\n }\n}\n\n// --- Helpers ---\n\nfunction emptyResult(\n status: AgenticQueryResult[\"status\"],\n _question: string,\n error?: string,\n): AgenticQueryResult {\n return {\n answer: \"\",\n citations: [],\n candidates: [],\n walked: [],\n status,\n error,\n }\n}\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n store: WikiStore,\n requesterId: string | undefined,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n // Build a title → path index from the store so wikilinks resolve.\n const titleIndex = new Map<string, string>()\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n }\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let frontier: Array<{ path: string; hop: number }> = []\n\n for (const c of candidates) {\n if (!opened.has(c.path)) frontier.push({ path: c.path, hop: 0 })\n }\n\n while (frontier.length && opened.size < maxArticles) {\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n\n const article = requesterId\n ? store.readArticleAs(next.path, requesterId)\n : store.readArticle(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (next.hop >= maxHops) continue\n\n for (const target of article.meta.related || []) {\n const path = titleIndex.get(target.toLowerCase())\n if (path && !opened.has(path)) {\n frontier.push({ path, hop: next.hop + 1 })\n }\n }\n }\n\n return Array.from(opened.values())\n}\n\n// --- Prompts ---\n\n/**\n * Pick candidates with the wiki-rerank seat instead of a Claude CLI call.\n *\n * The selector is 56% of a wiki query — 14.1s of a 25s total, measured —\n * and its whole job is \"pick 3 articles from this catalog\", which is a\n * Choice with per-option probabilities. Jev answers that in about a\n * second. Synthesis stays on Sonnet; it writes prose, which Jev cannot.\n *\n * BM25 shortlists first because the shared catalog carries 971 entries,\n * past the 255-option cap. Same two-stage shape as findRelevantReranked,\n * and it reuses that seat rather than introducing a second one.\n *\n * Returns null whenever the seat is off, errors, or has nothing to rank,\n * and the caller falls back to the CLI selector — so this is strictly an\n * accelerator, never a new way to fail.\n */\nasync function selectCandidatesViaSeat(\n question: string,\n pool: CatalogEntry[],\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n stage = \"catalog-selector\",\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\n if (pool.length < 2) return null\n\n const shortlist = rankCatalogPool(question, pool, messagePath, graphWeight).slice(0, DEFAULT_SHORTLIST)\n\n const candidates: RerankCandidate[] = shortlist.map((i) => ({\n id: `k${i}`,\n title: pool[i].title || pool[i].path,\n tags: pool[i].tags,\n // The catalog has no body — a title, its type, its wikilinks and its\n // branch of the intent graph are what the selector chooses on.\n excerpt: [\n pool[i].type ? `type: ${pool[i].type}` : \"\",\n (pool[i].related ?? []).length ? `related: ${(pool[i].related ?? []).join(\", \")}` : \"\",\n (pool[i].graphPath ?? []).length ? `graph: ${(pool[i].graphPath ?? []).join(\" › \")}` : \"\",\n ].filter(Boolean).join(\" · \"),\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query: question, candidates, excerptChars: 300 }),\n rerankQuestions(candidates),\n { features: { agent: requesterId ?? \"unknown\", stage } },\n )\n if (!result || result.mode !== \"active\") return null\n\n const ranking = toRanking(result.answers as never, candidates)\n const picked = ranking.ranked\n .slice(0, maxCandidates)\n .map((id) => pool[Number(id.slice(1))])\n .filter(Boolean)\n .map((a) => ({ title: a.title, path: a.path }))\n return picked.length > 0 ? picked : null\n } catch {\n return null\n }\n}\n\n/** Weight of the intent-graph branch match against the text match when\n * shortlisting catalog candidates. Mirrors `graph.retrievalWeights.graph`. */\nexport const DEFAULT_GRAPH_WEIGHT = 0.6\n\n/**\n * Order the catalog pool for a question. Three bands, never mixed:\n *\n * 1. articles the text match scored, ordered by `text * (1 + w * branch)`\n * when the request was classified: the branch reorders text matches\n * but cannot lift an unrelated article above one;\n * 2. articles on the request's branch that the text never matched, by\n * how much of the path they share;\n * 3. the rest, in catalog order.\n *\n * Band 1 comes first in full because the shortlist the reranker sees is\n * finite (DEFAULT_SHORTLIST): a busy category holds more same-branch\n * articles than that, and a blended score let them push the article that\n * actually answers the question out of the list.\n *\n * Exported for tests; the seat and the CLI selector both consume the order.\n */\nexport function rankCatalogPool(\n question: string,\n pool: Array<{ title: string; tags?: string[]; related?: string[]; graphPath?: string[] }>,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): number[] {\n const bm25 = scoreAll(question, buildIndex(pool.map(catalogDoc)))\n const maxBm25 = bm25.reduce((m, r) => Math.max(m, r.score), 0)\n const text = new Map(bm25.map((r) => [r.docIndex, maxBm25 > 0 ? r.score / maxBm25 : 0]))\n const useGraph = !!messagePath?.length\n const branch = (a: { graphPath?: string[] }) =>\n useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n\n const byScore = (x: { i: number; score: number }, y: { i: number; score: number }) => y.score - x.score || x.i - y.i\n const matched = pool\n .map((a, i) => ({ i, score: (text.get(i) ?? 0) * (1 + graphWeight * branch(a)) }))\n .filter((c) => text.has(c.i))\n .sort(byScore)\n const branchOnly = pool\n .map((a, i) => ({ i, score: branch(a) }))\n .filter((c) => !text.has(c.i) && c.score > 0)\n .sort(byScore)\n const ranked = [...matched, ...branchOnly].map((c) => c.i)\n for (let i = 0; i < pool.length; i++) if (!ranked.includes(i)) ranked.push(i)\n return ranked\n}\n\n/** What BM25 sees of a catalog entry: the catalog carries no body. */\nfunction catalogDoc(a: { title: string; tags?: string[]; related?: string[] }): string {\n return [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \")\n}\n\nfunction buildSelectorPrompt(question: string, catalog: string, maxCandidates: number, messagePath?: string[]): string {\n const branch = messagePath?.length\n ? `\\n## Intent\\n\\nThe request was classified under the intent-graph path \"${messagePath.join(\" › \")}\". Prefer articles filed under the same branch when their titles are equally plausible.\\n`\n : \"\"\n return `You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.\n\n## Question\n\n${question}\n${branch}\n## Catalog (_index.md — articles grouped by type, with wikilink previews)\n\n${catalog}\n\n## Your task\n\nPick up to ${maxCandidates} articles from the catalog that are most likely to answer the question. Prefer:\n- Articles whose title directly names a subject in the question.\n- Articles of the right type (e.g. a \"who owns X\" question → person or project; a \"what happened on DATE\" → event).\n- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.\n\nReturn ONLY valid JSON, no markdown fencing, no prose:\n\n[\n {\"title\": \"Exact Article Title\", \"path\": \"path/from/catalog.md\"},\n ...\n]\n\nIf none of the articles match, return [].`\n}\n\nfunction buildSynthesisPrompt(\n question: string,\n articles: Array<WikiArticle & { hop: number }>,\n): string {\n const articlesBlock = articles\n .map(a => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, related, \"\", a.content].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n\n return `You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.\n\n## Question\n\n${question}\n\n## Articles (${articles.length} walked from the catalog)\n\n${articlesBlock}\n\n## Your task\n\nAnswer the question in 2–6 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\n\nOutput ONLY the answer — no preamble, no \"here is my answer:\", no markdown fencing.`\n}\n\nfunction parseCandidates(raw: string): Array<{ title: string; path: string }> {\n const match = raw.match(/\\[[\\s\\S]*?\\]/)\n if (!match) return []\n try {\n const parsed = JSON.parse(match[0])\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter((x: any) => x && typeof x.title === \"string\" && typeof x.path === \"string\")\n .map((x: any) => ({ title: x.title, path: x.path }))\n } catch {\n return []\n }\n}\n\nasync function runClaude(prompt: string, model: string, timeoutMs: number): Promise<string> {\n // Use stdin via a temp-file pipe to avoid shell-escaping a huge prompt.\n // Prompts can exceed the `-E` arg buffer on macOS, so we always pipe.\n const { writeFileSync, mkdirSync, rmSync } = await import(\"fs\")\n const { tmpdir } = await import(\"os\")\n const dir = resolve(tmpdir(), `agentx-wiki-query-${process.pid}`)\n mkdirSync(dir, { recursive: true })\n const promptPath = resolve(dir, `prompt-${Date.now()}.txt`)\n writeFileSync(promptPath, prompt)\n try {\n const cmd = `cat '${promptPath}' | claude -p - --output-format json --max-turns 1 --model ${model} --disallowedTools \"Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit\"`\n const raw = execSync(cmd, { env: claudeCliEnv(), encoding: \"utf-8\", timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })\n try {\n const envelope = JSON.parse(raw)\n return String(envelope.result || envelope.content || \"\")\n } catch {\n return raw\n }\n } finally {\n try { rmSync(promptPath, { force: true }) } catch {}\n }\n}\n"],"mappings":"iNAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KAEzCC,IAWA,OAAS,WAAAC,MAAe,OACxB,OAAS,YAAAC,MAAgB,gBAiEzB,eAAsBC,GACpBC,EACAC,EACAC,EACAC,EAA4B,CAAC,EACA,CAC7B,IAAMC,EAAgBD,EAAK,eAAiB,QACtCE,EAAa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IAAI,EACxD,CAAE,OAAAC,CAAO,EAAI,KAAM,QAAO,IAAI,EAC9BC,EAAMhG,EAAQ+F,EAAO,EAAG,qBAAqB,QAAQ,KAAK,EAChEF,EAAUG,EAAK,CAAE,UAAW,EAAK,CAAC,EAClC,IAAMC,EAAajG,EAAQgG,EAAK,UAAU,KAAK,IAAI,OAAO,EAC1DJ,EAAcK,EAAYP,CAAM,EAChC,GAAI,CACF,IAAMQ,EAAM,QAAQD,+DAAwEN,6FACtFJ,EAAMtF,EAASiG,EAAK,CAAE,IAAKC,EAAa,EAAG,SAAU,QAAS,QAASvF,EAAW,UAAW,EAAI,KAAO,IAAK,CAAC,EACpH,GAAI,CACF,IAAMwF,EAAW,KAAK,MAAMb,CAAG,EAC/B,OAAO,OAAOa,EAAS,QAAUA,EAAS,SAAW,EAAE,CACzD,MAAE,CACA,OAAOb,CACT,CACF,QAAE,CACA,GAAI,CAAEO,EAAOG,EAAY,CAAE,MAAO,EAAK,CAAC,CAAE,MAAE,CAAO,CACrD,CACF","names":["readFileSync","existsSync","init_seat","resolve","execSync","agenticQuery","question","store","requesterId","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","existsSync","emptyResult","catalog","readFileSync","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","catalogPool","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","retrieveArticles","pool","matched","scoreAll","buildIndex","catalogDoc","r","rankCatalogPool","i","status","_question","error","titleIndex","article","opened","frontier","next","target","path","stage","DEFAULT_SHORTLIST","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","bm25","maxBm25","m","text","useGraph","branch","ancestryScore","byScore","x","y","branchOnly","ranked","articles","articlesBlock","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","claudeCliEnv","envelope"]}
@@ -1,51 +0,0 @@
1
- import{b as j}from"./chunk-2C3X6DVD.js";async function q(t,r,i,s,o={}){let e=o.retrieve??j,u=o.perEntry??2,l=o.maxArticles??8,p=o.queryChars??1500,m=new Map;for(let d of t){let n=[];try{n=await e(d.content.slice(0,p),r,i,{pool:s,maxCandidates:u,maxHops:1,maxArticles:u*2,stage:"absorb-covering"})}catch{}for(let a of n){let g=m.get(a.path);g?(g.hop=Math.min(g.hop,a.hop),g.entries.includes(d.id)||g.entries.push(d.id)):m.set(a.path,{...a,entries:[d.id]})}}return[...m.values()].sort((d,n)=>d.hop-n.hop||n.entries.length-d.entries.length||d.path.localeCompare(n.path)).slice(0,l)}function B(t){if(t.length===0)return"";let r=t.map(i=>{let s=`### ${i.meta.title} \u2014 ${i.meta.type||"untyped"} (${i.path})`,o=`Found for entries: ${i.entries.join(", ")}${i.hop>0?" (linked from a match)":""}`,e=i.meta.related?.length?`Related: ${i.meta.related.join(", ")}`:"";return[s,o,e,"",i.content].filter(u=>u!=="").join(`
2
- `)}).join(`
3
-
4
- ---
5
-
6
- `);return`
7
- ## Articles already covering these entries
8
-
9
- These ${t.length} articles were found by searching the wiki for each entry below. Read them before you write.
10
-
11
- - When an entry is about the subject of one of these articles, UPDATE that article: write it at the SAME path with the SAME title, carrying its full content merged with what the entry adds.
12
- - Keep every fact the article already has: commit hashes, URLs, numbers, dates and [[wikilinks]]. Restructure freely, but do not drop one unless an entry explicitly says it is wrong. A save that drops one is refused and the entries stay queued.
13
- - Do not create a second article (a new path or a near-identical title) for a subject one of these already covers.
14
-
15
- ${r}
16
- `}var M=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,R=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,x=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,P=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,U=/^\s*\d+[.)]\s/gm;function f(t){let r=[...t.matchAll(M)].map(l=>l[0].replace(/[.,;:!?'"]+$/,"")),i=[...t.matchAll(R)].map(l=>l[1].trim()),s=t.replace(M," ").replace(R," ").replace(U," "),o=[...s.matchAll(x)].map(l=>l[0].toLowerCase()),u=[...s.replace(x," ").matchAll(P)].map(l=>D(l[0]));return{commits:$(o),urls:$(r),wikilinks:$(i),numbers:$(u)}}function V(t,r){let i=f(t),s=f(r),o=r.toLowerCase(),e=[];for(let d of i.commits)!o.includes(d)&&!s.commits.some(n=>n.startsWith(d)||d.startsWith(n))&&e.push(`commit ${d}`);let u=d=>d.toLowerCase().replace(/\/+$/,""),l=new Set(s.urls.map(u));for(let d of i.urls)l.has(u(d))||e.push(`link ${d}`);let p=new Set(s.wikilinks.map(d=>d.toLowerCase()));for(let d of i.wikilinks)p.has(d.toLowerCase())||e.push(`link [[${d}]]`);let m=new Set(s.numbers);for(let d of i.numbers)m.has(d)||e.push(`number ${d}`);return e}function D(t){return/^\d{1,3}(,\d{3})+$/.test(t)?t.replace(/,/g,""):t}function $(t){return[...new Set(t)]}function Y(t,r){if(r.some(s=>s.path===t.path))return t.path;let i=E(t.title);return i?r.find(s=>E(s.title)===i)?.path??t.path:t.path}function E(t){return(t||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}function I(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 i=r>>>0;return()=>{i=i+1831565813>>>0;let s=i;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function Q(t,r,i){let s=I(i),o=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=o.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[o[e],o[u]]=[o[u],o[e]]}return o.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var F=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 S(t){let r=new Set;for(let i of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))F.has(i[0])||r.add(i[0]);return r}function J(t,r){let i=S(t);if(i.size===0)return 1;let s=S(r),o=0;for(let e of i)s.has(e)&&o++;return o/i.size}var _=.15;function k(t){let r=f(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function v(t,r,i){return t.includes(r)||i.some(s=>s.startsWith(r)||r.startsWith(s))}var w=t=>t.toLowerCase().replace(/\/+$/,"");function X(t,r,i){let s=t.sources.map(c=>r.get(c)).filter(c=>!!c),o=t.sources.filter(c=>!r.has(c)),e=s.filter(c=>S(c.content).size>=5&&J(c.content,t.content)<_).map(c=>c.id),u=[...s.map(c=>`${c.date??""}
17
- ${c.content}`),t.previous??""].join(`
18
- `),l=u.toLowerCase(),p=k(u),m=new Set(p.urls.map(w)),d=new Set(p.numbers),n=k(t.content),a=[];for(let c of n.commits)v(l,c,p.commits)||a.push(`commit ${c}`);for(let c of n.urls)!m.has(w(c))&&!l.includes(w(c))&&a.push(`link ${c}`);for(let c of n.numbers)/^\d{1,2}$/.test(c)||!d.has(c)&&!l.includes(c)&&a.push(`number ${c}`);let g=[];for(let c of s){let h=k(c.content);if(h.commits.length===0&&h.urls.length===0)continue;let C=i(c.id),A=(C.length>0?C:[t.content]).join(`
19
- `).toLowerCase(),N=k(A);for(let y of h.commits)v(A,y,N.commits)||g.push({entry:c.id,fact:`commit ${y}`});for(let y of h.urls)A.includes(w(y))||g.push({entry:c.id,fact:`link ${y}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:o,weakSources:e,ungrounded:a,lost:g}}function Z(t,r){let i=r.toLowerCase(),s=f(r).commits,o=[];for(let e of t){let u=f(e.content),l=[...u.commits.filter(p=>!v(i,p,s)).map(p=>`commit ${p}`),...u.urls.filter(p=>!i.includes(w(p))).map(p=>`link ${p}`)];l.length>0&&o.push({entry:e.id,facts:l})}return o}var z=new Set("the and for with from into of on in at to by an a".split(" "));function K(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!z.has(r)&&!F.has(r)))}function W(t,r){if(t.size===0||r.size===0)return 0;let i=0;for(let s of t)r.has(s)&&i++;return i/(t.size+r.size-i)}function tt(t,r,i={}){let s=i.titleMin??.75,o=i.sourcesMin??.5,e=t.map(l=>({...l,tt:K(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let p=l+1;p<e.length;p++){let m=e[l],d=e[p];if(r&&!r.has(m.path)&&!r.has(d.path))continue;let n=(m.type??"")===(d.type??"")?W(m.tt,d.tt):0;if(n>=s){u.push({a:m.path,b:d.path,reason:"title",score:n});continue}if(m.ss.size>=2&&d.ss.size>=2){let a=W(m.ss,d.ss);a>=o&&u.push({a:m.path,b:d.path,reason:"sources",score:a})}}return u.sort((l,p)=>p.score-l.score||l.a.localeCompare(p.a))}var L=4e3;function et(t,r){let i=r.map(o=>{let e=o.content.length>L?`${o.content.slice(0,L)}
20
- [\u2026cut]`:o.content;return`--- ENTRY ${o.id} [${o.date??""}] ---
21
- ${e}
22
- --- END ENTRY ---`}).join(`
23
-
24
- `),s=t.previous?`
25
- ## Earlier version of the article (facts here count as supported)
26
-
27
- ${t.previous}
28
- `:"";return`You are auditing one wiki article against the raw entries it cites. Do not use outside knowledge.
29
-
30
- ## Article: ${t.title} (${t.type??"untyped"}, ${t.path})
31
-
32
- ${t.content}
33
- ${s}
34
- ## Cited entries (${r.length})
35
-
36
- ${i||"(none)"}
37
-
38
- ## What to report
39
-
40
- 1. Split the article into factual claims (one per sentence or bullet; skip headings and "unknown" placeholders). Count them.
41
- 2. A claim is supported when a cited entry or the earlier version states it or plainly implies it. List each claim that is not supported, quoted briefly.
42
- 3. List each claim an entry contradicts.
43
- 4. List the cited entry ids that are about a different subject than the article (they were merged in by mistake).
44
- 5. List facts from the entries that belong in this article and are missing (names, numbers, identifiers, decisions). Ignore small talk.
45
- 6. Verdict: "good" (nothing wrong), "minor" (wording or a small omission), "major" (an unsupported or contradicted fact, a wrong merge, or a lost identifier).
46
-
47
- Reply with JSON only, no fencing:
48
- {"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function nt(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,i=l=>Array.isArray(l)?l.map(p=>String(p)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,o=s(r.claims);if(Number.isNaN(o))return null;let e=Math.min(o,Number.isNaN(s(r.supported))?o-i(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:o,supported:Math.max(0,e),unsupported:i(r.unsupported),contradicted:i(r.contradicted),offSubject:i(r.off_subject??r.offSubject),missing:i(r.missing),verdict:u}:null}function rt(t,r,i,s=[],o=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,p=new Set;for(let n of t)for(let a of n.lost)l.add(a.entry),p.add(`${a.entry}|${a.fact}`);let m=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(a=>a.path===n))),d={sample:{articles:t.length,seed:i.seed,since:i.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,a)=>n+a.missingSources.length,0),weakSources:t.reduce((n,a)=>n+a.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,a)=>n+a.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:p.size},duplicates:{pairs:r.length,articlesInPair:m.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,o).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(a=>({path:n.path,...a}))).slice(0,o),weak:t.filter(n=>n.weakSources.length>0).slice(0,o).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,o),uncited:(e?.lost??[]).slice(0,o).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,o).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(c=>c.verdict),a=n.reduce((c,h)=>c+h.claims,0),g=n.reduce((c,h)=>c+h.supported,0);d.judge={judged:n.length,claims:a,supported:g,supportRate:a>0?g/a:1,unsupported:n.reduce((c,h)=>c+h.unsupported.length,0),contradicted:n.reduce((c,h)=>c+h.contradicted.length,0),articlesWithWrongMerge:n.filter(c=>c.offSubject.length>0).length,missingFacts:n.reduce((c,h)=>c+h.missing.length,0),verdicts:{good:n.filter(c=>c.verdict==="good").length,minor:n.filter(c=>c.verdict==="minor").length,major:n.filter(c=>c.verdict==="major").length}}}return d}var b=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function st(t){let r=t.sample.articles,i=["# 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} (${b(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(_*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${b(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${b(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} (${b(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&i.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;i.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${b(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} (${b(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,o=(e,u)=>{u.length!==0&&i.push("",`## ${e}`,"",...u)};return o("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),o("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),o("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),o("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),o("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),o("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("; ")}`})),i.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."),i.join(`
49
- `)+`
50
- `}function it(t){if(!t||typeof t!="object")return{};let r=t,i=r.usage??{},s=o=>typeof o=="number"&&Number.isFinite(o)?o:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(i.input_tokens),outputTokens:s(i.output_tokens),cacheReadTokens:s(i.cache_read_input_tokens),cacheWriteTokens:s(i.cache_creation_input_tokens)}}function T(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function ot(t){let r=new Map,i=o=>{let e=o||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let o of t)o.kind==="call"?i(o.label).calls.push(o):o.kind==="run"&&i(o.label).runs.push(o);let s=[];for(let[o,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,a)=>n-a),p;if(u.length>0)p=u.reduce((n,a)=>n+(Date.parse(a.endedAt)-Date.parse(a.startedAt)),0);else{let n=e.map(g=>Date.parse(g.at)-g.wallMs),a=e.map(g=>Date.parse(g.at));p=Math.max(...a)-Math.min(...n)}let m=e.reduce((n,a)=>n+a.entries,0),d=e.reduce((n,a)=>n+(a.costUsd??0),0);s.push({label:o,calls:e.length,failed:e.filter(n=>n.failed).length,entries:m,articles:e.reduce((n,a)=>n+a.articles,0),refused:e.reduce((n,a)=>n+a.refused,0),heldCited:e.reduce((n,a)=>n+(a.heldCited??0),0),wallMs:p,callMsP50:T(l,.5),callMsP95:T(l,.95),prepMs:e.reduce((n,a)=>n+(a.prepMs??0),0),costUsd:d,costPerEntry:m>0?d/m:0,entriesPerMinute:p>0?m/p*6e4:0,promptChars:e.reduce((n,a)=>n+a.promptChars,0)})}return s.sort((o,e)=>o.label.localeCompare(e.label))}export{q as a,B as b,V as c,Y as d,I as e,Q as f,S as g,J as h,_ as i,X as j,Z as k,tt as l,L as m,et as n,nt as o,rt as p,st as q,it as r,ot as s};
51
- //# sourceMappingURL=chunk-2W3X6H7Z.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/wiki/absorb-context.ts","../src/wiki/absorb-eval.ts"],"sourcesContent":["// What `agentx wiki absorb` knows about the wiki before it writes (#801).\n//\n// Absorb used to show the model the catalog — titles and paths — and\n// nothing else. In the 2026-10-07 A/B one model rewrote an existing event\n// article it had never read and lost the commit, the test count and the\n// review URL; the other wrote a second event article beside the first.\n// Both are what a writer does when it cannot see the page it is editing.\n//\n// So before the compile call, each entry is run through the wiki query\n// retrieval (BM25 shortlist, rerank seat, wikilink walk) and the articles\n// it lands on go into the prompt in full. After the call, a save that\n// would drop a commit, link or number from the article it replaces is\n// refused, and a new article whose title an existing one already has is\n// written over that one instead of beside it.\n\nimport { retrieveArticles, type CatalogEntry } from \"./query\"\nimport type { WikiArticle } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\nexport type CoveringArticle = WikiArticle & { hop: number; entries: string[] }\n\nexport interface FindCoveringOptions {\n /** Articles picked per entry before the walk. Default 2. */\n perEntry?: number\n /** Cap on articles across the batch. Default 8. */\n maxArticles?: number\n /** Query text taken from each entry. Default 1500 chars. */\n queryChars?: number\n /** Swappable for tests. */\n retrieve?: typeof retrieveArticles\n}\n\n/**\n * The existing articles a batch of entries is about. Each entry is its own\n * query, so one batch mixing three subjects finds all three. Articles\n * picked directly (hop 0) and by more entries come first.\n */\nexport async function findCoveringArticles(\n entries: Array<{ id: string; content: string }>,\n store: WikiStore,\n agentId: string,\n pool: CatalogEntry[],\n opts: FindCoveringOptions = {},\n): Promise<CoveringArticle[]> {\n const retrieve = opts.retrieve ?? retrieveArticles\n const perEntry = opts.perEntry ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const queryChars = opts.queryChars ?? 1500\n const found = new Map<string, CoveringArticle>()\n\n for (const entry of entries) {\n let hits: Array<WikiArticle & { hop: number }> = []\n try {\n hits = await retrieve(entry.content.slice(0, queryChars), store, agentId, {\n pool,\n maxCandidates: perEntry,\n maxHops: 1,\n maxArticles: perEntry * 2,\n stage: \"absorb-covering\",\n })\n } catch {\n // Retrieval is an aid; an absorb without it is the old absorb.\n }\n for (const hit of hits) {\n const seen = found.get(hit.path)\n if (seen) {\n seen.hop = Math.min(seen.hop, hit.hop)\n if (!seen.entries.includes(entry.id)) seen.entries.push(entry.id)\n } else {\n found.set(hit.path, { ...hit, entries: [entry.id] })\n }\n }\n }\n\n return [...found.values()]\n .sort((a, b) => a.hop - b.hop || b.entries.length - a.entries.length || a.path.localeCompare(b.path))\n .slice(0, maxArticles)\n}\n\n/** The prompt section carrying the covering articles, in full. Articles are\n * never cut short: the drop-guard checks the whole old article, so the\n * model must have seen all of it. */\nexport function renderCoveringBlock(articles: CoveringArticle[]): string {\n if (articles.length === 0) return \"\"\n const body = articles\n .map((a) => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path})`\n const why = `Found for entries: ${a.entries.join(\", \")}${a.hop > 0 ? \" (linked from a match)\" : \"\"}`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, why, related, \"\", a.content].filter((l) => l !== \"\").join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n return `\n## Articles already covering these entries\n\nThese ${articles.length} articles were found by searching the wiki for each entry below. Read them before you write.\n\n- When an entry is about the subject of one of these articles, UPDATE that article: write it at the SAME path with the SAME title, carrying its full content merged with what the entry adds.\n- Keep every fact the article already has: commit hashes, URLs, numbers, dates and [[wikilinks]]. Restructure freely, but do not drop one unless an entry explicitly says it is wrong. A save that drops one is refused and the entries stay queued.\n- Do not create a second article (a new path or a near-identical title) for a subject one of these already covers.\n\n${body}\n`\n}\n\n// --- Drop-guard ---\n\nexport interface ArticleFacts {\n commits: string[]\n urls: string[]\n wikilinks: string[]\n numbers: string[]\n}\n\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)\\]]+/gi\nconst WIKILINK_RE = /\\[\\[([^\\]|]+)(?:\\|[^\\]]*)?\\]\\]/g\n// A short or full git hash: 7–40 hex chars holding at least one digit and\n// one letter, so words like \"defaced\" and plain numbers are not hashes.\nconst COMMIT_RE = /(?<![\\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\\w-])/gi\n// A number standing on its own: \"12\", \"1,234\", \"3.5\", \"2026-10-07\", \"14:30\",\n// \"v2\"-style suffixes excluded by the look-behind.\nconst NUMBER_RE = /(?<![\\w.,:/-])\\d+(?:[.,:\\-/]\\d+)*(?![\\w])/g\nconst LIST_MARKER_RE = /^\\s*\\d+[.)]\\s/gm\n\n/** The facts a rewrite must not lose, extracted from an article body. */\nexport function extractFacts(text: string): ArticleFacts {\n const urls = [...text.matchAll(URL_RE)].map((m) => m[0].replace(/[.,;:!?'\"]+$/, \"\"))\n const wikilinks = [...text.matchAll(WIKILINK_RE)].map((m) => m[1].trim())\n // Hashes and numbers are read with URLs and wikilink targets removed, so\n // a path segment or \"Release 2\" in a link is not counted twice.\n const rest = text.replace(URL_RE, \" \").replace(WIKILINK_RE, \" \").replace(LIST_MARKER_RE, \" \")\n const commits = [...rest.matchAll(COMMIT_RE)].map((m) => m[0].toLowerCase())\n const withoutCommits = rest.replace(COMMIT_RE, \" \")\n const numbers = [...withoutCommits.matchAll(NUMBER_RE)]\n .map((m) => normaliseNumber(m[0]))\n return {\n commits: unique(commits),\n urls: unique(urls),\n wikilinks: unique(wikilinks),\n numbers: unique(numbers),\n }\n}\n\n/**\n * The facts in `oldContent` that `newContent` no longer carries. Empty\n * means the rewrite is safe to save.\n *\n * A short hash is kept when the new text has it at any length; a URL or\n * wikilink is compared without case or trailing slash; a number is\n * compared as a token (thousands separators ignored), so \"12\" is not\n * found inside \"2012\".\n */\nexport function droppedFacts(oldContent: string, newContent: string): string[] {\n const before = extractFacts(oldContent)\n const after = extractFacts(newContent)\n const lowerNew = newContent.toLowerCase()\n const dropped: string[] = []\n\n for (const c of before.commits) {\n if (!lowerNew.includes(c) && !after.commits.some((n) => n.startsWith(c) || c.startsWith(n))) {\n dropped.push(`commit ${c}`)\n }\n }\n const urlKey = (u: string) => u.toLowerCase().replace(/\\/+$/, \"\")\n const newUrls = new Set(after.urls.map(urlKey))\n for (const u of before.urls) {\n if (!newUrls.has(urlKey(u))) dropped.push(`link ${u}`)\n }\n const newLinks = new Set(after.wikilinks.map((l) => l.toLowerCase()))\n for (const l of before.wikilinks) {\n if (!newLinks.has(l.toLowerCase())) dropped.push(`link [[${l}]]`)\n }\n const newNumbers = new Set(after.numbers)\n for (const n of before.numbers) {\n if (!newNumbers.has(n)) dropped.push(`number ${n}`)\n }\n return dropped\n}\n\nfunction normaliseNumber(n: string): string {\n // 1,234 → 1234; leave 3,5 (a decimal comma) and dates alone.\n return /^\\d{1,3}(,\\d{3})+$/.test(n) ? n.replace(/,/g, \"\") : n\n}\n\nfunction unique(list: string[]): string[] {\n return [...new Set(list)]\n}\n\n// --- Duplicate redirect ---\n\n/**\n * Where an absorbed article is written. A new path whose title an existing\n * article already carries is the same subject filed twice, so it goes to\n * the existing article — where the drop-guard then applies.\n */\nexport function absorbTargetPath(\n article: { path: string; title: string },\n catalog: Array<{ path: string; title: string }>,\n): string {\n if (catalog.some((a) => a.path === article.path)) return article.path\n const key = titleKey(article.title)\n if (!key) return article.path\n return catalog.find((a) => titleKey(a.title) === key)?.path ?? article.path\n}\n\nfunction titleKey(title: string): string {\n return (title || \"\").toLowerCase().replace(/[^\\p{L}\\p{N}]+/gu, \" \").trim()\n}\n","// Measuring what `agentx wiki absorb` writes (#808).\n//\n// Absorb turns raw entries into articles, and until now nothing checked\n// the result against the entries it came from. This module is the\n// scorecard: a fixed, seeded sample of articles, five checks per article,\n// and an optional model judge for the questions a string match cannot\n// answer (is this claim supported, does this source belong here).\n//\n// The deterministic checks are deliberately narrow. A commit hash or URL\n// in an article that no cited entry and no earlier version carries is\n// almost certainly made up or mis-attributed; a commit or URL in a cited\n// entry that no article carries was almost certainly lost. Prose claims\n// are left to the judge.\n\nimport { extractFacts } from \"./absorb-context\"\n\nexport interface EvalArticle {\n path: string\n title: string\n type?: string\n content: string\n sources: string[]\n lastUpdated?: string\n /** The article body before this absorb touched it, when one exists. */\n previous?: string\n}\n\nexport interface EvalEntry {\n id: string\n date?: string\n content: string\n}\n\n// --- Sample ---\n\n/** A small seeded PRNG, so a sample can be drawn again from the same seed. */\nexport function seededRandom(seed: string): () => number {\n let h = 1779033703 ^ seed.length\n for (let i = 0; i < seed.length; i++) {\n h = Math.imul(h ^ seed.charCodeAt(i), 3432918353)\n h = (h << 13) | (h >>> 19)\n }\n let a = h >>> 0\n return () => {\n a = (a + 0x6d2b79f5) >>> 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** `n` items picked without replacement. Same items and seed, same pick. */\nexport function pickSample<T extends { path: string }>(items: T[], n: number, seed: string): T[] {\n const rng = seededRandom(seed)\n const pool = [...items].sort((a, b) => a.path.localeCompare(b.path))\n for (let i = pool.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1))\n ;[pool[i], pool[j]] = [pool[j], pool[i]]\n }\n return pool.slice(0, Math.max(0, n)).sort((a, b) => a.path.localeCompare(b.path))\n}\n\n// --- Terms ---\n\nconst STOP = new Set(\n (\"about after again also because been before being between could does doing during each from have having here into \"\n + \"just more most only other over same should some such than that their them then there these they this those \"\n + \"through under until very were what when where which while will with would your yours user assistant agent \"\n + \"message entry please thanks\").split(\" \"),\n)\n\n/** Distinctive words: four letters or more, lower-cased, minus common ones. */\nexport function terms(text: string): Set<string> {\n const out = new Set<string>()\n for (const m of text.toLowerCase().matchAll(/[\\p{L}\\p{N}][\\p{L}\\p{N}_-]{3,}/gu)) {\n if (!STOP.has(m[0])) out.add(m[0])\n }\n return out\n}\n\n/** Share of `entry`'s distinctive words that appear in `article`. */\nexport function termOverlap(entry: string, article: string): number {\n const e = terms(entry)\n if (e.size === 0) return 1\n const a = terms(article)\n let hit = 0\n for (const t of e) if (a.has(t)) hit++\n return hit / e.size\n}\n\n// --- Per-article checks ---\n\n/** Below this share of shared words a cited entry is flagged as weak. */\nexport const WEAK_CITATION = 0.15\n\nexport interface ArticleCheck {\n path: string\n title: string\n type?: string\n sources: number\n /** Cited ids with no entry behind them. */\n missingSources: string[]\n /** Cited entries that share almost no words with the article. */\n weakSources: string[]\n /** Commits, links and numbers in the article that neither a cited entry\n * nor the earlier version carries. */\n ungrounded: string[]\n /** Commits and links in a cited entry that no article citing it carries. */\n lost: Array<{ entry: string; fact: string }>\n}\n\n/** What a fact looks like when matched against grounding text. */\nfunction factStrings(text: string): { commits: string[]; urls: string[]; numbers: string[] } {\n const f = extractFacts(text)\n return { commits: f.commits, urls: f.urls, numbers: f.numbers }\n}\n\nfunction hasCommit(haystack: string, commit: string, known: string[]): boolean {\n return haystack.includes(commit) || known.some((k) => k.startsWith(commit) || commit.startsWith(k))\n}\n\nconst urlKey = (u: string) => u.toLowerCase().replace(/\\/+$/, \"\")\n\n/**\n * Check one article against its cited entries.\n *\n * `citersOf` returns every article (in the whole wiki, not only the\n * sample) that cites an entry, so a fact moved to a sibling article is\n * not counted as lost.\n */\nexport function checkArticle(\n article: EvalArticle,\n entries: Map<string, EvalEntry>,\n citersOf: (entryId: string) => string[],\n): ArticleCheck {\n const cited = article.sources.map((id) => entries.get(id)).filter((e): e is EvalEntry => !!e)\n const missingSources = article.sources.filter((id) => !entries.has(id))\n\n const weakSources = cited\n .filter((e) => terms(e.content).size >= 5 && termOverlap(e.content, article.content) < WEAK_CITATION)\n .map((e) => e.id)\n\n // Grounding: entry text with its date (absorb is shown the date in the\n // entry header), plus the earlier version of the article.\n const grounding = [...cited.map((e) => `${e.date ?? \"\"}\\n${e.content}`), article.previous ?? \"\"].join(\"\\n\")\n const groundLower = grounding.toLowerCase()\n const g = factStrings(grounding)\n const groundUrls = new Set(g.urls.map(urlKey))\n const groundNumbers = new Set(g.numbers)\n const mine = factStrings(article.content)\n const ungrounded: string[] = []\n for (const c of mine.commits) if (!hasCommit(groundLower, c, g.commits)) ungrounded.push(`commit ${c}`)\n for (const u of mine.urls) if (!groundUrls.has(urlKey(u)) && !groundLower.includes(urlKey(u))) ungrounded.push(`link ${u}`)\n for (const n of mine.numbers) {\n // Bare small integers (\"2 tests\", \"3 people\") are too common to judge.\n if (/^\\d{1,2}$/.test(n)) continue\n if (!groundNumbers.has(n) && !groundLower.includes(n)) ungrounded.push(`number ${n}`)\n }\n\n const lost: Array<{ entry: string; fact: string }> = []\n for (const e of cited) {\n const facts = factStrings(e.content)\n if (facts.commits.length === 0 && facts.urls.length === 0) continue\n const carriers = citersOf(e.id)\n const text = (carriers.length > 0 ? carriers : [article.content]).join(\"\\n\").toLowerCase()\n const carrierFacts = factStrings(text)\n for (const c of facts.commits) if (!hasCommit(text, c, carrierFacts.commits)) lost.push({ entry: e.id, fact: `commit ${c}` })\n for (const u of facts.urls) if (!text.includes(urlKey(u))) lost.push({ entry: e.id, fact: `link ${u}` })\n }\n\n return {\n path: article.path,\n title: article.title,\n type: article.type,\n sources: article.sources.length,\n missingSources,\n weakSources,\n ungrounded,\n lost,\n }\n}\n\n// --- Uncited entries ---\n\n/**\n * Entries absorb read and cited nowhere that carry a commit or link no\n * article on the node has. A successful run marks every entry it read as\n * done (#762), so a fact in an entry the model passed over is gone from\n * the queue for good; the per-article \"lost\" check cannot see it because\n * no article points back at the entry.\n */\nexport function uncitedWithFacts(\n uncited: EvalEntry[],\n allArticles: string,\n): Array<{ entry: string; facts: string[] }> {\n const lower = allArticles.toLowerCase()\n const known = extractFacts(allArticles).commits\n const out: Array<{ entry: string; facts: string[] }> = []\n for (const e of uncited) {\n const f = extractFacts(e.content)\n const missing = [\n ...f.commits.filter((c) => !hasCommit(lower, c, known)).map((c) => `commit ${c}`),\n ...f.urls.filter((u) => !lower.includes(urlKey(u))).map((u) => `link ${u}`),\n ]\n if (missing.length > 0) out.push({ entry: e.id, facts: missing })\n }\n return out\n}\n\n// --- Duplicates ---\n\nexport interface DuplicatePair {\n a: string\n b: string\n reason: \"title\" | \"sources\"\n score: number\n}\n\nconst TITLE_STOP = new Set(\"the and for with from into of on in at to by an a\".split(\" \"))\n\nfunction titleTerms(title: string): Set<string> {\n return new Set(\n (title || \"\").toLowerCase().split(/[^\\p{L}\\p{N}]+/u).filter((w) => (w.length > 1 || /\\d/.test(w)) && !TITLE_STOP.has(w) && !STOP.has(w)),\n )\n}\n\nfunction jaccard<T>(a: Set<T>, b: Set<T>): number {\n if (a.size === 0 || b.size === 0) return 0\n let inter = 0\n for (const x of a) if (b.has(x)) inter++\n return inter / (a.size + b.size - inter)\n}\n\n/**\n * Pairs of articles that look like one subject filed twice: the same type\n * and near-identical title words, or most of their sources in common.\n * Only pairs touching `focus` are returned when it is given.\n */\nexport function findDuplicates(\n catalog: Array<{ path: string; title: string; type?: string; sources?: string[] }>,\n focus?: Set<string>,\n opts: { titleMin?: number; sourcesMin?: number } = {},\n): DuplicatePair[] {\n const titleMin = opts.titleMin ?? 0.75\n const sourcesMin = opts.sourcesMin ?? 0.5\n const rows = catalog.map((a) => ({ ...a, tt: titleTerms(a.title), ss: new Set(a.sources ?? []) }))\n const pairs: DuplicatePair[] = []\n for (let i = 0; i < rows.length; i++) {\n for (let j = i + 1; j < rows.length; j++) {\n const x = rows[i], y = rows[j]\n if (focus && !focus.has(x.path) && !focus.has(y.path)) continue\n const t = (x.type ?? \"\") === (y.type ?? \"\") ? jaccard(x.tt, y.tt) : 0\n if (t >= titleMin) { pairs.push({ a: x.path, b: y.path, reason: \"title\", score: t }); continue }\n if (x.ss.size >= 2 && y.ss.size >= 2) {\n const s = jaccard(x.ss, y.ss)\n if (s >= sourcesMin) pairs.push({ a: x.path, b: y.path, reason: \"sources\", score: s })\n }\n }\n }\n return pairs.sort((p, q) => q.score - p.score || p.a.localeCompare(q.a))\n}\n\n// --- Model judge ---\n\nexport interface JudgeVerdict {\n claims: number\n supported: number\n unsupported: string[]\n contradicted: string[]\n /** Cited entry ids that are about a different subject (a wrong merge). */\n offSubject: string[]\n /** Facts in the entries that belong in this article and are missing. */\n missing: string[]\n verdict: \"good\" | \"minor\" | \"major\"\n}\n\n/** Per-entry cap in the judge prompt, so one long transcript cannot crowd out the rest. */\nexport const JUDGE_ENTRY_CHARS = 4000\n\nexport function buildJudgePrompt(article: EvalArticle, entries: EvalEntry[]): string {\n const sourceBlock = entries\n .map((e) => {\n const body = e.content.length > JUDGE_ENTRY_CHARS ? `${e.content.slice(0, JUDGE_ENTRY_CHARS)}\\n[…cut]` : e.content\n return `--- ENTRY ${e.id} [${e.date ?? \"\"}] ---\\n${body}\\n--- END ENTRY ---`\n })\n .join(\"\\n\\n\")\n const earlier = article.previous\n ? `\\n## Earlier version of the article (facts here count as supported)\\n\\n${article.previous}\\n`\n : \"\"\n return `You are auditing one wiki article against the raw entries it cites. Do not use outside knowledge.\n\n## Article: ${article.title} (${article.type ?? \"untyped\"}, ${article.path})\n\n${article.content}\n${earlier}\n## Cited entries (${entries.length})\n\n${sourceBlock || \"(none)\"}\n\n## What to report\n\n1. Split the article into factual claims (one per sentence or bullet; skip headings and \"unknown\" placeholders). Count them.\n2. A claim is supported when a cited entry or the earlier version states it or plainly implies it. List each claim that is not supported, quoted briefly.\n3. List each claim an entry contradicts.\n4. List the cited entry ids that are about a different subject than the article (they were merged in by mistake).\n5. List facts from the entries that belong in this article and are missing (names, numbers, identifiers, decisions). Ignore small talk.\n6. Verdict: \"good\" (nothing wrong), \"minor\" (wording or a small omission), \"major\" (an unsupported or contradicted fact, a wrong merge, or a lost identifier).\n\nReply with JSON only, no fencing:\n{\"claims\": 0, \"supported\": 0, \"unsupported\": [], \"contradicted\": [], \"off_subject\": [], \"missing\": [], \"verdict\": \"good\"}`\n}\n\nexport function parseJudgeReply(value: unknown): JudgeVerdict | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null\n const v = value as Record<string, unknown>\n const list = (x: unknown) => (Array.isArray(x) ? x.map((s) => String(s)) : [])\n const num = (x: unknown) => (typeof x === \"number\" && Number.isFinite(x) && x >= 0 ? Math.round(x) : NaN)\n const claims = num(v.claims)\n if (Number.isNaN(claims)) return null\n const supported = Math.min(claims, Number.isNaN(num(v.supported)) ? claims - list(v.unsupported).length : num(v.supported))\n const verdict = v.verdict === \"good\" || v.verdict === \"minor\" || v.verdict === \"major\" ? v.verdict : null\n if (!verdict) return null\n return {\n claims,\n supported: Math.max(0, supported),\n unsupported: list(v.unsupported),\n contradicted: list(v.contradicted),\n offSubject: list(v.off_subject ?? v.offSubject),\n missing: list(v.missing),\n verdict,\n }\n}\n\n// --- Scorecard ---\n\nexport interface Scorecard {\n sample: { articles: number; seed: string; since?: string; byType: Record<string, number> }\n citations: { withSources: number; missingSources: number; weakSources: number; articlesWithWeak: number }\n grounding: { articlesWithUngrounded: number; ungroundedFacts: number }\n lost: { entriesWithLostFacts: number; lostFacts: number }\n duplicates: { pairs: number; articlesInPair: number }\n /** Entries read in the window that no article cites. */\n uncited?: { entries: number; withLostFacts: number }\n judge?: {\n judged: number\n claims: number\n supported: number\n supportRate: number\n unsupported: number\n contradicted: number\n articlesWithWrongMerge: number\n missingFacts: number\n verdicts: Record<\"good\" | \"minor\" | \"major\", number>\n }\n examples: {\n ungrounded: Array<{ path: string; facts: string[] }>\n lost: Array<{ path: string; entry: string; fact: string }>\n weak: Array<{ path: string; entries: string[] }>\n duplicates: DuplicatePair[]\n uncited: Array<{ entry: string; facts: string[] }>\n judged: Array<{ path: string; verdict: string; unsupported: string[]; contradicted: string[]; offSubject: string[]; missing: string[] }>\n }\n}\n\nexport function buildScorecard(\n checks: ArticleCheck[],\n duplicates: DuplicatePair[],\n meta: { seed: string; since?: string },\n judged: Array<{ path: string; verdict: JudgeVerdict }> = [],\n maxExamples = 5,\n uncited?: { entries: number; lost: Array<{ entry: string; facts: string[] }> },\n): Scorecard {\n const byType: Record<string, number> = {}\n for (const c of checks) byType[c.type ?? \"untyped\"] = (byType[c.type ?? \"untyped\"] ?? 0) + 1\n const lostEntries = new Set<string>()\n const lostKeys = new Set<string>()\n for (const c of checks) for (const l of c.lost) { lostEntries.add(l.entry); lostKeys.add(`${l.entry}|${l.fact}`) }\n const inPair = new Set(duplicates.flatMap((d) => [d.a, d.b]).filter((p) => checks.some((c) => c.path === p)))\n\n const card: Scorecard = {\n sample: { articles: checks.length, seed: meta.seed, since: meta.since, byType },\n citations: {\n withSources: checks.filter((c) => c.sources > 0).length,\n missingSources: checks.reduce((s, c) => s + c.missingSources.length, 0),\n weakSources: checks.reduce((s, c) => s + c.weakSources.length, 0),\n articlesWithWeak: checks.filter((c) => c.weakSources.length > 0).length,\n },\n grounding: {\n articlesWithUngrounded: checks.filter((c) => c.ungrounded.length > 0).length,\n ungroundedFacts: checks.reduce((s, c) => s + c.ungrounded.length, 0),\n },\n lost: { entriesWithLostFacts: lostEntries.size, lostFacts: lostKeys.size },\n duplicates: { pairs: duplicates.length, articlesInPair: inPair.size },\n ...(uncited ? { uncited: { entries: uncited.entries, withLostFacts: uncited.lost.length } } : {}),\n examples: {\n ungrounded: checks.filter((c) => c.ungrounded.length > 0).slice(0, maxExamples).map((c) => ({ path: c.path, facts: c.ungrounded.slice(0, 6) })),\n lost: checks.flatMap((c) => c.lost.map((l) => ({ path: c.path, ...l }))).slice(0, maxExamples),\n weak: checks.filter((c) => c.weakSources.length > 0).slice(0, maxExamples).map((c) => ({ path: c.path, entries: c.weakSources })),\n duplicates: duplicates.slice(0, maxExamples),\n uncited: (uncited?.lost ?? []).slice(0, maxExamples).map((u) => ({ entry: u.entry, facts: u.facts.slice(0, 4) })),\n judged: judged\n .filter((j) => j.verdict.verdict !== \"good\")\n .slice(0, maxExamples)\n .map((j) => ({\n path: j.path,\n verdict: j.verdict.verdict,\n unsupported: j.verdict.unsupported.slice(0, 4),\n contradicted: j.verdict.contradicted.slice(0, 4),\n offSubject: j.verdict.offSubject,\n missing: j.verdict.missing.slice(0, 4),\n })),\n },\n }\n\n if (judged.length > 0) {\n const v = judged.map((j) => j.verdict)\n const claims = v.reduce((s, x) => s + x.claims, 0)\n const supported = v.reduce((s, x) => s + x.supported, 0)\n card.judge = {\n judged: v.length,\n claims,\n supported,\n supportRate: claims > 0 ? supported / claims : 1,\n unsupported: v.reduce((s, x) => s + x.unsupported.length, 0),\n contradicted: v.reduce((s, x) => s + x.contradicted.length, 0),\n articlesWithWrongMerge: v.filter((x) => x.offSubject.length > 0).length,\n missingFacts: v.reduce((s, x) => s + x.missing.length, 0),\n verdicts: {\n good: v.filter((x) => x.verdict === \"good\").length,\n minor: v.filter((x) => x.verdict === \"minor\").length,\n major: v.filter((x) => x.verdict === \"major\").length,\n },\n }\n }\n return card\n}\n\nconst pct = (n: number, d: number) => (d > 0 ? `${Math.round((n / d) * 100)}%` : \"–\")\n\n/** The scorecard as Markdown, for the issue or a PR comment. */\nexport function renderScorecard(card: Scorecard): string {\n const n = card.sample.articles\n const lines = [\n `# Wiki absorb scorecard`,\n \"\",\n `Sample: ${n} articles (seed \\`${card.sample.seed}\\`${card.sample.since ? `, changed since ${card.sample.since}` : \"\"}). `\n + `Types: ${Object.entries(card.sample.byType).map(([t, k]) => `${t} ${k}`).join(\", \") || \"–\"}.`,\n \"\",\n \"| Check | Result | Lower is better? |\",\n \"|---|---|---|\",\n `| Articles citing at least one entry | ${card.citations.withSources}/${n} (${pct(card.citations.withSources, n)}) | no |`,\n `| Cited ids with no entry | ${card.citations.missingSources} | yes |`,\n `| Articles with a weak citation (entry shares <${Math.round(WEAK_CITATION * 100)}% of its words) | ${card.citations.articlesWithWeak}/${n} (${pct(card.citations.articlesWithWeak, n)}) | yes |`,\n `| Articles with an ungrounded commit, link or number | ${card.grounding.articlesWithUngrounded}/${n} (${pct(card.grounding.articlesWithUngrounded, n)}) | yes |`,\n `| Ungrounded facts | ${card.grounding.ungroundedFacts} | yes |`,\n `| Commits or links lost from cited entries | ${card.lost.lostFacts} across ${card.lost.entriesWithLostFacts} entries | yes |`,\n `| Sampled articles in a likely duplicate pair | ${card.duplicates.articlesInPair}/${n} (${pct(card.duplicates.articlesInPair, n)}) | yes |`,\n ]\n if (card.uncited) {\n lines.push(\n `| Entries read in the window but cited by no article | ${card.uncited.entries} | – |`,\n `| …of which carry a commit or link no article has | ${card.uncited.withLostFacts} | yes |`,\n )\n }\n if (card.judge) {\n const j = card.judge\n lines.push(\n `| Judge: claims supported by the cited entries | ${j.supported}/${j.claims} (${pct(j.supported, j.claims)}) | no |`,\n `| Judge: unsupported / contradicted claims | ${j.unsupported} / ${j.contradicted} | yes |`,\n `| Judge: articles with an off-subject source (wrong merge) | ${j.articlesWithWrongMerge}/${j.judged} (${pct(j.articlesWithWrongMerge, j.judged)}) | yes |`,\n `| Judge: facts missing from the article | ${j.missingFacts} | yes |`,\n `| Judge verdicts good / minor / major | ${j.verdicts.good} / ${j.verdicts.minor} / ${j.verdicts.major} | – |`,\n )\n }\n const ex = card.examples\n const section = (title: string, rows: string[]) => {\n if (rows.length === 0) return\n lines.push(\"\", `## ${title}`, \"\", ...rows)\n }\n section(\"Examples: ungrounded facts\", ex.ungrounded.map((e) => `- \\`${e.path}\\`: ${e.facts.join(\"; \")}`))\n section(\"Examples: lost facts\", ex.lost.map((e) => `- \\`${e.path}\\` ← entry \\`${e.entry}\\`: ${e.fact}`))\n section(\"Examples: weak citations\", ex.weak.map((e) => `- \\`${e.path}\\`: ${e.entries.map((x) => `\\`${x}\\``).join(\", \")}`))\n section(\"Examples: uncited entries with facts no article has\", ex.uncited.map((u) => `- \\`${u.entry}\\`: ${u.facts.join(\"; \")}`))\n section(\"Examples: likely duplicates\", ex.duplicates.map((d) => `- \\`${d.a}\\` ↔ \\`${d.b}\\` (${d.reason}, ${d.score.toFixed(2)})`))\n section(\n \"Examples: judge findings\",\n ex.judged.map((e) => {\n const parts = [\n e.unsupported.length ? `unsupported: ${e.unsupported.join(\" | \")}` : \"\",\n e.contradicted.length ? `contradicted: ${e.contradicted.join(\" | \")}` : \"\",\n e.offSubject.length ? `off-subject: ${e.offSubject.join(\", \")}` : \"\",\n e.missing.length ? `missing: ${e.missing.join(\" | \")}` : \"\",\n ].filter(Boolean)\n return `- \\`${e.path}\\` (${e.verdict}): ${parts.join(\"; \")}`\n }),\n )\n lines.push(\n \"\",\n \"## Method\",\n \"\",\n \"- 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.\",\n \"- 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.\",\n \"- Lost: a commit hash or link in a cited entry that no article citing that entry contains.\",\n \"- 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.\",\n \"- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.\",\n \"- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.\",\n \"- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items.\",\n )\n return lines.join(\"\\n\") + \"\\n\"\n}\n\n// --- Run telemetry ---\n\n/** One compile call, as appended to `_absorb-runs.jsonl`. */\nexport interface AbsorbCallRecord {\n kind: \"call\"\n at: string\n label?: string\n agent: string\n model: string\n entries: number\n articles: number\n refused: number\n /** Entries held by a refused save that another saved article cites:\n * they leave the queue, so the refused update is never retried. */\n heldCited?: number\n failed: boolean\n /** The model call alone. */\n wallMs: number\n /** Retrieval, fact lookups and prompt building before the call. */\n prepMs?: number\n promptChars: number\n promptParts?: Record<string, number>\n costUsd?: number\n apiMs?: number\n inputTokens?: number\n outputTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n}\n\n/** One whole `wiki absorb` invocation. */\nexport interface AbsorbRunRecord {\n kind: \"run\"\n label?: string\n startedAt: string\n endedAt: string\n max: number\n model: string\n}\n\n/** Cost and timing fields from the claude CLI's `--output-format json` envelope. */\nexport function envelopeUsage(envelope: unknown): Partial<AbsorbCallRecord> {\n if (!envelope || typeof envelope !== \"object\") return {}\n const e = envelope as Record<string, any>\n const u = (e.usage ?? {}) as Record<string, unknown>\n const n = (x: unknown) => (typeof x === \"number\" && Number.isFinite(x) ? x : undefined)\n return {\n costUsd: n(e.total_cost_usd) ?? n(e.cost_usd),\n apiMs: n(e.duration_api_ms),\n inputTokens: n(u.input_tokens),\n outputTokens: n(u.output_tokens),\n cacheReadTokens: n(u.cache_read_input_tokens),\n cacheWriteTokens: n(u.cache_creation_input_tokens),\n }\n}\n\nexport interface RunSummary {\n label: string\n calls: number\n failed: number\n entries: number\n articles: number\n refused: number\n heldCited: number\n /** First call start to last call end, or the run records' span when present. */\n wallMs: number\n callMsP50: number\n callMsP95: number\n /** Time spent before the model calls, summed. */\n prepMs: number\n costUsd: number\n costPerEntry: number\n entriesPerMinute: number\n promptChars: number\n}\n\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0\n return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))]\n}\n\n/** Totals per run label from the telemetry lines. Calls without a label group under \"(none)\". */\nexport function summariseRuns(records: Array<AbsorbCallRecord | AbsorbRunRecord>): RunSummary[] {\n const groups = new Map<string, { calls: AbsorbCallRecord[]; runs: AbsorbRunRecord[] }>()\n const group = (label?: string) => {\n const key = label || \"(none)\"\n let g = groups.get(key)\n if (!g) groups.set(key, (g = { calls: [], runs: [] }))\n return g\n }\n for (const r of records) {\n if (r.kind === \"call\") group(r.label).calls.push(r)\n else if (r.kind === \"run\") group(r.label).runs.push(r)\n }\n const out: RunSummary[] = []\n for (const [label, { calls, runs }] of groups) {\n if (calls.length === 0) continue\n const ms = calls.map((c) => c.wallMs).sort((a, b) => a - b)\n let wallMs: number\n if (runs.length > 0) {\n wallMs = runs.reduce((s, r) => s + (Date.parse(r.endedAt) - Date.parse(r.startedAt)), 0)\n } else {\n const starts = calls.map((c) => Date.parse(c.at) - c.wallMs)\n const ends = calls.map((c) => Date.parse(c.at))\n wallMs = Math.max(...ends) - Math.min(...starts)\n }\n const entries = calls.reduce((s, c) => s + c.entries, 0)\n const costUsd = calls.reduce((s, c) => s + (c.costUsd ?? 0), 0)\n out.push({\n label,\n calls: calls.length,\n failed: calls.filter((c) => c.failed).length,\n entries,\n articles: calls.reduce((s, c) => s + c.articles, 0),\n refused: calls.reduce((s, c) => s + c.refused, 0),\n heldCited: calls.reduce((s, c) => s + (c.heldCited ?? 0), 0),\n wallMs,\n callMsP50: percentile(ms, 0.5),\n callMsP95: percentile(ms, 0.95),\n prepMs: calls.reduce((s, c) => s + (c.prepMs ?? 0), 0),\n costUsd,\n costPerEntry: entries > 0 ? costUsd / entries : 0,\n entriesPerMinute: wallMs > 0 ? (entries / wallMs) * 60_000 : 0,\n promptChars: calls.reduce((s, c) => s + c.promptChars, 0),\n })\n }\n return out.sort((a, b) => a.label.localeCompare(b.label))\n}\n"],"mappings":"wCAqCA,eAAsBA,EACpBC,EACAC,EACAC,EACAC,EACAC,EAA4B,CAAC,EACD,CAC5B,IAAMC,EAAWD,EAAK,UAAYE,EAC5BC,EAAWH,EAAK,UAAY,EAC5BI,EAAcJ,EAAK,aAAe,EAClCK,EAAaL,EAAK,YAAc,KAChCM,EAAQ,IAAI,IAElB,QAAWC,KAASX,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,cAAcO,EAAE,KAAK,CAAC,CAC1D","names":["findCoveringArticles","entries","store","agentId","pool","opts","retrieve","retrieveArticles","perEntry","maxArticles","queryChars","found","entry","hits","hit","seen","a","b","renderCoveringBlock","articles","body","header","why","related","l","URL_RE","WIKILINK_RE","COMMIT_RE","NUMBER_RE","LIST_MARKER_RE","extractFacts","text","urls","m","wikilinks","rest","commits","numbers","normaliseNumber","unique","droppedFacts","oldContent","newContent","before","after","lowerNew","dropped","c","urlKey","u","newUrls","newLinks","newNumbers","n","list","absorbTargetPath","article","catalog","key","titleKey","title","seededRandom","seed","h","i","a","t","pickSample","items","n","rng","pool","b","j","STOP","terms","text","out","m","termOverlap","entry","article","e","hit","WEAK_CITATION","factStrings","f","extractFacts","hasCommit","haystack","commit","known","k","urlKey","u","checkArticle","entries","citersOf","cited","id","missingSources","weakSources","grounding","groundLower","g","groundUrls","groundNumbers","mine","ungrounded","lost","facts","carriers","carrierFacts","c","uncitedWithFacts","uncited","allArticles","lower","missing","TITLE_STOP","titleTerms","title","w","jaccard","inter","x","findDuplicates","catalog","focus","opts","titleMin","sourcesMin","rows","pairs","y","s","p","q","JUDGE_ENTRY_CHARS","buildJudgePrompt","sourceBlock","body","earlier","parseJudgeReply","value","v","list","num","claims","supported","verdict","buildScorecard","checks","duplicates","meta","judged","maxExamples","byType","lostEntries","lostKeys","l","inPair","d","card","pct","renderScorecard","lines","ex","section","parts","envelopeUsage","envelope","percentile","sorted","summariseRuns","records","groups","group","label","key","r","calls","runs","ms","wallMs","starts","ends","costUsd"]}
@@ -1,54 +0,0 @@
1
- import{l as U,m as F,n as Ke}from"./chunk-UIBUZ2N3.js";import{b as M,d as B,h as We}from"./chunk-BRK6M6LA.js";import{a as D,e as ze}from"./chunk-2QNT5JDS.js";import{a as g,b as He}from"./chunk-QIJLFPWE.js";import{z as i}from"zod";var Xe,Ze,Ge,Ye,Ve,Je,Qe,et,tt,H,z=g(()=>{"use strict";Xe=i.enum(["mon","tue","wed","thu","fri","sat","sun"]),Ze=i.object({days:i.array(Xe).default(["mon","tue","wed","thu","fri"]),start:i.string().regex(/^\d{2}:\d{2}$/),end:i.string().regex(/^\d{2}:\d{2}$/),lunch:i.object({start:i.string().regex(/^\d{2}:\d{2}$/),end:i.string().regex(/^\d{2}:\d{2}$/)}).optional()}),Ge=i.object({title:i.string(),responsibilities:i.array(i.string()).default([]),sopPath:i.string().optional(),kpis:i.array(i.string()).default([])}),Ye=i.object({role:i.string(),reportsTo:i.string().optional(),schedule:Ze,utilizationTarget:i.number().min(0).max(1).default(.8)}),Ve=i.object({channel:i.string(),chatId:i.string(),accountId:i.string().optional()}),Je=i.discriminatedUnion("type",[i.object({type:i.literal("backlog"),path:i.string().default(".agentx/backlog.md")}),i.object({type:i.literal("gitlab"),projects:i.array(i.string()).default([])}),i.object({type:i.literal("wiki"),path:i.string(),glob:i.string().default("**/*.md")})]),Qe=i.object({id:i.string(),pm:i.string().optional(),client:i.string().optional()}),et=i.object({channel:i.string().optional(),chatId:i.string().optional(),username:i.string().optional(),senderId:i.string().optional(),client:i.string(),project:i.string().optional(),displayName:i.string().optional()}),tt=i.object({name:i.string().optional(),kind:i.enum(["client","internal","own"]).optional(),respondWithin:i.string().optional(),standing:i.array(i.string()).default([])}),H=i.object({enabled:i.boolean().default(!1),timezone:i.string().default("UTC"),mainChannel:Ve,workSource:Je,roles:i.record(i.string(),Ge).default({}),orgChart:i.record(i.string(),Ye).default({}),projects:i.array(Qe).default([]),contactMap:i.array(et).default([]),clients:i.record(i.string(),tt).default({}),workTickMinutes:i.number().int().min(1).max(60).default(15),idleQueueThreshold:i.number().int().min(0).default(0),standup:i.object({enabled:i.boolean().default(!0),plansDir:i.string().default(".agentx/plans"),maxAgentsPerDay:i.number().int().min(1).max(100).default(20),dryRun:i.boolean().default(!1)}).default({})})});import{z as d}from"zod";function Tn(a,n){let t=new Set(a.labels||[]);if(a.state==="closed"){let o=n.find(s=>s.kind==="closed");if(o)return o.id}for(let o of n)if(o.kind==="scoped-label"&&o.scopedLabel&&t.has(o.scopedLabel))return o.id;for(let o of n)if(o.kind==="label"&&o.mapsToLabel&&t.has(o.mapsToLabel))return o.id;let r=n.find(o=>o.kind==="open-backlog");if(r){let o=r.scopedPrefix+"::";return[...t].some(l=>l.startsWith(o))?null:r.id}return n[0]?.id??null}function An(a,n){let t=[],r=[],o=!1,s=!1;return n.kind==="scoped-label"&&n.scopedLabel?t.push(n.scopedLabel):n.kind==="label"&&n.mapsToLabel?t.push(n.mapsToLabel):n.kind==="closed"&&(o=!0),a&&(a.kind==="scoped-label"&&a.scopedLabel?r.push(a.scopedLabel):a.kind==="label"&&a.mapsToLabel?r.push(a.mapsToLabel):a.kind==="closed"&&n.kind!=="closed"&&(s=!0)),{addLabels:t.length?t:void 0,removeLabels:r.length?r:void 0,closeIssue:o||void 0,reopen:s||void 0}}var nt,at,rt,ot,st,it,W,lt,K,X=g(()=>{"use strict";nt=d.object({name:d.string(),color:d.string().regex(/^#[0-9a-f]{6}$/i).default("#6366f1"),description:d.string().optional()}),at=d.object({id:d.string().regex(/^[a-z0-9_-]+$/,"column id must be lowercase slug"),title:d.string(),kind:d.enum(["open-backlog","scoped-label","closed","label"]).default("label"),mapsToLabel:d.string().optional(),scopedLabel:d.string().optional(),scopedPrefix:d.string().default("Status"),accent:d.string().optional()}),rt=d.object({enabled:d.boolean().default(!0),staleDoingMinutes:d.number().int().min(1).default(45),respectLunchBreak:d.boolean().default(!0),respectSchedule:d.boolean().default(!0),action:d.enum(["badge","notify"]).default("badge")}),ot=d.discriminatedUnion("type",[d.object({type:d.literal("gitlab"),projects:d.array(d.string()).min(1)})]),st=[{id:"open",title:"Open",kind:"open-backlog",scopedPrefix:"Status",accent:"#6b7280"},{id:"todo",title:"To Do",kind:"scoped-label",scopedLabel:"Status::To Do",scopedPrefix:"Status",accent:"#fb7a35"},{id:"doing",title:"Doing",kind:"scoped-label",scopedLabel:"Status::Doing",scopedPrefix:"Status",accent:"#22c55e"},{id:"onhold",title:"On Hold",kind:"scoped-label",scopedLabel:"Status::On Hold",scopedPrefix:"Status",accent:"#f59e0b"},{id:"review",title:"Review",kind:"scoped-label",scopedLabel:"Status::Review",scopedPrefix:"Status",accent:"#3b82f6"},{id:"closed",title:"Closed",kind:"closed",scopedPrefix:"Status",accent:"#6b7280"}],it=d.object({id:d.string().regex(/^[a-z0-9_-]+$/,"board id must be lowercase slug"),name:d.string(),source:ot,primaryToolLabel:d.string().optional(),labels:d.array(nt).default([]),columns:d.array(at).min(1).default(st),timeRangeDays:d.number().int().min(1).max(365).default(30),closedWindowDays:d.number().int().min(1).max(365).default(30),reconciliation:rt.default({})}),W=d.array(it).default([]),lt=d.object({name:d.string(),url:d.string(),dashboardUrl:d.string().optional(),token:d.string().optional(),dashboardToken:d.string().optional()}),K=d.object({enabled:d.boolean().default(!1),port:d.number().int().default(4202),bind:d.string().default("127.0.0.1"),token:d.string().optional(),daemonUrl:d.string().default("http://localhost:18800"),daemons:d.array(lt).default([]),draftAgent:d.string().optional()}).default({})});function ft(a){let n=String(a??"").trim().toLowerCase();if(!n)return{ok:!1,error:"is empty"};let t=n.split("+").map(s=>s.trim());if(t.some(s=>!s))return{ok:!1,error:`"${a}" has an empty part; write it like opt+space`};let r=mt[t[t.length-1]]??t[t.length-1],o=new Set;for(let s of t.slice(0,-1)){let l=dt[s];if(!l)return{ok:!1,error:`"${s}" is not a modifier; use ctrl, opt, shift or cmd`};if(o.has(l))return{ok:!1,error:`"${a}" names ${l} twice`};o.add(l)}return gt(r)?!Z(r)&&!["ctrl","opt","cmd"].some(s=>o.has(s))?{ok:!1,error:`"${a}" needs ctrl, opt or cmd, or it would take that key away from your typing`}:{ok:!0,value:[...ut.filter(s=>o.has(s)),r].join("+")}:{ok:!1,error:`"${r}" is not a key AgentX Voice can use; use a letter, a digit, f1 to f20, or space, period, comma, slash, return, tab`}}function G(a){let n=ft(a);return n.ok?void 0:n.error}function vn(a){let n={ctrl:"\u2303",opt:"\u2325",shift:"\u21E7",cmd:"\u2318"},t={space:"Space",period:".",comma:",",slash:"/",semicolon:";",quote:"'",minus:"-",equal:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",grave:"`",return:"Return",tab:"Tab"},r=a.split("+"),o=r.pop()??"";return r.map(s=>n[s]??s).join("")+(t[o]??o.toUpperCase())}var dt,ut,ct,mt,Z,gt,k,Y=g(()=>{"use strict";dt={ctrl:"ctrl",control:"ctrl",opt:"opt",option:"opt",alt:"opt",shift:"shift",cmd:"cmd",command:"cmd"},ut=["ctrl","opt","shift","cmd"],ct=["space","period","comma","slash","semicolon","quote","minus","equal","leftbracket","rightbracket","backslash","grave","return","tab"],mt={".":"period",",":"comma","/":"slash",";":"semicolon","'":"quote","-":"minus","=":"equal","`":"grave",enter:"return"},Z=a=>/^f([1-9]|1[0-9]|20)$/.test(a),gt=a=>/^[a-z0-9]$/.test(a)||ct.includes(a)||Z(a);k={talk:"opt+space",stop:"cmd+opt+period",paste:"cmd+opt+v"}});function Q(a){let n=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(a);if(!n)return null;let[t,r,o]=n.slice(1).map(b=>parseInt(b,16)/255),s=Math.max(t,r,o),l=Math.min(t,r,o),u=s-l;return u<.04?null:((s===t?(r-o)/u%6:s===r?(o-t)/u+2:(t-r)/u+4)*60+360)%360}function pt(a){let n=Q(a);if(n===null)return y.find(o=>o.id==="lagoon");let t=y[0],r=360;for(let o of y){let s=Math.abs(o.hue-n),l=Math.min(s,360-s);l<r&&(t=o,r=l)}return t}function Cn(a,n=_){let t=l=>y.find(u=>u.id===l),r=t(a?.palette);if(r)return{...r,set:!0};let o=a?.color;return{...o&&Q(o)!==null?pt(o):t(n)??t(_),set:!1}}var y,V,J,L,_,ee=g(()=>{"use strict";y=[{id:"sunrise",label:"Sunrise",hue:18,colors:["#E8505B","#F2726F","#F79A5A","#FBBF4A","#FFE3A3"]},{id:"desert",label:"Desert",hue:36,colors:["#A4492C","#C8683E","#D9905E","#E7B98A","#F6E3C4"]},{id:"forest",label:"Forest",hue:100,colors:["#2F5D34","#4C7D3A","#6FA046","#9CC25E","#D5EBA4"]},{id:"lagoon",label:"Lagoon",hue:172,colors:["#0B6E73","#0E9594","#1FBFB2","#56DCCB","#B8F4EA"]},{id:"ocean",label:"Ocean",hue:205,colors:["#15457E","#1C6BA8","#2B93CF","#5DBBE8","#BFE6FA"]},{id:"dusk",label:"Dusk",hue:268,colors:["#2E2A7A","#5B3E9E","#8C4FB0","#C8649E","#F4A7B9"]},{id:"blossom",label:"Blossom",hue:330,colors:["#A3245B","#CF3F78","#E8699A","#F49BB8","#FFD6E0"]}],V=["orb","character"],J=["off","rarely","sometimes","often"],L=y.map(a=>a.id);_="lagoon"});function te(a){let n=(a.match(/[؀-ۿ]/g)??[]).length,t=(a.match(/[a-zA-ZÀ-ÿ]/g)??[]).length;if(n&&n>=t)return"ar";let r=0,o=0;for(let s of a.toLowerCase().replace(/[’]/g,"'").match(/[a-zà-ÿœ']+/g)??[])bt.has(s)&&r++,ht.has(s)||s.startsWith("l'")||s.startsWith("d'")||s.startsWith("qu'")?o++:xt.test(s)&&(o+=.5);return r===o?null:r>o?"en":"fr"}var bt,ht,xt,ne=g(()=>{"use strict";bt=new Set("the and is are was were i you he she we they it this that to of in for with not but yes what have has will would can your my".split(" ")),ht=new Set("le la les des du de un une et est sont je tu il elle nous vous ils elles ce cette c'est pas pour que qui avec dans sur au aux mais tr\xE8s oui non merci bonjour votre mon".split(" ")),xt=/[éèêëàâçùûîïôœ]/});function Nn(a,n=O){let t=a;if(t=t.replace(/```[\s\S]*?```/g,". "),t=t.replace(/`[^`]*`/g,""),t=t.replace(/\*\*(.*?)\*\*/g,"$1"),t=t.replace(/__(.*?)__/g,"$1"),t=t.replace(/\*([^*]+)\*/g,"$1"),t=t.replace(/_([^_]+)_/g,"$1"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]+\)/g,"image$1 "),t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/^[\s]*[-*+]\s+/gm,". "),t=t.replace(/^[\s]*\d+\.\s+/gm,". "),t=t.replace(/^[-=_]{3,}$/gm,""),t=t.replace(/^>\s*/gm,""),t=t.replace(/https?:\/\/\S+/g,"link"),t=t.replace(/\/\w+(\/\w+)+/g,r=>r.split("/").filter(Boolean).join(" slash ")),t=t.replace(/&/g," and "),t=t.replace(/@/g," at "),t=t.replace(/=>/g," returns "),t=t.replace(/->/g," to "),t=t.replace(/\|/g," or "),t=t.replace(/\be\.g\./gi,"for example"),t=t.replace(/\bi\.e\./gi,"that is"),t=t.replace(/\betc\./gi,"etcetera"),t=t.replace(/\bvs\.?\b/gi,"versus"),t=t.replace(/\n{2,}/g,". "),t=t.replace(/\n/g," "),t=t.replace(/\s+/g," "),t=t.replace(/\.\s*\./g,"."),t=t.replace(/\s+([.,!?])/g,"$1"),t=t.trim().replace(/^[.,:;]+\s*/,""),t.length>n){let r=t.slice(0,n),o=([...t.slice(0,n+1).matchAll(/[.!?؟](?=\s)/g)].at(-1)?.index??-1)+1;t=(o>=n/2?r.slice(0,o):r.replace(/\s+\S*$/,"")+"...")+" "+yt[te(r)??"en"]}return t}var O,yt,ae=g(()=>{"use strict";ne();O=500,yt={en:"The rest is on screen.",fr:"La suite est \xE0 l'\xE9cran.",ar:"\u0627\u0644\u0628\u0627\u0642\u064A \u0639\u0644\u0649 \u0627\u0644\u0634\u0627\u0634\u0629."}});function Pn(a,n=j){let t=new Set(n.map(re)),r=a.replace(/\[([^\][]*)\]|\(([^()]*)\)/g,(o,s,l)=>t.has(re(s??l))?"":o);return!/[\p{L}\p{N}]/u.test(r)}var j,qn,re,oe=g(()=>{"use strict";j=["background noise","noise","mumbling","babbling","unintelligible","inaudible","muffled speech","pause","silence","music","outro jingle","blank audio"],qn="I didn't catch that.",re=a=>a.toLowerCase().replace(/[_\s]+/g," ").trim()});import{z as c}from"zod";var se,St,ie,le=g(()=>{"use strict";se=c.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"use HH:MM, 24-hour"),St=c.object({id:c.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/,"lowercase letters, digits, - and _"),enabled:c.boolean().default(!0),chats:c.array(c.string().min(1)).default([]),senders:c.array(c.string().min(1)).default([]),agent:c.string().min(1),prompt:c.string().max(4e3).optional(),quietHours:c.object({start:se,end:se}).optional(),autoAck:c.boolean().default(!1)}).refine(a=>a.chats.length>0||a.senders.length>0,{message:"a rule needs at least one chat or sender"}),ie=c.object({enabled:c.boolean().default(!1),secretEnv:c.string().regex(/^[A-Z_][A-Z0-9_]*$/).default("WACLI_WEBHOOK_SECRET"),batchSeconds:c.number().int().min(0).max(600).default(20),timezone:c.string().optional(),allowAutoAck:c.boolean().default(!1),describeMedia:c.boolean().default(!0),wacli:c.object({bin:c.string().default("wacli"),account:c.string().optional(),store:c.string().optional()}).default({}),rules:c.array(St).default([])}).default({})});function kt(a){a.exec(`
2
- CREATE TABLE IF NOT EXISTS requests (
3
- id TEXT PRIMARY KEY,
4
- state TEXT NOT NULL,
5
- channel TEXT NOT NULL,
6
- chat_id TEXT NOT NULL,
7
- sender TEXT,
8
- agent_id TEXT NOT NULL,
9
- text TEXT NOT NULL,
10
- created_at INTEGER NOT NULL,
11
- updated_at INTEGER NOT NULL,
12
- attention_reason TEXT,
13
- notified_at INTEGER,
14
- question TEXT,
15
- closed_at INTEGER,
16
- evidence TEXT,
17
- close_reason TEXT
18
- );
19
- CREATE INDEX IF NOT EXISTS idx_requests_state_created ON requests(state, created_at);
20
- CREATE INDEX IF NOT EXISTS idx_requests_chat ON requests(agent_id, channel, chat_id, created_at);
21
- CREATE TABLE IF NOT EXISTS request_links (
22
- request_id TEXT NOT NULL,
23
- kind TEXT NOT NULL,
24
- ref TEXT NOT NULL,
25
- at INTEGER NOT NULL,
26
- PRIMARY KEY (kind, ref),
27
- FOREIGN KEY (request_id) REFERENCES requests(id) ON DELETE CASCADE
28
- );
29
- CREATE INDEX IF NOT EXISTS idx_request_links_request ON request_links(request_id);
30
- `),F(a,"requests",U);let n=a.prepare("PRAGMA table_info(requests)").all();for(let[t,r]of[["pickup_at","INTEGER"],["owner_note","TEXT"],["note_said","INTEGER"],["asked_agent","TEXT"]])if(!n.some(o=>o.name===t))try{a.exec(`ALTER TABLE requests ADD COLUMN ${t} ${r}`)}catch(o){if(!/duplicate column name/i.test(String(o?.message)))throw o}}function Fn(a){return!!a.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()}function h(a){return{id:a.id,state:a.state,channel:a.channel,chatId:a.chat_id,sender:a.sender??null,person:a.person??null,agentId:a.agent_id,text:a.text,createdAt:a.created_at,updatedAt:a.updated_at,attentionReason:a.attention_reason??null,notifiedAt:a.notified_at??null,question:a.question??null,closedAt:a.closed_at??null,evidence:a.evidence??null,closeReason:a.close_reason??null,ownerNote:a.owner_note??null,noteSaid:!!a.note_said,askedAgent:a.asked_agent??null}}var x,f,N,$,p,de,ue=g(()=>{"use strict";Ke();x=["in_progress","waiting_owner","waiting_other","needs_attention"],f=["done","declined","dropped"],N=4e3,$=500;p=a=>Array(a).fill("?").join(","),de=class{constructor(n){this.db=n;kt(n),n.pragma("foreign_keys = ON")}addCandidate(n){this.db.prepare(`INSERT OR IGNORE INTO requests (id, state, channel, chat_id, sender, person, agent_id, text, created_at, updated_at)
31
- VALUES (?, 'candidate', ?, ?, ?, ?, ?, ?, ?, ?)`).run(n.id,n.channel,n.chatId,n.sender??null,n.person??null,n.agentId,n.text.slice(0,N),n.now,n.now),this.link(n.id,"run",n.runId,n.now)}get(n){let t=this.db.prepare("SELECT * FROM requests WHERE id = ?").get(n);return t?h(t):null}byLink(n,t){let r=this.db.prepare("SELECT r.* FROM requests r JOIN request_links l ON l.request_id = r.id WHERE l.kind = ? AND l.ref = ?").get(n,t);return r?h(r):null}link(n,t,r,o){this.db.prepare("INSERT OR IGNORE INTO request_links (request_id, kind, ref, at) VALUES (?, ?, ?, ?)").run(n,t,r,o)}links(n){return this.db.prepare("SELECT kind, ref, at FROM request_links WHERE request_id = ? ORDER BY at, rowid").all(n)}lastAnswer(n){try{return this.db.prepare(`SELECT t.agent_id AS agentId, t.final_response AS text, COALESCE(t.finished_at, t.started_at) AS at
32
- FROM request_links l JOIN task_traces t ON t.task_id = l.ref
33
- WHERE l.request_id = ? AND l.kind = 'run' AND t.final_response IS NOT NULL AND t.final_response != ''
34
- ORDER BY t.started_at DESC LIMIT 1`).get(n)??null}catch{return null}}touch(n,t){this.db.prepare("UPDATE requests SET updated_at = ? WHERE id = ?").run(t,n)}progress(n,t,r="in_progress"){this.db.prepare(`UPDATE requests SET state = ?, updated_at = ?, attention_reason = NULL, notified_at = NULL, question = NULL
35
- WHERE id = ? AND state NOT IN (${p(f.length)})`).run(r,t,n,...f)}waitOnOwner(n,t,r){this.db.prepare(`UPDATE requests SET state = 'waiting_owner', updated_at = ?, question = ?, attention_reason = NULL, notified_at = NULL
36
- WHERE id = ? AND state NOT IN (${p(f.length)})`).run(r,t.slice(0,N),n,...f)}needsAttention(n,t,r){return this.db.prepare(`UPDATE requests SET state = 'needs_attention', updated_at = ?, attention_reason = ?, notified_at = NULL
37
- WHERE id = ? AND state NOT IN ('needs_attention', ${p(f.length)})`).run(r,t.replace(/\s+/g," ").trim().slice(0,$),n,...f).changes>0}close(n,t,r,o){let s=r.trim();if(!s)throw new Error(t==="done"?"a finished request needs a link to the evidence":`a ${t} request needs a reason`);return this.db.prepare(`UPDATE requests SET state = ?, closed_at = ?, updated_at = ?, evidence = ?, close_reason = ?
38
- WHERE id = ? AND state NOT IN (${p(f.length)})`).run(t,o,o,t==="done"?s.slice(0,$):null,t==="done"?null:s.slice(0,$),n,...f).changes>0}discardCandidate(n){return this.db.prepare("DELETE FROM requests WHERE id = ? AND state = 'candidate'").run(n).changes>0}listOpen(){return this.db.prepare(`SELECT * FROM requests WHERE state IN (${p(x.length)}) ORDER BY created_at, rowid`).all(...x).map(h)}quietSince(n,t){return this.db.prepare(`SELECT * FROM requests WHERE state IN (${p(n.length)}) AND updated_at < ? ORDER BY created_at, rowid`).all(...n,t).map(h)}awaitingNotice(){return this.db.prepare("SELECT * FROM requests WHERE state = 'needs_attention' AND notified_at IS NULL ORDER BY created_at, rowid").all().map(h)}markNotified(n,t){this.db.prepare("UPDATE requests SET notified_at = ? WHERE id = ?").run(t,n)}listByState(n){return this.db.prepare("SELECT * FROM requests WHERE state = ? ORDER BY created_at, rowid").all(n).map(h)}requestPickup(n,t){return this.db.prepare(`UPDATE requests SET state = 'in_progress', updated_at = ?, attention_reason = NULL, notified_at = NULL, pickup_at = ?
39
- WHERE id = ? AND state = 'needs_attention'`).run(t,t,n).changes>0}handOff(n,t,r,o){return this.db.prepare(`UPDATE requests SET agent_id = ?, state = 'in_progress', updated_at = ?, attention_reason = NULL, notified_at = NULL,
40
- question = NULL, pickup_at = ?, owner_note = ?, note_said = NULL, asked_agent = COALESCE(asked_agent, agent_id)
41
- WHERE id = ? AND state IN (${p(x.length)})`).run(t,o,o,r.trim().slice(0,N)||null,n,...x).changes>0}setNoteSaid(n,t,r){this.db.prepare(`UPDATE requests SET note_said = ? WHERE id = ? AND owner_note = ?${r?" AND pickup_at IS NULL":""}`).run(r?1:null,n,t)}takePickups(){return this.db.prepare("UPDATE requests SET pickup_at = NULL WHERE pickup_at IS NOT NULL RETURNING *").all().map(h).filter(n=>n.state==="in_progress").sort((n,t)=>n.createdAt-t.createdAt)}pruneClosed(n){return this.db.prepare(`DELETE FROM requests WHERE state IN (${p(f.length)}) AND closed_at < ?`).run(...f,n).changes}}});function Wn(a){return Object.assign({channel:ge,chatId:a,sender:"operator"},{[fe]:!0})}function Kn(a){return!!a&&a[fe]===!0}function Et(a,n,t,r=!1){let o=E(n);if(a.channels.length&&!a.channels.map(E).includes(o))return!1;if(T.has(o))return r&&!_t.has((t?.name??"").toLowerCase());let s=wt.has(o)?t?.username:t?.id,l=s?ce(o,s):"";return l?a.from.some(u=>{let m=u.trim().toLowerCase(),b=m.indexOf(":");return b>0&&m.slice(0,b)===o&&ce(o,m.slice(b+1))===l}):!1}function Xn(a){if(!a)return;let n=r=>typeof r=="string"&&r?r.slice(0,120):void 0,t={name:n(a.sender),id:n(a.senderId),username:n(a.senderUsername)};return t.name||t.id||t.username?t:void 0}function Tt(a){return/\btimed? ?out\b|timeout/i.test(a)?"timed out":"failed"}var ge,fe,T,_t,E,wt,ce,w,S,me,pe=g(()=>{"use strict";ue();ge="requests",fe=Symbol("requests.pickup");T=new Set(["voice","app","dashboard","webrtc"]),_t=new Set(["camera"]),E=a=>a.toLowerCase().split("@")[0],wt=new Set(["github","gitlab"]),ce=(a,n)=>a==="whatsapp"?n.replace(/@.*$/,"").replace(/\D/g,""):n.trim().toLowerCase().replace(/^@/,"");w=(a,n=200)=>{let t=a.replace(/\s+/g," ").trim();return t.length>n?`${t.slice(0,n-1)}\u2026`:t},S=(a,n,t)=>`${a}\0${n}\0${t}`,me=class{constructor(n,t,r,o=Date.now){this.store=n;this.settings=t;this.log=r;this.now=o}live=new Map;guard(n,t){try{t()}catch(r){this.log(`[requests] ${n} failed: ${r?.message??r}`)}}isListedOwner(n){let t=E(n.channel),r=this.settings().channels;return r.length&&!r.map(E).includes(t)?!1:n.person?.role==="owner"&&!T.has(t)}liveRequestId(n,t,r){return this.live.get(S(n,t,r))?.requestId??null}taskStarted(n){n.taskId&&this.guard("capture",()=>{if(!this.settings().enabled)return;let t=this.now(),r=n.resumedFrom?this.store.byLink("run",n.resumedFrom):null,o=S(n.agentId,n.channel,n.chatId);if(r){this.store.link(r.id,"run",n.taskId,t),r.state==="candidate"?this.store.touch(r.id,t):this.store.progress(r.id,t),this.live.set(o,{requestId:r.id,runId:n.taskId});return}let s=n.pickup&&n.channel===ge?this.store.get(n.chatId):null;if(s&&s.agentId===n.agentId){this.store.link(s.id,"run",n.taskId,t),this.store.touch(s.id,t),this.live.set(o,{requestId:s.id,runId:n.taskId});return}!n.humanRoot||!(Et(this.settings(),n.channel,n.sender,n.operator===!0)||this.isListedOwner(n))||(this.live.set(o,{requestId:`req-${n.taskId}`,runId:n.taskId}),this.store.addCandidate({id:`req-${n.taskId}`,runId:n.taskId,channel:n.channel,chatId:n.chatId,sender:n.sender?.name??n.sender?.username??n.sender?.id??null,person:n.person?.id??null,agentId:n.agentId,text:n.requestText??n.fullMessage??n.messagePreview,now:t}))})}taskCompleted(n){n.taskId&&this.guard("run end",()=>{let t=S(n.agentId,n.channel,n.chatId);this.live.get(t)?.runId===n.taskId&&this.live.delete(t);let r=this.store.byLink("run",n.taskId);if(!r)return;let o=this.now();if(!n.interrupted){if(n.error&&n.errorKind!=="cancelled"){let s=Tt(n.error);this.store.needsAttention(r.id,`${n.agentId} ${s}: ${w(n.error)}`,o)&&this.log(`[requests] ${r.id} needs attention: run ${n.taskId} ${s}`);return}r.state==="candidate"?this.store.discardCandidate(r.id):this.store.touch(r.id,o)}})}delegationStarted(n){this.guard("delegation start",()=>{if(!this.settings().enabled)return;let t=this.live.get(S(n.caller,n.origin.channel,n.origin.chatId));if(!t)return;let r=this.now();this.store.link(t.requestId,"delegation",n.id,r),this.store.progress(t.requestId,r,"waiting_other")})}delegationDone(n,t,r){this.guard("delegation end",()=>{let o=this.store.byLink("delegation",n.id);if(!o)return;let s=this.now(),l=n.peer?`${n.callee} on ${n.peer}`:n.callee;if(t==="done"){this.store.progress(o.id,s);return}let u={error:"failed",timeout:"did not answer in time",lost:"was lost in a restart"}[t];this.store.needsAttention(o.id,`The work handed to ${l} ${u}: ${w(r)}`,s)&&this.log(`[requests] ${o.id} needs attention: delegation ${n.id} ${t}`)})}cardRaised(n,t){t&&this.guard("card",()=>{if(!this.settings().enabled)return;let r=this.live.get(S(n.raised_by,t.channel,t.chatId))?.requestId;if(!r)return;let o=this.now();this.store.link(r,"card",n.id,o),this.store.waitOnOwner(r,n.ask,o)})}cardResolved(n){this.guard("card result",()=>{let t=this.store.byLink("card",n.id);if(!t)return;let r=this.now(),o=n.outcome??n.if_silent;n.status==="decided"?t.state==="waiting_owner"&&this.store.progress(t.id,r):this.store.needsAttention(t.id,`Your answer did not come before the card expired (${w(n.ask)}); "${o}" was applied`,r)&&this.log(`[requests] ${t.id} needs attention: card ${n.id} expired unanswered`)})}closingNote(n){try{let t=this.store.byLink("delegation",n);return!t||!x.includes(t.state)?void 0:`This is part of the owner's open request ${t.id}. It stays on their list until it is closed. If it is finished now, close it with agentx_request: {action:"done", id:"${t.id}", evidence:"<link to the proof>"}. If you will not do it, use decline with the reason. If work goes on, leave it open.`}catch{return}}resumeOutcome(n){this.guard("restart",()=>{let t=this.store.byLink("run",n.taskId);if(!t)return;let r=this.now();n.decision==="resumed"?t.state==="candidate"?this.store.touch(t.id,r):this.store.progress(t.id,r):(n.decision==="reported"||n.decision==="resume-failed"||n.decision==="skipped")&&this.store.needsAttention(t.id,`Cut off by a restart and not picked up again (${w(n.reason)})`,r)&&this.log(`[requests] ${t.id} needs attention: run ${n.taskId} cut off by a restart`)})}}});import{randomBytes as At,timingSafeEqual as he}from"crypto";import{chmodSync as Rt,existsSync as vt,mkdirSync as It,readFileSync as Ct,writeFileSync as Lt}from"fs";import{networkInterfaces as Ot}from"os";import{dirname as jt,resolve as Nt}from"path";function Qn(a){return Object.assign(a,{[xe]:!0})}function ye(a){return!!a&&a[xe]===!0}function qt(a=process.cwd()){return Nt(a,".agentx","operator.key")}function ea(a=process.cwd(),n={}){let t=qt(a);try{if(vt(t)){let o=Ct(t,"utf-8").trim();if(o)return o}if(!n.create)return null;let r=At(32).toString("hex");return It(jt(t),{recursive:!0}),Lt(t,r+`
42
- `,{mode:384}),Rt(t,384),r}catch{return null}}function Pt(a,n){let t=Array.isArray(n)?n[0]:n;if(!a||!t)return!1;let r=Buffer.from(a),o=Buffer.from(t.trim());return r.length===o.length&&he(r,o)}function Mt(a,n,t,r){if(!a||typeof a!="object")return!1;let o=String(a.channel??"").toLowerCase().split("@")[0];return r.has(o)?Pt(t,n[$t]):!1}function Bt(a,n){let t=a[Dt];if((Array.isArray(t)?t[0]:t)!=="1")return!1;let r=a.authorization,o=(Array.isArray(r)?r[0]:r)||"",s=o.toLowerCase().startsWith("bearer ")?o.slice(7).trim():"";if(!s)return!1;let l=Buffer.from(s);for(let u of n){if(!u)continue;let m=Buffer.from(u);if(m.length===l.length&&he(m,l))return!0}return!1}function Ut(a,n=Ft()){let t=be(a??"");if(!t||t==="::1"||t.startsWith("127."))return!0;for(let r of n)if(be(r)===t)return!0;return!1}function Ft(){return Object.values(Ot()).flatMap(a=>(a??[]).map(n=>n.address))}function ta(a,n,t){if(Mt(a,n.headers,t.key,t.operatorChannels))return!0;if(!a||typeof a!="object")return!1;let r=String(a.channel??"").toLowerCase().split("@")[0];return!t.operatorChannels.has(r)||Ut(n.remoteAddress,t.ownAddresses)?!1:Bt(n.headers,t.peerTokens)}var $t,xe,Dt,be,Se=g(()=>{"use strict";$t="x-agentx-operator",xe=Symbol("requests.operator");Dt="x-agentx-operator-vouch";be=a=>a.toLowerCase().replace(/^::ffff:/,"").replace(/%.*$/,"")});function ia(a,n){return a.find(t=>t.id===n)?.name??(n===A?"Owner":n)}function ke(a,n){let t=n.trim().toLowerCase();return a==="whatsapp"?t.replace(/@.*$/,"").replace(/\D/g,""):t.replace(/^@/,"")}function _e(a){let n=a.indexOf(":");if(n<=0||n===a.length-1)return null;let t=q(a.slice(0,n).trim()),r=ke(t,a.slice(n+1));return r?{channel:t,value:r}:null}function we(a){let n=new Set,t=new Map;for(let r of a){if(n.has(r.id))return`person "${r.id}" is listed twice`;if(n.add(r.id),r.id===A&&r.role!=="owner")return`the id "${A}" is kept for a person with the owner role`;for(let o of r.identities){let s=_e(o);if(!s)return`identity "${o}" of "${r.id}" must be written channel:id`;let l=`${s.channel}:${s.value}`,u=t.get(l);if(u&&u!==r.id)return`identity "${o}" belongs to both "${u}" and "${r.id}"`;t.set(l,r.id)}}return null}function Ht(a,n,t){let r=q(n),s=(r==="whatsapp"?[t?.id]:[t?.id,t?.username]).filter(l=>typeof l=="string"&&!!l).map(l=>ke(r,l)).filter(Boolean);return s.length?a.find(l=>l.identities.some(u=>{let m=_e(u);return!!m&&m.channel===r&&s.includes(m.value)}))??null:null}function zt(a){let n=a.filter(t=>t.role==="owner");return n.length===0?{id:A,role:"owner"}:n.length===1?{id:n[0].id,role:"owner"}:null}function Ee(a,n){let t=M(n);if(t)return t.person?{id:t.person}:null;if(!n||B(n)!=="human")return null;let r=String(n.channel??"");if(T.has(q(r)))return ye(n)?zt(a):null;let o=l=>typeof l=="string"?l:void 0,s=Ht(a,r,{id:o(n.senderId),username:o(n.senderUsername)});return s?{id:s.id,role:s.role}:null}function Wt(a,n){let t=a.agents??[];return a.role==="owner"||t.length===0||t.includes(n)}function la(a,n,t){let r=Ee(a,t);if(!r)return null;let o=a.find(l=>l.id===r.id);if(!o||Wt(o,n))return null;let s=(o.agents??[]).join(", ");return{person:o,note:`${o.name}, you can reach ${s} here, not ${n}. Ask the owner if you need ${n}.`}}function da(a,n){let t=a.trim().split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${t}$`,"i").test(n.trim())}function ua(a,n){let t=Ee(a,n);if(!t)return null;let r=a.find(l=>l.id===t.id);if(!r||r.role==="owner")return null;let o=r.deny?.tools??[],s=r.deny?.skills??[];return!o.length&&!s.length?null:{personId:r.id,name:r.name,tools:[...o],skills:[...s]}}var sa,A,q,Te=g(()=>{"use strict";We();pe();Se();sa=["owner","member","client","guest"],A="owner";q=a=>a.toLowerCase().split("@")[0]});function ga(a){return typeof a=="string"&&Xt.includes(a)}function Ae(a){let n=new Set(Kt);return a.map(t=>t.trim()).filter(t=>t&&!n.has(t))}var Kt,Xt,ma,Re=g(()=>{"use strict";Kt=["agentx_generate","agentx_inspect","agentx_skill_match","agentx_detect_output_type","agentx_channel_reply","agentx_channel_label","agentx_send","agentx_send_agent","agentx_recent","agentx_events","agentx_send_contact","agentx_task","agentx_agents","agentx_voice_queue","agentx_call_owner","agentx_camera_ask","agentx_camera_look","agentx_health","agentx_attach_next","agentx_attach_answer","agentx_crons","agentx_schedule","agentx_approval","agentx_request","agentx_workflow","agentx_debug","agentx_wiki_query","agentx_wiki_patch","agentx_wiki_interview","agentx_graph_review"],Xt=["read","full"],ma=["agentx_inspect","agentx_skill_match","agentx_detect_output_type","agentx_recent","agentx_events","agentx_agents","agentx_voice_queue","agentx_health","agentx_crons","agentx_wiki_query"]});var Sn={};He(Sn,{INTEGRATION_KINDS:()=>tn,approvalsConfigSchema:()=>Ue,callsSchema:()=>$e,cameraBotSchema:()=>Ne,daemonConfigSchema:()=>Fe,eventSubscriptionSchema:()=>je,expandEnvVars:()=>C,loadDaemonConfig:()=>xn,membersConfigSchema:()=>Me,peopleConfigSchema:()=>De,personSchema:()=>Pe,requestStatusConfigSchema:()=>Be,requestsConfigSchema:()=>qe,validateWorkspaces:()=>yn});import{z as e}from"zod";import{readFileSync as Ie,existsSync as v}from"fs";import{resolve as I}from"path";function Zt(a){let n=I(a,".env");if(!v(n))return;let t=Ie(n,"utf-8");for(let r of t.split(`
43
- `)){let o=r.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let l=o.slice(0,s).trim(),u=o.slice(s+1).trim();process.env[l]||(process.env[l]=u)}}function C(a){if(typeof a=="string")return a.replace(/\$\{(\w+)\}/g,(n,t)=>process.env[t]||"");if(Array.isArray(a))return a.map(C);if(a!==null&&typeof a=="object"){let n={};for(let[t,r]of Object.entries(a))n[t]=C(r);return n}return a}function hn(a,n){let t=[],r=new Set;for(let o of a){let s=o.path.join("."),l=/^channels\.telegram\.accounts\.([^.]+)\.token$/.exec(s);if(l&&o.message.toLowerCase().includes("required")){let u=l[1],m=`tg:${u}`;if(r.has(m))continue;r.add(m),t.push(`Hint: Telegram account "${u}" is enabled but has no bot token.
44
- Either:
45
- A) Open ${n} and set channels.telegram.accounts.${u}.token to your bot token (or "\${TG_${u.toUpperCase()}_BOT_TOKEN}" + the matching .env entry).
46
- B) If you don't need Telegram on this instance, remove the entire "telegram" block under "channels" (or set channels.telegram.enabled to false AND drop accounts.${u}).`)}}return t}function xn(a){let n=a?[a]:[I(process.cwd(),"agentx.json"),I(process.cwd(),".agentx/config.json")];Zt(process.cwd());let t,r;for(let u of n)if(v(u)){t=Ie(u,"utf-8"),r=u;break}if(!t||!r)throw new Error(`No config found. Create agentx.json or .agentx/config.json
47
- Searched: ${n.join(", ")}`);let o;try{o=JSON.parse(t)}catch(u){throw new Error(`Invalid JSON in ${r}: ${u.message}`)}let s=C(o),l=Fe.safeParse(s);if(!l.success){let u=l.error.issues.map(P=>` ${P.path.join(".")}: ${P.message}`).join(`
48
- `),m=hn(l.error.issues,r),b=m.length?`
49
-
50
- ${m.join(`
51
-
52
- `)}`:"";throw new Error(`Config validation failed (${r}):
53
- ${u}${b}`)}return l.data}function yn(a){let n=[];for(let[t,r]of Object.entries(a.agents)){if(!v(r.workspace)){n.push(`Agent "${t}": workspace not found at ${r.workspace}`);continue}if(r.tier==="claude-code"){let l=I(r.workspace,".claude");v(l)||n.push(`Agent "${t}": no .claude/ directory in workspace ${r.workspace}. Claude Code native features (hooks, MCP, skills) won't be available.`)}let o=r.provider||"claude",s=a.providers[o];!["claude-code","codex-cli","opencode"].includes(r.tier)&&(!s||!s.apiKey)&&n.push(`Agent "${t}": provider "${o}" has no API key configured. Set providers.${o}.apiKey in config or use a CLI-backed tier ("claude-code", "codex-cli", or "opencode").`)}for(let[t,r]of Object.entries(a.crons))a.agents[r.agent]||n.push(`Cron "${t}": references unknown agent "${r.agent}"`);if(a.channels.telegram.enabled)for(let[t,r]of Object.entries(a.channels.telegram.accounts))a.agents[r.agentBinding]||n.push(`Telegram account "${t}": references unknown agent "${r.agentBinding}"`);return n}var ve,Gt,Yt,Vt,Jt,Qt,en,tn,Ce,Le,R,Oe,je,nn,an,Ne,rn,on,sn,ln,dn,un,cn,mn,gn,$e,fn,pn,bn,qe,Pe,De,Me,Be,Ue,Fe,kn=g(()=>{z();X();ze();Y();ee();ae();oe();le();Te();Re();ve=e.array(e.string().min(1)).superRefine((a,n)=>{let t=Ae(a);t.length&&n.addIssue({code:e.ZodIssueCode.custom,message:`not an agentx tool: ${t.join(", ")}. Use the names the agentx server lists, without "mcp__agentx__".`})}),Gt=e.object({apiKey:e.string().optional(),defaultModel:e.string().optional(),baseUrl:e.string().optional(),thinking:e.boolean().optional()}),Yt=e.object({type:e.literal("stdio").optional(),command:e.string(),args:e.array(e.string()).default([]),env:e.record(e.string(),e.string()).optional()}),Vt=e.object({type:e.literal("http"),url:e.string().url(),headers:e.record(e.string(),e.string()).optional()}),Jt=e.union([Vt,Yt]),Qt=e.object({tokenEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),privateAppTokenEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),apiKeyEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),refreshTokenEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),clientIdEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),clientSecretEnv:e.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),auth:e.literal("keyring").optional(),sessionDir:e.string().optional()}).strict(),en=e.object({kind:e.string().min(1),label:e.string().min(1),credentials:Qt.default({}),metadata:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()])).default({}),enabled:e.boolean().default(!0)}),tn=["telegram-bot","whatsapp","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"],Ce=e.enum(["system","elevenlabs"]),Le=e.union([e.string(),e.record(e.string(),e.string())]),R=e.string().superRefine((a,n)=>{let t=G(a);t&&n.addIssue({code:e.ZodIssueCode.custom,message:`shortcut ${t}`})}),Oe=e.object({provider:Ce.optional(),system:Le.optional(),fallbacks:e.array(e.string().min(1)).optional(),elevenlabsVoiceId:e.string().optional(),gender:e.enum(["female","male","neutral"]).optional(),style:e.string().optional(),intro:e.string().optional(),narrate:e.enum(["off","on","all"]).optional(),rate:e.number().min(.75).max(1.5).optional(),priority:e.enum(["high","normal","low"]).optional(),hotkey:R.optional()}),je=e.object({kinds:e.array(e.string().min(1)).min(1),agents:e.array(e.string().min(1)).optional(),nodes:e.array(e.string().min(1)).optional(),match:e.string().min(1).optional(),delivery:e.enum(["pull","digest","wake"]).default("pull"),maxPerHour:e.number().int().min(1).max(60).default(4)}),nn=e.object({name:e.string(),workspace:e.string(),tier:e.enum(["claude-code","codex-cli","opencode","sdk","orchestrator"]).default("claude-code"),provider:e.string().optional(),model:e.string().optional(),systemPrompt:e.string().optional(),mentions:e.array(e.string()).default([]),intents:e.array(e.string()).default([]),maxDelegationDepth:e.number().int().min(0).max(50).default(5),mcp:e.record(e.string(),Jt).optional(),codegraph:e.boolean().default(!1),contextStrategy:e.enum(["layered","planner"]).optional(),contextReferences:e.boolean().default(!1),richMessages:e.boolean().default(!0),maxConcurrent:e.number().default(1),maxExecutionMinutes:e.number().int().min(1).max(240).default(20),preSpawnTimeoutSec:e.number().int().min(10).max(3600).default(300),drainTimeoutSeconds:e.number().int().min(0).max(86400).optional(),permissionMode:e.string().default("default"),billing:e.enum(["subscription","api"]).default("subscription"),cloudSessions:e.object({enabled:e.boolean().default(!1),maxPerDay:e.number().int().min(0).default(0),openHours:e.number().min(1).max(168).default(24),launchTimeoutSeconds:e.number().int().min(10).max(600).default(120)}).default({}),toolUseRequired:e.array(e.string()).default([]),gitlabAutoReply:e.boolean().optional(),persistentProcess:e.boolean().default(!1),queueMode:e.enum(["collect","followup","drop"]).default("collect"),heartbeat:e.object({enabled:e.boolean().default(!1),intervalMinutes:e.number().default(30),prompt:e.string().default("Check inbox, pending tasks, and system health. Report anything that needs attention."),channel:e.string().default("heartbeat")}).default({}),access:e.enum(["private","public"]).default("private"),admin:e.boolean().optional(),subscriptions:e.array(je).default([]),integrations:e.array(en).default([]),voice:Oe.optional(),presence:e.object({color:e.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),palette:e.enum(L).optional(),initial:e.string().max(2).optional(),label:e.string().optional(),allowActions:e.boolean().optional()}).optional()}),an=e.object({token:e.string(),agentBinding:e.string(),allowFrom:e.array(e.string()).optional(),pollInbound:e.boolean().default(!0)}),Ne=e.object({frameIntervalSeconds:e.number().int().min(0).max(3600).default(0),maxSessionMinutes:e.number().int().min(1).max(240).default(10),maxFrameEdge:e.number().int().min(160).max(3840).default(1024),keepFrames:e.boolean().default(!1),streamFrameSeconds:e.number().int().min(2).max(60).default(5),streamMaxSeconds:e.number().int().min(10).max(600).default(60)}).default({}),rn=e.object({telegram:e.object({enabled:e.boolean().default(!1),accounts:e.record(e.string(),an).default({}),policy:e.object({dm:e.enum(["pair","block"]).default("pair"),group:e.enum(["mention-required","all"]).default("mention-required"),allowFrom:e.array(e.string()).optional()}).default({})}).default({}),whatsapp:e.object({enabled:e.boolean().default(!1),sessionDir:e.string().default(".agentx/whatsapp-sessions"),defaultAgent:e.string().optional(),allowFrom:e.array(e.string()).optional(),routes:e.array(e.object({contact:e.string().optional(),group:e.string().optional(),agent:e.string()})).default([]),ingest:e.object({enabled:e.boolean().default(!1),mode:e.enum(["metadata-only","messages"]).default("metadata-only"),allowContacts:e.array(e.string()).default([]),allowGroups:e.array(e.string()).default([]),denyContacts:e.array(e.string()).default([]),denyGroups:e.array(e.string()).default([]),messageCap:e.number().int().min(1).max(500).default(50),historyDays:e.number().int().min(1).max(365).default(30),contactRefreshDays:e.number().int().min(1).max(90).default(7),throttle:e.object({minMsBetweenCalls:e.number().int().min(100).default(1500),maxCallsPerMinute:e.number().int().min(1).default(20),maxChatsPerSweep:e.number().int().min(1).default(25)}).default({}),retentionDays:e.number().int().min(0).default(0)}).default({})}).default({}),gitlab:e.object({enabled:e.boolean().default(!1),webhookPort:e.number().default(18810),webhookSecret:e.string().optional(),host:e.string().default("https://gitlab.com"),token:e.string().optional(),autoReplyLegacy:e.boolean().default(!0),routes:e.array(e.object({project:e.string(),agent:e.string()})).default([]),agentMappings:e.array(e.object({agentId:e.string(),gitlabUsernames:e.array(e.string()).default([]),keywords:e.array(e.string()).default([]),token:e.string().optional(),node:e.string().optional()})).default([]),agentUsernamePrefixes:e.array(e.string().min(1)).default([])}).default({}),github:e.object({enabled:e.boolean().default(!1),autoReplyLegacy:e.boolean().default(!0),cloudSessions:e.boolean().default(!1),token:e.string().optional(),tokenFile:e.string().optional(),appId:e.number().optional(),clientId:e.string().optional(),privateKeyFile:e.string().optional(),webhookSecret:e.string().optional(),routes:e.array(e.object({repo:e.string(),agent:e.string()})).default([]),agentMappings:e.array(e.object({agentId:e.string(),githubUsernames:e.array(e.string()).default([]),token:e.string().optional(),tokenFile:e.string().optional(),node:e.string().optional()})).default([]),issueActions:e.array(e.string().min(1)).default(["opened","reopened","assigned"]),pullRequestActions:e.array(e.string().min(1)).default(["opened","reopened","ready_for_review"]),ignoreOwnChanges:e.boolean().default(!0),debounceSeconds:e.number().min(0).max(3600).default(30)}).default({}),ntfy:e.object({enabled:e.boolean().default(!1),server:e.string().default("https://ntfy.sh"),topic:e.string().optional(),token:e.string().optional(),defaultPriority:e.number().int().min(1).max(5).default(3),defaultTitle:e.string().optional()}).default({}),push:e.object({enabled:e.boolean().default(!1),keysFile:e.string().default(".agentx/push-keys.json"),subject:e.string().regex(/^(mailto:|https:\/\/)/,"must start with mailto: or https://").optional(),relayTo:e.string().optional(),ttlSeconds:e.number().int().min(0).max(2419200).default(86400),keepRecent:e.number().int().min(0).max(1e3).default(50),allowedHosts:e.array(e.string().min(1)).default(["fcm.googleapis.com","push.services.mozilla.com","push.apple.com","notify.windows.com"])}).default({}),webrtc:e.object({enabled:e.boolean().default(!1),stunServers:e.array(e.string()).default(["stun:stun.l.google.com:19302"]),turnServers:e.array(e.object({urls:e.string(),username:e.string().optional(),credential:e.string().optional()})).default([]),allowedCallers:e.array(e.string()).default([]),ringNotify:e.array(e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()})).default([]),callUrlBase:e.string().optional(),bot:e.object({enabled:e.boolean().default(!1),defaultAgentId:e.string().optional(),whisperBackend:e.enum(["auto","mlx","openai"]).default("auto"),whisperModel:e.string().optional(),whisperLanguage:e.string().default("auto"),mlxBinary:e.string().optional(),transcriptChannel:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional(),maxCallMinutes:e.number().int().min(1).max(240).default(30)}).default({}),camera:e.object({width:e.number().int().min(160).max(3840).default(1280),height:e.number().int().min(120).max(2160).default(720),frameRate:e.number().int().min(1).max(60).default(15),maxSeconds:e.number().int().min(10).max(7200).default(600),voiceInput:e.boolean().default(!0),speakAnswers:e.boolean().default(!0),bot:Ne}).default({})}).default({})}),on=e.object({enabled:e.boolean().default(!0),schedule:e.string(),timezone:e.string().default("UTC"),agent:e.string(),prompt:e.string().default(""),command:e.string().optional(),timeout:e.number().default(600),model:e.string().optional(),maxOutputTokens:e.number().int().min(50).max(8e3).optional(),autonomy:D.optional(),onError:e.union([e.enum(["log","notify","disable"]),e.array(e.enum(["log","notify","disable"]))]).default("log").transform(a=>Array.isArray(a)?a:[a]),notify:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional(),deliverResult:e.boolean().optional(),fireToken:e.string().optional(),createdBy:e.string().optional(),approval:e.object({action:e.enum(["create","delete"]),requestedBy:e.string(),requestedAt:e.string()}).optional()}).refine(a=>!!(a.command?.trim()||a.prompt?.trim()),{message:"a cron needs either a prompt (dispatch an agent) or a command (run it directly)"}).refine(a=>!(a.command?.trim()&&a.autonomy&&a.autonomy!=="act"),{message:"autonomy applies to agent routines; a command cron runs no agent (remove autonomy or the command)"}),sn=e.object({name:e.string(),triggers:e.array(e.object({pattern:e.string(),channel:e.string().optional()})),allowedContacts:e.array(e.string()).optional(),agent:e.string(),prompt:e.string(),schedule:e.string().optional(),timezone:e.string().default("UTC"),notify:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional()}),ln=e.object({url:e.string(),name:e.string(),token:e.string().optional()}),dn=e.object({name:e.string(),agent:e.string(),enabled:e.boolean().default(!0)}),un=e.object({enabled:e.boolean().default(!1),peers:e.array(ln).default([]),inboxes:e.array(dn).default([]),discovery:e.enum(["static","mdns"]).default("static"),healthCheck:e.object({interval:e.number().default(60),timeout:e.number().default(10)}).default({}),feed:e.object({enabled:e.boolean().default(!0),skipTypes:e.array(e.string().min(1)).default(["task:step"])}).default({}),delegation:e.object({asyncWhenHuman:e.boolean().default(!0),timeoutMinutes:e.number().int().min(1).max(240).default(30)}).default({})}),cn=e.object({enabled:e.boolean().default(!1),baseDir:e.string().default(".agentx/graph"),draftAgent:e.string().optional(),reviewAgent:e.string().optional(),autoApproveStructure:e.enum(["strict","extend-leaves","any"]).default("extend-leaves"),autoApproveConfidence:e.number().min(0).max(1).default(1),classifierModel:e.string().default("claude-haiku-4-5-20251001"),retrievalWeights:e.object({graph:e.number().min(0).default(.6),bm25:e.number().min(0).default(.4)}).default({})}).default({}),mn=e.object({mode:e.enum(["off","shadow","active"]).default("off"),backend:e.string().optional(),model:e.string().optional(),timeoutMs:e.number().int().min(100).optional(),temperature:e.number().min(.01).default(1),explore:e.number().min(0).max(1).default(.15),holdout:e.number().min(0).max(1).optional()}).default({}),gn=e.object({enabled:e.boolean().default(!1),dbPath:e.string().default(".agentx/decisions/decisions.sqlite"),redactState:e.boolean().default(!1),keepStateRows:e.number().int().min(0).default(2e3),defaultBackend:e.string().default("local"),backends:e.object({local:e.object({provider:e.string().default("claude-code"),model:e.string().default("claude-haiku-4-5-20251001"),structureMode:e.enum(["auto","tool","text"]).default("auto"),normalizeProbabilities:e.boolean().default(!0),nRetryMalformedStructure:e.number().int().min(0).max(3).default(1),maxStateChars:e.number().int().min(500).default(24e3)}).default({}),simpleJev:e.object({baseUrl:e.string().default("http://127.0.0.1:8000/v1"),model:e.string().optional(),apiKeyEnv:e.string().optional(),timeoutMs:e.number().int().min(100).default(3e4),maxStateChars:e.number().int().min(500).default(6e3),maxChoiceOptions:e.number().int().min(2).max(255).default(50)}).default({}),jev:e.object({baseUrl:e.string().default("https://openrouter.ai/api/alpha"),path:e.string().default("/decisions"),model:e.string().default("jev-latest"),apiKeyEnv:e.string().default("OPENROUTER_API_KEY"),timeoutMs:e.number().int().min(100).default(3e4),maxStateChars:e.number().int().min(500).default(9e4),maxChoiceOptions:e.number().int().min(2).max(255).default(255)}).default({}),typesafe:e.object({baseUrl:e.string().default("https://api.typesafe.ai/v1"),path:e.string().default("/systemone"),model:e.string().default("jev-latest"),apiKeyEnv:e.string().default("TYPESAFE_API_KEY"),timeoutMs:e.number().int().min(100).default(3e4),maxStateChars:e.number().int().min(500).default(9e4),maxChoiceOptions:e.number().int().min(2).max(255).default(255)}).default({})}).default({}),seats:e.record(e.string(),mn).default({}),routing:e.object({cheapModel:e.string().optional(),cheapModels:e.object({"claude-code":e.string().optional(),"codex-cli":e.string().optional()}).optional()}).default({})}).default({}),$e=e.object({allow:e.array(e.string()).default([]),maxPerHour:e.number().int().min(1).max(60).default(3),ringSeconds:e.number().int().min(10).max(300).default(45),maxCallMinutes:e.number().int().min(1).max(240).default(30),ringSound:e.string().regex(/^[\w -]+$/).default("Submarine"),summary:e.boolean().default(!0)}).default({}),fn=e.object({longTaskThreshold:e.number().default(30),destination:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional(),channel:e.string().optional(),on:e.object({taskComplete:e.boolean().default(!0),taskError:e.boolean().default(!0),taskQueued:e.boolean().default(!1)}).default({}),local:e.object({banner:e.boolean().default(!0),sound:e.boolean().default(!0),soundName:e.string().regex(/^[\w -]+$/).default("Glass"),volume:e.number().min(0).max(1).default(.4),icon:e.string().optional()}).default({})}).default({}),pn=e.object({x:e.number(),y:e.number(),width:e.number().positive(),height:e.number().positive()}),bn=e.object({maxPixels:e.number().int().positive().default(12e5),timeoutMs:e.number().int().positive().default(5e3),intervalMs:e.number().int().positive().default(100),changeThreshold:e.number().min(0).max(1).default(.015),stableMs:e.number().int().nonnegative().default(400),regions:e.record(e.string().regex(/^[a-z][\w-]*$/),pn).default({}),buffer:e.object({enabled:e.boolean().default(!1),seconds:e.number().positive().max(120).default(10),fps:e.number().positive().max(10).default(2),region:e.string().default("screen"),maxPixels:e.number().int().positive().default(3e5)}).default({})}).default({}),qe=e.object({enabled:e.boolean().default(!1),channels:e.array(e.string().min(1)).default([]),from:e.array(e.string().regex(/^[a-z0-9_-]+:\S+$/i,"use channel:id, for example telegram:123456789")).default([]),staleAfterHours:e.number().positive().max(24*365).default(24),retentionDays:e.number().positive().max(3650).default(90),plans:e.object({enabled:e.boolean().default(!0),stallMinutes:e.number().positive().max(7*24*60).default(30),maxNudges:e.number().int().min(0).max(20).default(3),approveKinds:e.array(e.string().regex(/^[a-z][a-z0-9_-]{0,30}$/,"a step kind: a short lower-case word")).default(["message"]),disabledAgents:e.array(e.string().min(1)).default([])}).default({})}).default({}),Pe=e.object({id:e.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"lower-case letters, digits, - and _"),name:e.string().min(1).max(80),say:e.string().trim().min(1).max(120).optional(),role:e.enum(["owner","member","client","guest"]).default("member"),identities:e.array(e.string().regex(/^[A-Za-z][\w-]*:\S.*$/,"write it as channel:id")).default([]),agents:e.array(e.string().min(1)).default([]),deny:e.object({tools:e.array(e.string().min(1)).default([]),skills:e.array(e.string().min(1)).default([])}).strict().default({})}),De=e.array(Pe).default([]).superRefine((a,n)=>{let t=we(a);t&&n.addIssue({code:e.ZodIssueCode.custom,message:t})}),Me=e.object({logRetentionDays:e.number().int().min(1).max(3650).default(90)}).default({}),Be=e.object({channels:e.array(e.string().min(1)).default([])}).default({}),Ue=e.object({defaultExpiryDays:e.number().positive().max(365).default(3),maxExpiryDays:e.number().positive().max(365).default(30),laterHours:e.number().positive().max(24*30).default(24),notifyAgent:e.boolean().default(!0),forwardTo:e.string().min(1).optional(),digest:e.object({enabled:e.boolean().default(!0),time:e.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"use HH:MM, 24-hour").default("09:00"),timezone:e.string().refine(a=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:a}),!0}catch{return!1}},"unknown timezone").optional(),destination:e.object({channel:e.string(),chatId:e.string(),accountId:e.string().optional()}).optional()}).default({}),popup:e.object({enabled:e.boolean().default(!1),style:e.enum(["card","dialog"]).default("card"),theme:e.enum(["system","light","dark"]).default("system"),speak:e.boolean().default(!0),voice:e.string().regex(/^[\w .()-]+$/,"a voice name, as `say -v '?'` lists them").optional(),sound:e.string().regex(/^[\w -]*$/,"a sound name, like chime or Glass").default("chime"),volume:e.number().min(0).max(1).default(.4),timeoutSeconds:e.number().int().min(10).max(3600).default(600)}).default({}),checkin:e.object({enabled:e.boolean().default(!1),times:e.array(e.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"use HH:MM, 24-hour")).default(["11:00","14:00","17:00"]),dailyAt:e.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"use HH:MM, 24-hour").default("09:00"),timezone:e.string().refine(a=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:a}),!0}catch{return!1}},"unknown timezone").optional(),lists:e.array(e.string().min(1)).default(["Reminders"]),agent:e.string().min(1).optional(),dueWithinHours:e.number().positive().max(24*30).default(24),maxAsksPerPass:e.number().int().min(1).max(20).default(5),composeTimeoutSeconds:e.number().int().min(30).max(3600).default(300)}).default({})}).default({}),Fe=e.object({node:e.object({id:e.string(),name:e.string(),bind:e.string().default("127.0.0.1:18800"),defaultAgent:e.string().optional()}),providers:e.record(e.string(),Gt).default({}),agents:e.record(e.string(),nn).default({}),channels:rn.default({}),crons:e.record(e.string(),on).default({}),services:e.record(e.string(),sn).default({}),notifications:fn,calls:$e,whatsappTriage:ie,approvals:Ue,shutdown:e.object({drainTimeoutSeconds:e.number().int().min(0).max(86400).optional(),restart:e.object({allowBy:e.string().optional(),window:e.string().regex(/^\d{1,2}:\d{2}$/,"window must be HH:MM").optional(),windowWaitMinutes:e.number().int().min(1).max(1440).default(180),forbidOnTimeoutRestart:e.boolean().default(!1)}).default({})}).default({}),resume:e.object({enabled:e.boolean().default(!0),maxAgeMinutes:e.number().int().positive().default(30),maxAttempts:e.number().int().min(0).default(1),reportOnlyChannels:e.array(e.string()).default([]),directChannels:e.array(e.string()).default([]),crashLoop:e.object({restarts:e.number().int().positive().default(3),windowMinutes:e.number().positive().default(10)}).default({})}).default({}),requests:qe,people:De,members:Me,requestStatus:Be,reminders:e.object({enabled:e.boolean().default(!1),lists:e.array(e.string().min(1)).default(["AgentX"]),pollSeconds:e.number().int().min(15).default(60),lookbackHours:e.number().positive().default(24),command:e.string().min(1).default("remindctl")}).default({}),app:e.object({android:e.object({packageName:e.string().regex(/^[a-zA-Z][\w]*(\.[a-zA-Z][\w]*)+$/,"must look like com.example.app").default("dev.agentx.phone"),certFingerprints:e.array(e.string().regex(/^([0-9A-Fa-f]{2}:){31}[0-9A-Fa-f]{2}$/,"must be 32 hex pairs separated by colons")).default([])}).default({}),places:e.object({enabled:e.boolean().default(!0),file:e.string().min(1).default(".agentx/places.json"),defaultRadiusMeters:e.number().int().min(50).max(5e4).default(150),minRadiusMeters:e.number().int().min(50).max(5e4).default(100),maxRadiusMeters:e.number().int().min(50).max(5e4).default(5e3),maxPlaces:e.number().int().min(1).max(100).default(50),maxRulesPerPlace:e.number().int().min(1).max(50).default(10),cooldownMinutes:e.number().int().min(0).max(1440).default(10),maxEventAgeMinutes:e.number().int().min(1).max(1440).default(30),syncMinutes:e.number().int().min(15).max(1440).default(60)}).default({})}).default({}),demo:e.object({startupTimeoutSeconds:e.number().int().positive().max(3600).optional()}).default({}),events:e.object({ringSize:e.number().int().min(1).max(1e5).default(1e3)}).default({}),screen:bn,mesh:un.default({}),meshVoices:e.record(e.string(),Oe.omit({rate:!0,priority:!0,hotkey:!0}).extend({name:e.string().optional()})).default({}),voice:e.object({provider:Ce.default("system"),fallback:e.enum(["system","none"]).default("system"),system:Le.optional(),locale:e.string().default("en"),listener:e.string().optional(),pronunciations:e.array(e.object({written:e.string().trim().min(1).max(80),spoken:e.string().trim().min(1).max(120),languages:e.array(e.enum(["en","fr","ar"])).optional()}).strict()).max(200).default([]),pointer:e.boolean().default(!0),stt:e.enum(["auto","elevenlabs","local"]).default("auto"),allowUnmeasured:e.boolean().default(!1),spokenMaxChars:e.number().int().min(300).max(1500).default(O),noiseFilter:e.object({enabled:e.boolean().default(!0),markers:e.array(e.string()).default(j)}).default({}),localStt:e.enum(["mlx-whisper","parakeet"]).default("mlx-whisper"),endOfTurn:e.enum(["vad","volume"]).default("vad"),hotkeys:e.object({talk:R.default(k.talk),stop:R.default(k.stop),paste:R.default(k.paste)}).default({}),look:e.enum(V).default("orb"),startReduced:e.boolean().default(!1),stroll:e.boolean().default(!1),animations:e.enum(J).default("sometimes"),palette:e.enum(L).default(_),card:e.object({timeout:e.number().min(0).max(600).default(30),maxHeight:e.number().min(120).max(800).default(320)}).default({})}).default({}),business:H.optional(),boards:W,dashboard:K,graph:cn,decisions:gn,workflows:e.object({enabled:e.boolean().default(!1),dir:e.string().default(".agentx/workflows"),n8n:e.object({baseUrl:e.string().default(""),apiKey:e.string().default("")}).default({baseUrl:"",apiKey:""}),matching:e.object({enabled:e.boolean().default(!1),mode:e.enum(["suggest","auto"]).default("suggest"),autoRunThreshold:e.number().min(0).max(1).default(.85),suggestThreshold:e.number().min(0).max(1).default(.65)}).default({}),followUp:e.object({enabled:e.boolean().default(!0),agents:e.record(e.boolean()).default({}),stallMinutes:e.number().positive().max(7*24*60).default(30),maxNudges:e.number().int().min(0).max(20).default(2),approval:e.enum(["start","step"]).default("step")}).default({}),editor:e.enum(["disabled","readonly","edit"]).default("edit")}).default({}),procedures:e.object({enabled:e.boolean().default(!0),dir:e.string().default(".agentx/procedures"),extraction:e.object({enabled:e.boolean().default(!1),onTaskCompletion:e.boolean().default(!1),minOccurrences:e.number().int().min(2).default(3),sinceDays:e.number().int().min(1).default(7),maxClusters:e.number().int().min(1).default(5),via:e.string().optional()}).default({}),injection:e.object({enabled:e.boolean().default(!0),maxProcedures:e.number().int().min(1).default(2),minScore:e.number().min(0).max(1).default(.5)}).default({})}).default({}),webhooks:e.array(e.object({id:e.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"webhook id must be lowercase slug"),source:e.string().min(1),agentId:e.string(),secretEnv:e.string().optional(),description:e.string().optional(),enabled:e.boolean().default(!0),node:e.string().optional(),triggers:e.record(e.string(),e.string()).optional(),defaultWorkflow:e.string().optional()})).default([]),session:e.object({staleMinutes:e.number().int().min(1).max(1440).default(720),maxTurnsPerSession:e.number().int().min(2).max(200).default(40),tierTwoThresholdTokens:e.number().int().min(5e4).max(2e5).default(18e4),tierTwoThresholdTokensByChannel:e.record(e.number().int().min(5e4).max(2e5)).default({}),contextStrategy:e.enum(["layered","planner"]).default("layered"),maxClaudeCodeDispatchesPerHour:e.number().int().min(0).max(1e4).optional(),maxClaudeCodeDispatchesPer5h:e.number().int().min(0).max(5e4).optional(),continuityStateTurns:e.number().int().min(0).max(5).default(0),profileByChannel:e.record(e.enum(["full","lean"])).default({}),lean:e.object({mcpServers:e.array(e.string().min(1)).default(["agentx"]),settingSources:e.array(e.enum(["user","project","local"])).default(["project","local"]),contextOnDemand:e.boolean().default(!0),tools:e.array(e.string().min(1)).default([]),toolsByChannel:e.record(e.array(e.string().min(1))).default({}),agentxTools:ve.default([]),agentxToolsByChannel:e.record(ve).default({})}).default({}),triage:e.object({models:e.object({"claude-code":e.string().min(1).optional(),"codex-cli":e.string().min(1).optional()}).default({}),actions:e.array(e.string().min(1)).default(["labeled","unlabeled","closed"])}).default({}),memoryIndexMaxChars:e.number().int().min(0).max(2e5).default(0),resumeGate:e.object({mode:e.enum(["off","shadow","active"]).default("off"),freshTokens:e.number().int().min(1e3).max(2e5).default(3e4),cacheTtlMinutes:e.number().int().min(1).max(1440).default(60),cacheWriteFactor:e.number().min(1).max(4).default(2),margin:e.number().min(1).max(10).default(1.5)}).default({}),observationPack:e.object({enabled:e.boolean().default(!1),limitBytes:e.number().int().min(1024).max(1048576).default(10240),headBytes:e.number().int().min(0).max(65536).default(1024),tailBytes:e.number().int().min(0).max(65536).default(1024),tools:e.array(e.string().min(1)).default(["Bash","Grep","Read","WebFetch","mcp__.*"]),retentionDays:e.number().int().min(0).max(3650).default(0)}).default({})}).default({}),plugins:e.array(e.string()).default([]),processPool:e.object({maxIdleSeconds:e.number().int().min(5).max(86400).default(30),maxAgeSeconds:e.number().int().min(60).max(86400).default(2700),sweepIntervalSeconds:e.number().int().min(1).max(300).default(5)}).default({})})});export{Tn as a,An as b,X as c,ft as d,vn as e,k as f,Y as g,y as h,V as i,J as j,L as k,Cn as l,ee as m,te as n,ne as o,Nn as p,ae as q,qn as r,Pn as s,oe as t,ie as u,le as v,x as w,f as x,N as y,Fn as z,de as A,ue as B,Wn as C,Kn as D,T as E,Xn as F,me as G,pe as H,$t as I,Qn as J,ye as K,ea as L,Mt as M,ta as N,Se as O,sa as P,A as Q,ia as R,_e as S,Ht as T,zt as U,Ee as V,la as W,da as X,ua as Y,Te as Z,Xt as _,ma as $,ga as aa,Re as ba,tn as ca,je as da,Ne as ea,$e as fa,qe as ga,Pe as ha,De as ia,Me as ja,Be as ka,Ue as la,Fe as ma,C as na,xn as oa,yn as pa,Sn as qa,kn as ra};
54
- //# sourceMappingURL=chunk-46JKX6CT.js.map