agentix-cli 0.127.0 → 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 (132) hide show
  1. package/dist/{App-FF66N2KH.js → App-BOLQUKCN.js} +2 -2
  2. package/dist/{ChatApp-HMHQZVVD.js → ChatApp-72HXQV24.js} +2 -2
  3. package/dist/absorb-eval-O3HA6XA5.js +2 -0
  4. package/dist/{agent-UAWDO3I2.js → agent-S2DXXALS.js} +2 -2
  5. package/dist/{board-dashboard-Y2OECKDG.js → board-dashboard-ZKXXK5CG.js} +4 -4
  6. package/dist/{chunk-COWAAE54.js → chunk-2SV4RKRW.js} +2 -2
  7. package/dist/{chunk-YV22EOGL.js → chunk-4V7SWL2S.js} +2 -2
  8. package/dist/chunk-5DAEJF5S.js +36 -0
  9. package/dist/chunk-5DAEJF5S.js.map +1 -0
  10. package/dist/{chunk-VBJTGTF5.js → chunk-6GGGXCOY.js} +2 -2
  11. package/dist/{chunk-4WZGZ2Z6.js → chunk-6KIUVVKX.js} +2 -2
  12. package/dist/{chunk-NUSROFTJ.js → chunk-C5MTLW7O.js} +2 -2
  13. package/dist/{chunk-73WQ42PO.js → chunk-D2WX3BET.js} +2 -2
  14. package/dist/chunk-DN3RLR5Z.js +17 -0
  15. package/dist/chunk-DN3RLR5Z.js.map +1 -0
  16. package/dist/{chunk-EJT3F6QM.js → chunk-DQ2LNQ2D.js} +2 -2
  17. package/dist/{chunk-HYRBBH6T.js → chunk-EJT4MA3J.js} +9 -9
  18. package/dist/chunk-EJT4MA3J.js.map +1 -0
  19. package/dist/chunk-FSW4FUMW.js +55 -0
  20. package/dist/chunk-FSW4FUMW.js.map +1 -0
  21. package/dist/chunk-FXBMFGOV.js +6 -0
  22. package/dist/chunk-FXBMFGOV.js.map +1 -0
  23. package/dist/{chunk-PH43FUU7.js → chunk-HKW56YZK.js} +2 -2
  24. package/dist/{chunk-LTH3AYXC.js → chunk-LDS4SZBU.js} +2 -2
  25. package/dist/chunk-MRYA4J5F.js +54 -0
  26. package/dist/chunk-MRYA4J5F.js.map +1 -0
  27. package/dist/{chunk-HNBW5Q47.js → chunk-O2BS6N3T.js} +2 -2
  28. package/dist/{chunk-EHLTZ6IB.js → chunk-P4XGM7ZM.js} +2 -2
  29. package/dist/{chunk-QWQOI4G4.js → chunk-QACEFESP.js} +6 -6
  30. package/dist/{chunk-CKYPQMUD.js → chunk-QFZU5CEO.js} +2 -2
  31. package/dist/{chunk-XX5QKBX4.js → chunk-QQFURUMS.js} +2 -2
  32. package/dist/{chunk-I4DGMFQG.js → chunk-TG6CT54D.js} +2 -2
  33. package/dist/{chunk-O6FP3LPC.js → chunk-TPNTFCSQ.js} +2 -2
  34. package/dist/{chunk-56KNKUFF.js → chunk-VD7IO653.js} +3 -3
  35. package/dist/{chunk-56KNKUFF.js.map → chunk-VD7IO653.js.map} +1 -1
  36. package/dist/{chunk-3KYZOC7N.js → chunk-YWKLUQDC.js} +2 -2
  37. package/dist/chunk-Z3W7D5RR.js +4 -0
  38. package/dist/chunk-Z3W7D5RR.js.map +1 -0
  39. package/dist/{chunk-XYT6XY7G.js → chunk-ZLC4TSXF.js} +2 -2
  40. package/dist/cli.js +1 -1
  41. package/dist/{client-2VVRJ3UF.js → client-VBV7Q43P.js} +2 -2
  42. package/dist/config-52C3DJD2.js +2 -0
  43. package/dist/{config-mutate-47WZDZBO.js → config-mutate-DKQESY6F.js} +2 -2
  44. package/dist/config-mutator-BF4D4QGN.js +2 -0
  45. package/dist/contributions-5OEZWYXI.js +57 -0
  46. package/dist/contributions-5OEZWYXI.js.map +1 -0
  47. package/dist/{doctor-Q3QNZVLC.js → doctor-VLRC4HW2.js} +2 -2
  48. package/dist/{follow-up-tool-GKZVG4L2.js → follow-up-tool-235LDEMP.js} +2 -2
  49. package/dist/{hub-DNPINTIF.js → hub-5QK7KYTZ.js} +2 -2
  50. package/dist/index.d.ts +224 -0
  51. package/dist/index.js +1 -1
  52. package/dist/{program-4QWUOJE3.js → program-MVD57PKP.js} +226 -222
  53. package/dist/program-MVD57PKP.js.map +1 -0
  54. package/dist/{promote-PETKX7KR.js → promote-UPPQ4BQE.js} +2 -2
  55. package/dist/query-XQS5JN6E.js +2 -0
  56. package/dist/{registry-2XDO53AJ.js → registry-MOMTLJ6R.js} +2 -2
  57. package/dist/{request-planner-A3WJNPXO.js → request-planner-QGZJEAKY.js} +2 -2
  58. package/dist/{review-candidates-A6ID2RDX.js → review-candidates-PAKF2JQF.js} +2 -2
  59. package/dist/{rotation-memo-6UW6DTBQ.js → rotation-memo-7VLREGS6.js} +2 -2
  60. package/dist/{routing-NPP3MEUW.js → routing-JG3EV4O4.js} +2 -2
  61. package/dist/schedule-tool-O7ZZ2A7X.js +2 -0
  62. package/dist/{scheduler-T6VLBM3U.js → scheduler-LMPBAA34.js} +2 -2
  63. package/dist/score-KDNIUTNV.js +3 -0
  64. package/dist/score-KDNIUTNV.js.map +1 -0
  65. package/dist/{seat-D3DBYTSC.js → seat-JN3IVZ3G.js} +2 -2
  66. package/dist/{select-RFY64RY7.js → select-ZMMRFMNO.js} +2 -2
  67. package/dist/{set-enabled-AU66DR5C.js → set-enabled-7Y3TW6Z4.js} +2 -2
  68. package/dist/{tool-F3YA2ZZQ.js → tool-OCYXCDOK.js} +2 -2
  69. package/dist/{tool-PCHIVR27.js → tool-S7QI6HRA.js} +2 -2
  70. package/dist/wiki-OCLFFZG6.js +2 -0
  71. package/package.json +1 -1
  72. package/dist/absorb-eval-ERKVVTGG.js +0 -2
  73. package/dist/chunk-HYRBBH6T.js.map +0 -1
  74. package/dist/chunk-PLIT25TH.js +0 -51
  75. package/dist/chunk-PLIT25TH.js.map +0 -1
  76. package/dist/chunk-TJ4P4WW2.js +0 -4
  77. package/dist/chunk-TJ4P4WW2.js.map +0 -1
  78. package/dist/chunk-UJXS4MS3.js +0 -49
  79. package/dist/chunk-UJXS4MS3.js.map +0 -1
  80. package/dist/chunk-Y27RUOD2.js +0 -54
  81. package/dist/chunk-Y27RUOD2.js.map +0 -1
  82. package/dist/config-YSKHOV44.js +0 -2
  83. package/dist/config-mutator-7DIEQUB5.js +0 -2
  84. package/dist/program-4QWUOJE3.js.map +0 -1
  85. package/dist/query-D44BUTH3.js +0 -2
  86. package/dist/schedule-tool-ZECUQMQK.js +0 -2
  87. package/dist/wiki-NI3ZPUZS.js +0 -2
  88. /package/dist/{App-FF66N2KH.js.map → App-BOLQUKCN.js.map} +0 -0
  89. /package/dist/{ChatApp-HMHQZVVD.js.map → ChatApp-72HXQV24.js.map} +0 -0
  90. /package/dist/{absorb-eval-ERKVVTGG.js.map → absorb-eval-O3HA6XA5.js.map} +0 -0
  91. /package/dist/{agent-UAWDO3I2.js.map → agent-S2DXXALS.js.map} +0 -0
  92. /package/dist/{board-dashboard-Y2OECKDG.js.map → board-dashboard-ZKXXK5CG.js.map} +0 -0
  93. /package/dist/{chunk-COWAAE54.js.map → chunk-2SV4RKRW.js.map} +0 -0
  94. /package/dist/{chunk-YV22EOGL.js.map → chunk-4V7SWL2S.js.map} +0 -0
  95. /package/dist/{chunk-VBJTGTF5.js.map → chunk-6GGGXCOY.js.map} +0 -0
  96. /package/dist/{chunk-4WZGZ2Z6.js.map → chunk-6KIUVVKX.js.map} +0 -0
  97. /package/dist/{chunk-NUSROFTJ.js.map → chunk-C5MTLW7O.js.map} +0 -0
  98. /package/dist/{chunk-73WQ42PO.js.map → chunk-D2WX3BET.js.map} +0 -0
  99. /package/dist/{chunk-EJT3F6QM.js.map → chunk-DQ2LNQ2D.js.map} +0 -0
  100. /package/dist/{chunk-PH43FUU7.js.map → chunk-HKW56YZK.js.map} +0 -0
  101. /package/dist/{chunk-LTH3AYXC.js.map → chunk-LDS4SZBU.js.map} +0 -0
  102. /package/dist/{chunk-HNBW5Q47.js.map → chunk-O2BS6N3T.js.map} +0 -0
  103. /package/dist/{chunk-EHLTZ6IB.js.map → chunk-P4XGM7ZM.js.map} +0 -0
  104. /package/dist/{chunk-QWQOI4G4.js.map → chunk-QACEFESP.js.map} +0 -0
  105. /package/dist/{chunk-CKYPQMUD.js.map → chunk-QFZU5CEO.js.map} +0 -0
  106. /package/dist/{chunk-XX5QKBX4.js.map → chunk-QQFURUMS.js.map} +0 -0
  107. /package/dist/{chunk-I4DGMFQG.js.map → chunk-TG6CT54D.js.map} +0 -0
  108. /package/dist/{chunk-O6FP3LPC.js.map → chunk-TPNTFCSQ.js.map} +0 -0
  109. /package/dist/{chunk-3KYZOC7N.js.map → chunk-YWKLUQDC.js.map} +0 -0
  110. /package/dist/{chunk-XYT6XY7G.js.map → chunk-ZLC4TSXF.js.map} +0 -0
  111. /package/dist/{client-2VVRJ3UF.js.map → client-VBV7Q43P.js.map} +0 -0
  112. /package/dist/{config-YSKHOV44.js.map → config-52C3DJD2.js.map} +0 -0
  113. /package/dist/{config-mutate-47WZDZBO.js.map → config-mutate-DKQESY6F.js.map} +0 -0
  114. /package/dist/{config-mutator-7DIEQUB5.js.map → config-mutator-BF4D4QGN.js.map} +0 -0
  115. /package/dist/{doctor-Q3QNZVLC.js.map → doctor-VLRC4HW2.js.map} +0 -0
  116. /package/dist/{follow-up-tool-GKZVG4L2.js.map → follow-up-tool-235LDEMP.js.map} +0 -0
  117. /package/dist/{hub-DNPINTIF.js.map → hub-5QK7KYTZ.js.map} +0 -0
  118. /package/dist/{promote-PETKX7KR.js.map → promote-UPPQ4BQE.js.map} +0 -0
  119. /package/dist/{query-D44BUTH3.js.map → query-XQS5JN6E.js.map} +0 -0
  120. /package/dist/{registry-2XDO53AJ.js.map → registry-MOMTLJ6R.js.map} +0 -0
  121. /package/dist/{request-planner-A3WJNPXO.js.map → request-planner-QGZJEAKY.js.map} +0 -0
  122. /package/dist/{review-candidates-A6ID2RDX.js.map → review-candidates-PAKF2JQF.js.map} +0 -0
  123. /package/dist/{rotation-memo-6UW6DTBQ.js.map → rotation-memo-7VLREGS6.js.map} +0 -0
  124. /package/dist/{routing-NPP3MEUW.js.map → routing-JG3EV4O4.js.map} +0 -0
  125. /package/dist/{schedule-tool-ZECUQMQK.js.map → schedule-tool-O7ZZ2A7X.js.map} +0 -0
  126. /package/dist/{scheduler-T6VLBM3U.js.map → scheduler-LMPBAA34.js.map} +0 -0
  127. /package/dist/{seat-D3DBYTSC.js.map → seat-JN3IVZ3G.js.map} +0 -0
  128. /package/dist/{select-RFY64RY7.js.map → select-ZMMRFMNO.js.map} +0 -0
  129. /package/dist/{set-enabled-AU66DR5C.js.map → set-enabled-7Y3TW6Z4.js.map} +0 -0
  130. /package/dist/{tool-F3YA2ZZQ.js.map → tool-OCYXCDOK.js.map} +0 -0
  131. /package/dist/{tool-PCHIVR27.js.map → tool-S7QI6HRA.js.map} +0 -0
  132. /package/dist/{wiki-NI3ZPUZS.js.map → wiki-OCLFFZG6.js.map} +0 -0
@@ -0,0 +1,55 @@
1
+ import{c as j}from"./chunk-VD7IO653.js";import{a as D,b as I,c as _,d as L,e as T,j as U}from"./chunk-LDS4SZBU.js";import{y as O,z as V}from"./chunk-YWKLUQDC.js";import{b as P,c as $}from"./chunk-QOYAX2FT.js";import{readFileSync as J,existsSync as N}from"fs";V();import{resolve as W}from"path";import{execSync as z}from"child_process";async function pt(e,r,o,t={}){let d=t.selectorModel??"haiku",l=t.synthModel??"sonnet",p=t.maxCandidates??3,g=t.maxHops??2,h=t.maxArticles??8,s=t.timeoutMs??6e4,a=t.log??console.error.bind(console,"[wiki-query]"),c=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??C,i=W(r.baseDir,"_index.md"),u=H(r,o,t.shared);if(!N(i)&&u.sharedPool.length===0)return S("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let f=(N(i)?J(i,"utf-8"):"")+q(e,u.sharedPool,c,n),E=Date.now(),k=[],y="";try{let m=await G(e,u.pool,o,p,c,n);m?(k=m,y=`[wiki-rerank seat] ${m.map(b=>b.title).join(" | ")}`):(y=await Q(et(e,f,p,c),d,s),k=nt(y))}catch(m){return a("selector failed:",m?.message),{...S("error",e,`Selector: ${m?.message||"unknown"}`),trace:{selectorMs:Date.now()-E,synthesisMs:0,selectorOutput:y}}}let x=Date.now()-E;if(k.length===0)return{...S("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:y}};let A=Y(k,u,g,h);if(A.length===0)return{...S("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:k,trace:{selectorMs:x,synthesisMs:0,selectorOutput:y}};let v=Date.now(),R="";try{R=await Q(rt(e,A),l,s*2)}catch(m){return a("synthesis failed:",m?.message),{...S("error",e,`Synthesis: ${m?.message||"unknown"}`),candidates:k,walked:A.map(b=>({title:b.meta.title,path:b.path,type:b.meta.type,hop:b.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-v,selectorOutput:y}}}let K=Date.now()-v;return{answer:R.trim(),citations:A.map(m=>({title:m.meta.title,path:m.path,type:m.meta.type})),candidates:k,walked:A.map(m=>({title:m.meta.title,path:m.path,type:m.meta.type,hop:m.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:K,selectorOutput:y}}}async function gt(e,r,o,t={}){let d=t.maxCandidates??3,l=t.graphWeight??C,p=t.messagePath?.length?t.messagePath:void 0,g=t.pool??B(r);if(g.length===0||!e.trim())return[];let h=await G(e,g,o,d,p,l,t.stage??"retrieve");if(!h){let s=new Set($(e,P(g.map(F))).map(a=>a.docIndex));h=M(e,g,p,l).filter(a=>s.has(a)).slice(0,d).map(a=>({title:g[a].title,path:g[a].path}))}return h.length===0?[]:Y(h,H(r,o),t.maxHops??1,t.maxArticles??6)}function B(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function S(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function H(e,r,o=[]){let t=new Map,d=[];for(let s of e.listArticles(r||""))t.set(s.meta.title.toLowerCase(),s.path),d.push({path:s.path,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let l=[],p=new Map;for(let s of o)if(s.store.baseDir!==e.baseDir){p.set(s.id,s);for(let a of s.store.listArticles(r||"")){if(a.path.includes("/_versions/")||s.skip?.(a.path))continue;let c=`@${s.id}/${a.path}`;l.push(X(a,c)),d.push({path:c,related:a.meta.related??[],lastUpdated:a.meta.lastUpdated??""});let n=a.meta.title.toLowerCase();t.has(n)||t.set(n,c)}}let g=new Map;if(p.size>0)for(let s of[...d].sort((a,c)=>c.lastUpdated.localeCompare(a.lastUpdated)))for(let a of s.related){let c=a.toLowerCase(),n=g.get(c)??[];n.includes(s.path)||n.push(s.path),g.set(c,n)}let h;return{backlinks:g,get pool(){return h??=[...B(e),...l]},sharedPool:l,titleIndex:t,read(s){let a=s.match(/^@([^/]+)\/(.+)$/),c=a?p.get(a[1]):void 0;if(a&&!c)return null;let n=c?.store??e,i=a?a[2]:s,u=r?n.readArticleAs(i,r):n.readArticle(i);return u?{...u,path:s}:null}}}function X(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var Z=150;function q(e,r,o,t){return r.length===0?"":`
2
+
3
+ ## Shared wiki (other agents' articles)
4
+
5
+ ${M(e,r,o,t).slice(0,Z).map(l=>`- ${r[l].title}${r[l].type?` [${r[l].type}]`:""} (${r[l].path})`).join(`
6
+ `)}
7
+ `}var tt=3;function Y(e,r,o,t){let d=r.titleIndex,l=n=>n.startsWith("@"),p=[...e.filter(n=>!l(n.path)),...e.filter(n=>l(n.path))],g=p.length>0&&!l(p[0].path)?Math.floor(t/2):t,h=new Map,s=0,a=p.map(n=>({path:n.path,hop:0})),c=[];for(;h.size<t;){if(!a.length){if(!c.length||g>=t)break;g=t,a=c.splice(0)}let n=a.shift();if(h.has(n.path)||n.hop>o)continue;if(l(n.path)&&s>=g){c.push(n);continue}let i=r.read(n.path);if(i&&(h.set(n.path,{...i,hop:n.hop}),l(n.path)&&s++,!(n.hop>=o))){if(n.hop===0){let u=[i.meta.title,...i.meta.aliases??[]].map(f=>f.toLowerCase()),w=[...new Set(u.flatMap(f=>r.backlinks.get(f)??[]))].filter(f=>f!==n.path&&!h.has(f)).slice(0,tt);for(let f of w)a.push({path:f,hop:1})}for(let u of i.meta.related||[]){let w=d.get(u.toLowerCase());w&&!h.has(w)&&a.push({path:w,hop:n.hop+1})}}}return Array.from(h.values())}async function G(e,r,o,t,d,l=C,p="catalog-selector"){try{if(r.length<2)return null;let h=M(e,r,d,l).slice(0,I).map(n=>({id:`k${n}`,title:r[n].title||r[n].path,tags:r[n].tags,excerpt:[r[n].type?`type: ${r[n].type}`:"",(r[n].related??[]).length?`related: ${(r[n].related??[]).join(", ")}`:"",(r[n].graphPath??[]).length?`graph: ${(r[n].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),s=await O(D,_({query:e,candidates:h,excerptChars:300}),L(h),{features:{agent:o??"unknown",stage:p}});if(!s||s.mode!=="active")return null;let c=T(s.answers,h).ranked.slice(0,t).map(n=>r[Number(n.slice(1))]).filter(Boolean).map(n=>({title:n.title,path:n.path}));return c.length>0?c:null}catch{return null}}var C=.6;function M(e,r,o,t=C){let d=$(e,P(r.map(F))),l=d.reduce((i,u)=>Math.max(i,u.score),0),p=new Map(d.map(i=>[i.docIndex,l>0?i.score/l:0])),g=!!o?.length,h=i=>g&&i.graphPath?.length?U(o,i.graphPath):0,s=(i,u)=>u.score-i.score||i.i-u.i,a=r.map((i,u)=>({i:u,score:(p.get(u)??0)*(1+t*h(i))})).filter(i=>p.has(i.i)).sort(s),c=r.map((i,u)=>({i:u,score:h(i)})).filter(i=>!p.has(i.i)&&i.score>0).sort(s),n=[...a,...c].map(i=>i.i);for(let i=0;i<r.length;i++)n.includes(i)||n.push(i);return n}function F(e){return[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")}function et(e,r,o,t){let d=t?.length?`
8
+ ## Intent
9
+
10
+ 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.
11
+ `:"";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.
12
+
13
+ ## Question
14
+
15
+ ${e}
16
+ ${d}
17
+ ## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
18
+
19
+ ${r}
20
+
21
+ ## Your task
22
+
23
+ Pick up to ${o} articles from the catalog that are most likely to answer the question. Prefer:
24
+ - Articles whose title directly names a subject in the question.
25
+ - Articles of the right type (e.g. a "who owns X" question \u2192 person or project; a "what happened on DATE" \u2192 event).
26
+ - Articles whose wikilinks suggest they sit at the center of a relevant subgraph.
27
+
28
+ Return ONLY valid JSON, no markdown fencing, no prose:
29
+
30
+ [
31
+ {"title": "Exact Article Title", "path": "path/from/catalog.md"},
32
+ ...
33
+ ]
34
+
35
+ If none of the articles match, return [].`}function rt(e,r){let o=r.map(t=>{let d=[t.meta.owner?`owner: ${t.meta.owner}`:"",t.meta.lastUpdated?`updated: ${t.meta.lastUpdated}`:""].filter(Boolean).join(", "),l=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]${d?` {${d}}`:""}`,p=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[l,p,"",t.content].filter(Boolean).join(`
36
+ `)}).join(`
37
+
38
+ ---
39
+
40
+ `);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.
41
+
42
+ ## Question
43
+
44
+ ${e}
45
+
46
+ ## Articles (${r.length} walked from the catalog)
47
+
48
+ ${o}
49
+
50
+ ## Your task
51
+
52
+ Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
+
54
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function nt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(e,r,o){let{writeFileSync:t,mkdirSync:d,rmSync:l}=await import("fs"),{tmpdir:p}=await import("os"),g=W(p(),`agentx-wiki-query-${process.pid}`);d(g,{recursive:!0});let h=W(g,`prompt-${Date.now()}.txt`);t(h,e);try{let s=`cat '${h}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,a=z(s,{env:j(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let c=JSON.parse(a);return String(c.result||c.content||"")}catch{return a}}finally{try{l(h,{force:!0})}catch{}}}async function ut(e){try{let{loadDaemonConfig:r}=await import("./config-52C3DJD2.js");return r(e).wiki.query.shared}catch{return!0}}export{pt as a,gt as b,B as c,Z as d,C as e,M as f,ut as g};
55
+ //# sourceMappingURL=chunk-FSW4FUMW.js.map
@@ -0,0 +1 @@
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 /** Other wikis to search besides `store`: the shared wiki (#824). Only\n * articles the requester may read are offered. Their paths come back\n * as `@<id>/<path>`. */\n shared?: SharedWikiStore[]\n}\n\n/** A wiki searched alongside the requester's own. */\nexport interface SharedWikiStore {\n /** Shown in citations as `@<id>/<path>`: an agent id, or \"shared\". */\n id: string\n store: WikiStore\n /** Paths to leave out, e.g. the agents/ tree under the root store. */\n skip?: (path: string) => boolean\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 const view = scopeView(store, requesterId, opts.shared)\n if (!existsSync(catalogPath) && view.sharedPool.length === 0) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const ownCatalog = existsSync(catalogPath) ? readFileSync(catalogPath, \"utf-8\") : \"\"\n const catalog = ownCatalog + renderSharedCatalog(question, view.sharedPool, messagePath, graphWeight)\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, view.pool, 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, view, 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, scopeView(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\n/**\n * The articles a query may open: the requester's own wiki first, then\n * each shared one. Shared paths carry an `@<id>/` prefix so the walk\n * knows which store to read; a title the own wiki has resolves there.\n */\ninterface ScopeView {\n /** Own catalog, then the shared articles. */\n pool: CatalogEntry[]\n sharedPool: CatalogEntry[]\n titleIndex: Map<string, string>\n /** Title (lowercased) → pages whose `related` names it, newest first.\n * Built only when shared wikis are searched. */\n backlinks: Map<string, string[]>\n read(path: string): WikiArticle | null\n}\n\nfunction scopeView(store: WikiStore, requesterId: string | undefined, shared: SharedWikiStore[] = []): ScopeView {\n const titleIndex = new Map<string, string>()\n const linking: Array<{ path: string; related: string[]; lastUpdated: string }> = []\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n linking.push({ path: article.path, related: article.meta.related ?? [], lastUpdated: article.meta.lastUpdated ?? \"\" })\n }\n const sharedPool: CatalogEntry[] = []\n const byId = new Map<string, SharedWikiStore>()\n for (const s of shared) {\n if (s.store.baseDir === store.baseDir) continue\n byId.set(s.id, s)\n // listArticles is cached and already drops what the requester can't\n // read; rebuilding every agent's index per query would not be.\n for (const a of s.store.listArticles(requesterId || \"\")) {\n if (a.path.includes(\"/_versions/\") || s.skip?.(a.path)) continue\n const path = `@${s.id}/${a.path}`\n sharedPool.push(catalogEntry(a, path))\n linking.push({ path, related: a.meta.related ?? [], lastUpdated: a.meta.lastUpdated ?? \"\" })\n const key = a.meta.title.toLowerCase()\n if (!titleIndex.has(key)) titleIndex.set(key, path)\n }\n }\n // In a fleet's shared pool the page that answers a question often links\n // TO the page the selector picked (a decision about a person), and the\n // forward walk never reaches it (#824 review: ranked 103rd of ~5,700).\n const backlinks = new Map<string, string[]>()\n if (byId.size > 0) {\n for (const l of [...linking].sort((a, b) => b.lastUpdated.localeCompare(a.lastUpdated))) {\n for (const t of l.related) {\n const key = t.toLowerCase()\n const list = backlinks.get(key) ?? []\n if (!list.includes(l.path)) list.push(l.path)\n backlinks.set(key, list)\n }\n }\n }\n let pool: CatalogEntry[] | undefined\n return {\n backlinks,\n // Lazy: retrieveArticles brings its own pool, and building this one\n // rebuilds the index.\n get pool() { return (pool ??= [...catalogPool(store), ...sharedPool]) },\n sharedPool,\n titleIndex,\n read(path) {\n const m = path.match(/^@([^/]+)\\/(.+)$/)\n const target = m ? byId.get(m[1]) : undefined\n if (m && !target) return null\n const s = target?.store ?? store\n const rel = m ? m[2] : path\n const article = requesterId ? s.readArticleAs(rel, requesterId) : s.readArticle(rel)\n return article ? { ...article, path } : null\n },\n }\n}\n\nfunction catalogEntry(a: WikiArticle, path: string): CatalogEntry {\n return {\n path,\n title: a.meta.title,\n type: a.meta.type,\n related: a.meta.related,\n tags: a.meta.tags || [],\n owner: a.meta.owner,\n access: a.meta.access,\n sharedWith: a.meta.sharedWith,\n aliases: [a.meta.title.toLowerCase(), ...(a.meta.aliases ?? []).map((x) => x.toLowerCase())],\n backlinks: 0,\n sources: a.meta.sources,\n lastUpdated: a.meta.lastUpdated,\n graphPath: a.meta.graphPath,\n }\n}\n\n/** Shared articles most related to the question, for the CLI selector.\n * Capped: a fleet's shared catalog would not fit one prompt. */\nexport const SHARED_CATALOG_LINES = 150\n\nfunction renderSharedCatalog(question: string, pool: CatalogEntry[], messagePath: string[] | undefined, graphWeight: number): string {\n if (pool.length === 0) return \"\"\n const lines = rankCatalogPool(question, pool, messagePath, graphWeight)\n .slice(0, SHARED_CATALOG_LINES)\n .map((i) => `- ${pool[i].title}${pool[i].type ? ` [${pool[i].type}]` : \"\"} (${pool[i].path})`)\n return `\\n\\n## Shared wiki (other agents' articles)\\n\\n${lines.join(\"\\n\")}\\n`\n}\n\n/** Pages that link to a picked page, opened per picked page. */\nconst BACKLINKS_PER_PICK = 3\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n view: ScopeView,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n const titleIndex = view.titleIndex\n const isShared = (path: string) => path.startsWith(\"@\")\n\n // The agent's own pages come first, and shared pages may take at most\n // half the walk when it has any: in the #824 trial shared pages took\n // the slots of the agent's own correct pages and its score dropped.\n const ordered = [...candidates.filter((c) => !isShared(c.path)), ...candidates.filter((c) => isShared(c.path))]\n let sharedCap = ordered.length > 0 && !isShared(ordered[0].path) ? Math.floor(maxArticles / 2) : maxArticles\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let sharedOpened = 0\n let frontier: Array<{ path: string; hop: number }> = ordered.map((c) => ({ path: c.path, hop: 0 }))\n // Shared pages turned away by the cap, in walk order. When the agent's\n // own pages run out first they get the slots left: an own pick with no\n // own neighbours must not leave the walk short of shared pages that answer.\n const deferred: Array<{ path: string; hop: number }> = []\n\n while (opened.size < maxArticles) {\n if (!frontier.length) {\n if (!deferred.length || sharedCap >= maxArticles) break\n sharedCap = maxArticles\n frontier = deferred.splice(0)\n }\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n if (isShared(next.path) && sharedOpened >= sharedCap) { deferred.push(next); continue }\n\n const article = view.read(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (isShared(next.path)) sharedOpened++\n if (next.hop >= maxHops) continue\n\n if (next.hop === 0) {\n // Pages link to a subject by any of its names; skip what is already\n // open before taking the newest few, or an opened page uses a slot.\n const names = [article.meta.title, ...(article.meta.aliases ?? [])].map((n) => n.toLowerCase())\n const linking = [...new Set(names.flatMap((n) => view.backlinks.get(n) ?? []))]\n .filter((path) => path !== next.path && !opened.has(path))\n .slice(0, BACKLINKS_PER_PICK)\n for (const path of linking) frontier.push({ path, hop: 1 })\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 // Owner and date let the answer say where a fact came from and pick\n // the newer page when two disagree (#824).\n const from = [a.meta.owner ? `owner: ${a.meta.owner}` : \"\", a.meta.lastUpdated ? `updated: ${a.meta.lastUpdated}` : \"\"].filter(Boolean).join(\", \")\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]${from ? ` {${from}}` : \"\"}`\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]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\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\n/** `wiki.query.shared` from agentx.json: whether a query also searches the\n * shared wiki. On when there is no config to read. The CLI and the\n * `agentx_wiki_query` tool both ask here, so the switch reaches both. */\nexport async function sharedQueryEnabled(configPath?: string): Promise<boolean> {\n try {\n const { loadDaemonConfig } = await import(\"@/daemon/config\")\n return loadDaemonConfig(configPath).wiki.query.shared\n } catch {\n return true\n }\n}\n"],"mappings":"iNAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KAE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requesterId","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","view","scopeView","existsSync","emptyResult","catalog","readFileSync","renderSharedCatalog","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","retrieveArticles","pool","catalogPool","matched","scoreAll","buildIndex","catalogDoc","r","rankCatalogPool","i","status","_question","error","shared","titleIndex","linking","article","sharedPool","byId","path","catalogEntry","key","backlinks","l","b","t","list","m","target","s","rel","x","SHARED_CATALOG_LINES","BACKLINKS_PER_PICK","isShared","ordered","sharedCap","opened","sharedOpened","frontier","deferred","next","names","n","stage","DEFAULT_SHORTLIST","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","bm25","maxBm25","text","useGraph","branch","ancestryScore","byScore","y","branchOnly","ranked","articles","articlesBlock","from","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","claudeCliEnv","envelope","sharedQueryEnabled","configPath","loadDaemonConfig"]}
@@ -0,0 +1,6 @@
1
+ import{d as h}from"./chunk-DN3RLR5Z.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
2
+ `),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
3
+ `).filter(o=>o.trim()).length,a=c.split(`
4
+ `).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
5
+ `))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
6
+ //# sourceMappingURL=chunk-FXBMFGOV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/fact-guard.ts"],"sourcesContent":["import { droppedFacts } from \"./absorb-context\"\n\n// --- Fact-loss guard for edits to an existing article (#824) ---\n//\n// A fleet test found page rewrites had dropped a contact's phone number\n// and their \"main contact\" role. `droppedFacts` already guards absorb\n// against losing commits, links and numbers; this adds the structured\n// facts a person page carries in words: email addresses, roles and\n// contact markers. Every edit path that changes an existing article\n// (`wiki patch`, the daily contribution merge) runs it and holds the\n// change instead of saving it silently.\n\n/** Phrases that mark a person's standing; losing one loses a fact. */\nconst CONTACT_MARKERS = [\n \"main contact\",\n \"primary contact\",\n \"point of contact\",\n \"billing contact\",\n \"technical contact\",\n \"decision maker\",\n]\n\nconst EMAIL_RE = /[\\w.+-]+@[\\w-]+(?:\\.[\\w-]+)+/g\nconst ROLE_RE = /\\b(role|title|position|job)\\s*\\**\\s*[::]\\s*\\**\\s*([^\\n;|]+)/gi\n\n/**\n * Structured facts `before` carries that `after` no longer does.\n *\n * `superseded` lists values the edit replaces on purpose (a checked\n * correction keeps the old value in the fact ledger's history and the\n * page's version history), so they don't count as lost.\n */\nexport function lostStructuredFacts(before: string, after: string, superseded: string[] = []): string[] {\n const kept = [after, ...superseded].join(\"\\n\")\n const keptLower = kept.toLowerCase()\n const lost = droppedFacts(before, kept)\n\n for (const email of unique(before.match(EMAIL_RE) ?? [])) {\n if (!keptLower.includes(email.toLowerCase())) lost.push(`email ${email}`)\n }\n const beforeLower = before.toLowerCase()\n for (const marker of CONTACT_MARKERS) {\n if (beforeLower.includes(marker) && !keptLower.includes(marker)) lost.push(`marker \"${marker}\"`)\n }\n for (const m of before.matchAll(ROLE_RE)) {\n const role = m[2].replace(/\\*+/g, \"\").trim()\n if (role && !keptLower.includes(role.toLowerCase())) lost.push(`${m[1].toLowerCase()} \"${role}\"`)\n }\n return unique(lost)\n}\n\nfunction unique(list: string[]): string[] {\n return [...new Set(list)]\n}\n\n/** Below this share of the old line count, an edit is a rewrite. */\nconst MIN_KEPT_LINES = 0.9\n\n/** The model talking about its task instead of writing the article. */\nconst CHATTER_RE = /^\\s*(?:wait\\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\\s|let me\\b|as requested\\b)/im\n\n/**\n * Why an LLM-applied patch to an existing article must not be saved\n * as it is. Empty means it looks like the small edit it was asked for.\n *\n * The fleet test behind #824 found `wiki patch` doing four things a\n * patch must not: replacing the whole body with just the new section\n * (33 → 4 lines), pasting its own reasoning into the page (\"Wait — I\n * must output the full article body\"), duplicating header lines, and\n * dropping facts. Each is checked here.\n */\nexport function patchProblems(before: string, after: string): string[] {\n const problems: string[] = []\n const oldLines = before.split(\"\\n\").filter((l) => l.trim()).length\n const newLines = after.split(\"\\n\").filter((l) => l.trim()).length\n if (oldLines >= 5 && newLines < Math.floor(oldLines * MIN_KEPT_LINES)) {\n problems.push(`the article shrinks from ${oldLines} to ${newLines} lines`)\n }\n const chatter = after.match(CHATTER_RE)\n if (chatter && !before.match(CHATTER_RE)) problems.push(`it contains the model's own commentary (\"${chatter[0].trim().slice(0, 40)}\")`)\n const headings = (text: string) => {\n const n = new Map<string, number>()\n for (const l of text.split(\"\\n\")) if (/^#{1,6} /.test(l)) n.set(l.trim(), (n.get(l.trim()) ?? 0) + 1)\n return n\n }\n const was = headings(before)\n for (const [h, count] of headings(after)) {\n if (count > 1 && count > (was.get(h) ?? 0)) problems.push(`the heading \"${h}\" appears ${count} times`)\n }\n const lost = lostStructuredFacts(before, after)\n if (lost.length) problems.push(`it drops ${lost.length} fact(s): ${lost.slice(0, 6).join(\", \")}${lost.length > 6 ? \", …\" : \"\"}`)\n return problems\n}\n"],"mappings":"wCAaA,IAAMA,EAAkB,CACtB,eACA,kBACA,mBACA,kBACA,oBACA,gBACF,EAEMC,EAAW,gCACXC,EAAU,gEAST,SAASC,EAAoBC,EAAgBC,EAAeC,EAAuB,CAAC,EAAa,CACtG,IAAMC,EAAO,CAACF,EAAO,GAAGC,CAAU,EAAE,KAAK;AAAA,CAAI,EACvCE,EAAYD,EAAK,YAAY,EAC7BE,EAAOC,EAAaN,EAAQG,CAAI,EAEtC,QAAWI,KAASC,EAAOR,EAAO,MAAMH,CAAQ,GAAK,CAAC,CAAC,EAChDO,EAAU,SAASG,EAAM,YAAY,CAAC,GAAGF,EAAK,KAAK,SAASE,GAAO,EAE1E,IAAME,EAAcT,EAAO,YAAY,EACvC,QAAWU,KAAUd,EACfa,EAAY,SAASC,CAAM,GAAK,CAACN,EAAU,SAASM,CAAM,GAAGL,EAAK,KAAK,WAAWK,IAAS,EAEjG,QAAWC,KAAKX,EAAO,SAASF,CAAO,EAAG,CACxC,IAAMc,EAAOD,EAAE,CAAC,EAAE,QAAQ,OAAQ,EAAE,EAAE,KAAK,EACvCC,GAAQ,CAACR,EAAU,SAASQ,EAAK,YAAY,CAAC,GAAGP,EAAK,KAAK,GAAGM,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KAAK,IAAI,IAAIA,EAAK,OAAS,EAAI,WAAQ,IAAI,EACxHY,CACT","names":["CONTACT_MARKERS","EMAIL_RE","ROLE_RE","lostStructuredFacts","before","after","superseded","kept","keptLower","lost","droppedFacts","email","unique","beforeLower","marker","m","role","list","MIN_KEPT_LINES","CHATTER_RE","patchProblems","problems","oldLines","l","newLines","chatter","headings","text","n","was","h","count"]}
@@ -1,5 +1,5 @@
1
- import{ma as m,na as $,ra as x}from"./chunk-Y27RUOD2.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
1
+ import{ma as m,na as $,ua as x}from"./chunk-MRYA4J5F.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
4
4
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
5
- //# sourceMappingURL=chunk-PH43FUU7.js.map
5
+ //# sourceMappingURL=chunk-HKW56YZK.js.map
@@ -1,6 +1,6 @@
1
- import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-3KYZOC7N.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-YWKLUQDC.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-LTH3AYXC.js.map
6
+ //# sourceMappingURL=chunk-LDS4SZBU.js.map
@@ -0,0 +1,54 @@
1
+ import{b as M,d as B,h as Ge}from"./chunk-BRK6M6LA.js";import{l as U,m as F,n as Ye}from"./chunk-UIBUZ2N3.js";import{a as D,e as Ze}from"./chunk-2QNT5JDS.js";import{a as g,b as Xe}from"./chunk-QIJLFPWE.js";import{z as s}from"zod";var Ve,Je,Qe,et,tt,nt,rt,at,ot,z,H=g(()=>{"use strict";Ve=s.enum(["mon","tue","wed","thu","fri","sat","sun"]),Je=s.object({days:s.array(Ve).default(["mon","tue","wed","thu","fri"]),start:s.string().regex(/^\d{2}:\d{2}$/),end:s.string().regex(/^\d{2}:\d{2}$/),lunch:s.object({start:s.string().regex(/^\d{2}:\d{2}$/),end:s.string().regex(/^\d{2}:\d{2}$/)}).optional()}),Qe=s.object({title:s.string(),responsibilities:s.array(s.string()).default([]),sopPath:s.string().optional(),kpis:s.array(s.string()).default([])}),et=s.object({role:s.string(),reportsTo:s.string().optional(),schedule:Je,utilizationTarget:s.number().min(0).max(1).default(.8)}),tt=s.object({channel:s.string(),chatId:s.string(),accountId:s.string().optional()}),nt=s.discriminatedUnion("type",[s.object({type:s.literal("backlog"),path:s.string().default(".agentx/backlog.md")}),s.object({type:s.literal("gitlab"),projects:s.array(s.string()).default([])}),s.object({type:s.literal("wiki"),path:s.string(),glob:s.string().default("**/*.md")})]),rt=s.object({id:s.string(),pm:s.string().optional(),client:s.string().optional()}),at=s.object({channel:s.string().optional(),chatId:s.string().optional(),username:s.string().optional(),senderId:s.string().optional(),client:s.string(),project:s.string().optional(),displayName:s.string().optional()}),ot=s.object({name:s.string().optional(),kind:s.enum(["client","internal","own"]).optional(),respondWithin:s.string().optional(),standing:s.array(s.string()).default([])}),z=s.object({enabled:s.boolean().default(!1),timezone:s.string().default("UTC"),mainChannel:tt,workSource:nt,roles:s.record(s.string(),Qe).default({}),orgChart:s.record(s.string(),et).default({}),projects:s.array(rt).default([]),contactMap:s.array(at).default([]),clients:s.record(s.string(),ot).default({}),workTickMinutes:s.number().int().min(1).max(60).default(15),idleQueueThreshold:s.number().int().min(0).default(0),standup:s.object({enabled:s.boolean().default(!0),plansDir:s.string().default(".agentx/plans"),maxAgentsPerDay:s.number().int().min(1).max(100).default(20),dryRun:s.boolean().default(!1)}).default({})})});import{z as u}from"zod";function Cn(r,n){let t=new Set(r.labels||[]);if(r.state==="closed"){let o=n.find(i=>i.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 a=n.find(o=>o.kind==="open-backlog");if(a){let o=a.scopedPrefix+"::";return[...t].some(l=>l.startsWith(o))?null:a.id}return n[0]?.id??null}function On(r,n){let t=[],a=[],o=!1,i=!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),r&&(r.kind==="scoped-label"&&r.scopedLabel?a.push(r.scopedLabel):r.kind==="label"&&r.mapsToLabel?a.push(r.mapsToLabel):r.kind==="closed"&&n.kind!=="closed"&&(i=!0)),{addLabels:t.length?t:void 0,removeLabels:a.length?a:void 0,closeIssue:o||void 0,reopen:i||void 0}}var it,st,lt,ut,dt,ct,W,mt,K,X=g(()=>{"use strict";it=u.object({name:u.string(),color:u.string().regex(/^#[0-9a-f]{6}$/i).default("#6366f1"),description:u.string().optional()}),st=u.object({id:u.string().regex(/^[a-z0-9_-]+$/,"column id must be lowercase slug"),title:u.string(),kind:u.enum(["open-backlog","scoped-label","closed","label"]).default("label"),mapsToLabel:u.string().optional(),scopedLabel:u.string().optional(),scopedPrefix:u.string().default("Status"),accent:u.string().optional()}),lt=u.object({enabled:u.boolean().default(!0),staleDoingMinutes:u.number().int().min(1).default(45),respectLunchBreak:u.boolean().default(!0),respectSchedule:u.boolean().default(!0),action:u.enum(["badge","notify"]).default("badge")}),ut=u.discriminatedUnion("type",[u.object({type:u.literal("gitlab"),projects:u.array(u.string()).min(1)})]),dt=[{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"}],ct=u.object({id:u.string().regex(/^[a-z0-9_-]+$/,"board id must be lowercase slug"),name:u.string(),source:ut,primaryToolLabel:u.string().optional(),labels:u.array(it).default([]),columns:u.array(st).min(1).default(dt),timeRangeDays:u.number().int().min(1).max(365).default(30),closedWindowDays:u.number().int().min(1).max(365).default(30),reconciliation:lt.default({})}),W=u.array(ct).default([]),mt=u.object({name:u.string(),url:u.string(),dashboardUrl:u.string().optional(),token:u.string().optional(),dashboardToken:u.string().optional()}),K=u.object({enabled:u.boolean().default(!1),port:u.number().int().default(4202),bind:u.string().default("127.0.0.1"),token:u.string().optional(),daemonUrl:u.string().default("http://localhost:18800"),daemons:u.array(mt).default([]),draftAgent:u.string().optional()}).default({})});function xt(r){let n=String(r??"").trim().toLowerCase();if(!n)return{ok:!1,error:"is empty"};let t=n.split("+").map(i=>i.trim());if(t.some(i=>!i))return{ok:!1,error:`"${r}" has an empty part; write it like opt+space`};let a=bt[t[t.length-1]]??t[t.length-1],o=new Set;for(let i of t.slice(0,-1)){let l=gt[i];if(!l)return{ok:!1,error:`"${i}" is not a modifier; use ctrl, opt, shift or cmd`};if(o.has(l))return{ok:!1,error:`"${r}" names ${l} twice`};o.add(l)}return ht(a)?!Z(a)&&!["ctrl","opt","cmd"].some(i=>o.has(i))?{ok:!1,error:`"${r}" needs ctrl, opt or cmd, or it would take that key away from your typing`}:{ok:!0,value:[...ft.filter(i=>o.has(i)),a].join("+")}:{ok:!1,error:`"${a}" 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(r){let n=xt(r);return n.ok?void 0:n.error}function Ln(r){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"},a=r.split("+"),o=a.pop()??"";return a.map(i=>n[i]??i).join("")+(t[o]??o.toUpperCase())}var gt,ft,pt,bt,Z,ht,k,Y=g(()=>{"use strict";gt={ctrl:"ctrl",control:"ctrl",opt:"opt",option:"opt",alt:"opt",shift:"shift",cmd:"cmd",command:"cmd"},ft=["ctrl","opt","shift","cmd"],pt=["space","period","comma","slash","semicolon","quote","minus","equal","leftbracket","rightbracket","backslash","grave","return","tab"],bt={".":"period",",":"comma","/":"slash",";":"semicolon","'":"quote","-":"minus","=":"equal","`":"grave",enter:"return"},Z=r=>/^f([1-9]|1[0-9]|20)$/.test(r),ht=r=>/^[a-z0-9]$/.test(r)||pt.includes(r)||Z(r);k={talk:"opt+space",stop:"cmd+opt+period",paste:"cmd+opt+v"}});function Q(r){let n=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(r);if(!n)return null;let[t,a,o]=n.slice(1).map(b=>parseInt(b,16)/255),i=Math.max(t,a,o),l=Math.min(t,a,o),d=i-l;return d<.04?null:((i===t?(a-o)/d%6:i===a?(o-t)/d+2:(t-a)/d+4)*60+360)%360}function yt(r){let n=Q(r);if(n===null)return y.find(o=>o.id==="lagoon");let t=y[0],a=360;for(let o of y){let i=Math.abs(o.hue-n),l=Math.min(i,360-i);l<a&&(t=o,a=l)}return t}function $n(r,n=w){let t=l=>y.find(d=>d.id===l),a=t(r?.palette);if(a)return{...a,set:!0};let o=r?.color;return{...o&&Q(o)!==null?yt(o):t(n)??t(w),set:!1}}var y,V,J,O,w,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"],O=y.map(r=>r.id);w="lagoon"});function te(r){let n=(r.match(/[؀-ۿ]/g)??[]).length,t=(r.match(/[a-zA-ZÀ-ÿ]/g)??[]).length;if(n&&n>=t)return"ar";let a=0,o=0;for(let i of r.toLowerCase().replace(/[’]/g,"'").match(/[a-zà-ÿœ']+/g)??[])St.has(i)&&a++,kt.has(i)||i.startsWith("l'")||i.startsWith("d'")||i.startsWith("qu'")?o++:wt.test(i)&&(o+=.5);return a===o?null:a>o?"en":"fr"}var St,kt,wt,ne=g(()=>{"use strict";St=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(" ")),kt=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(" ")),wt=/[éèêëàâçùûîïôœ]/});function Mn(r,n=j){let t=r;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,a=>a.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 a=t.slice(0,n),o=([...t.slice(0,n+1).matchAll(/[.!?؟](?=\s)/g)].at(-1)?.index??-1)+1;t=(o>=n/2?a.slice(0,o):a.replace(/\s+\S*$/,"")+"...")+" "+_t[te(a)??"en"]}return t}var j,_t,re=g(()=>{"use strict";ne();j=500,_t={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 Fn(r,n=L){let t=new Set(n.map(ae)),a=r.replace(/\[([^\][]*)\]|\(([^()]*)\)/g,(o,i,l)=>t.has(ae(i??l))?"":o);return!/[\p{L}\p{N}]/u.test(a)}var L,Un,ae,oe=g(()=>{"use strict";L=["background noise","noise","mumbling","babbling","unintelligible","inaudible","muffled speech","pause","silence","music","outro jingle","blank audio"],Un="I didn't catch that.",ae=r=>r.toLowerCase().replace(/[_\s]+/g," ").trim()});import{z as c}from"zod";var ie,Et,se,le=g(()=>{"use strict";ie=c.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/,"use HH:MM, 24-hour"),Et=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:ie,end:ie}).optional(),autoAck:c.boolean().default(!1)}).refine(r=>r.chats.length>0||r.senders.length>0,{message:"a rule needs at least one chat or sender"}),se=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(Et).default([])}).default({})});function Tt(r){r.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(r,"requests",U);let n=r.prepare("PRAGMA table_info(requests)").all();for(let[t,a]of[["pickup_at","INTEGER"],["owner_note","TEXT"],["note_said","INTEGER"],["asked_agent","TEXT"]])if(!n.some(o=>o.name===t))try{r.exec(`ALTER TABLE requests ADD COLUMN ${t} ${a}`)}catch(o){if(!/duplicate column name/i.test(String(o?.message)))throw o}}function Xn(r){return!!r.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()}function h(r){return{id:r.id,state:r.state,channel:r.channel,chatId:r.chat_id,sender:r.sender??null,person:r.person??null,agentId:r.agent_id,text:r.text,createdAt:r.created_at,updatedAt:r.updated_at,attentionReason:r.attention_reason??null,notifiedAt:r.notified_at??null,question:r.question??null,closedAt:r.closed_at??null,evidence:r.evidence??null,closeReason:r.close_reason??null,ownerNote:r.owner_note??null,noteSaid:!!r.note_said,askedAgent:r.asked_agent??null}}var x,f,N,$,p,ue,de=g(()=>{"use strict";Ye();x=["in_progress","waiting_owner","waiting_other","needs_attention"],f=["done","declined","dropped"],N=4e3,$=500;p=r=>Array(r).fill("?").join(","),ue=class{constructor(n){this.db=n;Tt(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 a=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 a?h(a):null}link(n,t,a,o){this.db.prepare("INSERT OR IGNORE INTO request_links (request_id, kind, ref, at) VALUES (?, ?, ?, ?)").run(n,t,a,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,a="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(a,t,n,...f)}waitOnOwner(n,t,a){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(a,t.slice(0,N),n,...f)}needsAttention(n,t,a){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(a,t.replace(/\s+/g," ").trim().slice(0,$),n,...f).changes>0}close(n,t,a,o){let i=a.trim();if(!i)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"?i.slice(0,$):null,t==="done"?null:i.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,a,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,a.trim().slice(0,N)||null,n,...x).changes>0}setNoteSaid(n,t,a){this.db.prepare(`UPDATE requests SET note_said = ? WHERE id = ? AND owner_note = ?${a?" AND pickup_at IS NULL":""}`).run(a?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 Yn(r){return Object.assign({channel:ge,chatId:r,sender:"operator"},{[fe]:!0})}function Vn(r){return!!r&&r[fe]===!0}function vt(r,n,t,a=!1){let o=E(n);if(r.channels.length&&!r.channels.map(E).includes(o))return!1;if(T.has(o))return a&&!At.has((t?.name??"").toLowerCase());let i=Rt.has(o)?t?.username:t?.id,l=i?ce(o,i):"";return l?r.from.some(d=>{let m=d.trim().toLowerCase(),b=m.indexOf(":");return b>0&&m.slice(0,b)===o&&ce(o,m.slice(b+1))===l}):!1}function Jn(r){if(!r)return;let n=a=>typeof a=="string"&&a?a.slice(0,120):void 0,t={name:n(r.sender),id:n(r.senderId),username:n(r.senderUsername)};return t.name||t.id||t.username?t:void 0}function It(r){return/\btimed? ?out\b|timeout/i.test(r)?"timed out":"failed"}var ge,fe,T,At,E,Rt,ce,_,S,me,pe=g(()=>{"use strict";de();ge="requests",fe=Symbol("requests.pickup");T=new Set(["voice","app","dashboard","webrtc"]),At=new Set(["camera"]),E=r=>r.toLowerCase().split("@")[0],Rt=new Set(["github","gitlab"]),ce=(r,n)=>r==="whatsapp"?n.replace(/@.*$/,"").replace(/\D/g,""):n.trim().toLowerCase().replace(/^@/,"");_=(r,n=200)=>{let t=r.replace(/\s+/g," ").trim();return t.length>n?`${t.slice(0,n-1)}\u2026`:t},S=(r,n,t)=>`${r}\0${n}\0${t}`,me=class{constructor(n,t,a,o=Date.now){this.store=n;this.settings=t;this.log=a;this.now=o}live=new Map;guard(n,t){try{t()}catch(a){this.log(`[requests] ${n} failed: ${a?.message??a}`)}}isListedOwner(n){let t=E(n.channel),a=this.settings().channels;return a.length&&!a.map(E).includes(t)?!1:n.person?.role==="owner"&&!T.has(t)}liveRequestId(n,t,a){return this.live.get(S(n,t,a))?.requestId??null}taskStarted(n){n.taskId&&this.guard("capture",()=>{if(!this.settings().enabled)return;let t=this.now(),a=n.resumedFrom?this.store.byLink("run",n.resumedFrom):null,o=S(n.agentId,n.channel,n.chatId);if(a){this.store.link(a.id,"run",n.taskId,t),a.state==="candidate"?this.store.touch(a.id,t):this.store.progress(a.id,t),this.live.set(o,{requestId:a.id,runId:n.taskId});return}let i=n.pickup&&n.channel===ge?this.store.get(n.chatId):null;if(i&&i.agentId===n.agentId){this.store.link(i.id,"run",n.taskId,t),this.store.touch(i.id,t),this.live.set(o,{requestId:i.id,runId:n.taskId});return}!n.humanRoot||!(vt(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 a=this.store.byLink("run",n.taskId);if(!a)return;let o=this.now();if(!n.interrupted){if(n.error&&n.errorKind!=="cancelled"){let i=It(n.error);this.store.needsAttention(a.id,`${n.agentId} ${i}: ${_(n.error)}`,o)&&this.log(`[requests] ${a.id} needs attention: run ${n.taskId} ${i}`);return}a.state==="candidate"?this.store.discardCandidate(a.id):this.store.touch(a.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 a=this.now();this.store.link(t.requestId,"delegation",n.id,a),this.store.progress(t.requestId,a,"waiting_other")})}delegationDone(n,t,a){this.guard("delegation end",()=>{let o=this.store.byLink("delegation",n.id);if(!o)return;let i=this.now(),l=n.peer?`${n.callee} on ${n.peer}`:n.callee;if(t==="done"){this.store.progress(o.id,i);return}let d={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} ${d}: ${_(a)}`,i)&&this.log(`[requests] ${o.id} needs attention: delegation ${n.id} ${t}`)})}cardRaised(n,t){t&&this.guard("card",()=>{if(!this.settings().enabled)return;let a=this.live.get(S(n.raised_by,t.channel,t.chatId))?.requestId;if(!a)return;let o=this.now();this.store.link(a,"card",n.id,o),this.store.waitOnOwner(a,n.ask,o)})}cardResolved(n){this.guard("card result",()=>{let t=this.store.byLink("card",n.id);if(!t)return;let a=this.now(),o=n.outcome??n.if_silent;n.status==="decided"?t.state==="waiting_owner"&&this.store.progress(t.id,a):this.store.needsAttention(t.id,`Your answer did not come before the card expired (${_(n.ask)}); "${o}" was applied`,a)&&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 a=this.now();n.decision==="resumed"?t.state==="candidate"?this.store.touch(t.id,a):this.store.progress(t.id,a):(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 (${_(n.reason)})`,a)&&this.log(`[requests] ${t.id} needs attention: run ${n.taskId} cut off by a restart`)})}}});import{randomBytes as Ct,timingSafeEqual as he}from"crypto";import{chmodSync as Ot,existsSync as jt,mkdirSync as Lt,readFileSync as Nt,writeFileSync as $t}from"fs";import{networkInterfaces as Pt}from"os";import{dirname as qt,resolve as Dt}from"path";function ar(r){return Object.assign(r,{[xe]:!0})}function ye(r){return!!r&&r[xe]===!0}function Bt(r=process.cwd()){return Dt(r,".agentx","operator.key")}function or(r=process.cwd(),n={}){let t=Bt(r);try{if(jt(t)){let o=Nt(t,"utf-8").trim();if(o)return o}if(!n.create)return null;let a=Ct(32).toString("hex");return Lt(qt(t),{recursive:!0}),$t(t,a+`
42
+ `,{mode:384}),Ot(t,384),a}catch{return null}}function Ut(r,n){let t=Array.isArray(n)?n[0]:n;if(!r||!t)return!1;let a=Buffer.from(r),o=Buffer.from(t.trim());return a.length===o.length&&he(a,o)}function zt(r,n,t,a){if(!r||typeof r!="object")return!1;let o=String(r.channel??"").toLowerCase().split("@")[0];return a.has(o)?Ut(t,n[Mt]):!1}function Ht(r,n){let t=r[Ft];if((Array.isArray(t)?t[0]:t)!=="1")return!1;let a=r.authorization,o=(Array.isArray(a)?a[0]:a)||"",i=o.toLowerCase().startsWith("bearer ")?o.slice(7).trim():"";if(!i)return!1;let l=Buffer.from(i);for(let d of n){if(!d)continue;let m=Buffer.from(d);if(m.length===l.length&&he(m,l))return!0}return!1}function Wt(r,n=Kt()){let t=be(r??"");if(!t||t==="::1"||t.startsWith("127."))return!0;for(let a of n)if(be(a)===t)return!0;return!1}function Kt(){return Object.values(Pt()).flatMap(r=>(r??[]).map(n=>n.address))}function ir(r,n,t){if(zt(r,n.headers,t.key,t.operatorChannels))return!0;if(!r||typeof r!="object")return!1;let a=String(r.channel??"").toLowerCase().split("@")[0];return!t.operatorChannels.has(a)||Wt(n.remoteAddress,t.ownAddresses)?!1:Ht(n.headers,t.peerTokens)}var Mt,xe,Ft,be,Se=g(()=>{"use strict";Mt="x-agentx-operator",xe=Symbol("requests.operator");Ft="x-agentx-operator-vouch";be=r=>r.toLowerCase().replace(/^::ffff:/,"").replace(/%.*$/,"")});function mr(r,n){return r.find(t=>t.id===n)?.name??(n===A?"Owner":n)}function ke(r,n){let t=n.trim().toLowerCase();return r==="whatsapp"?t.replace(/@.*$/,"").replace(/\D/g,""):t.replace(/^@/,"")}function we(r){let n=r.indexOf(":");if(n<=0||n===r.length-1)return null;let t=P(r.slice(0,n).trim()),a=ke(t,r.slice(n+1));return a?{channel:t,value:a}:null}function _e(r){let n=new Set,t=new Map;for(let a of r){if(n.has(a.id))return`person "${a.id}" is listed twice`;if(n.add(a.id),a.id===A&&a.role!=="owner")return`the id "${A}" is kept for a person with the owner role`;for(let o of a.identities){let i=we(o);if(!i)return`identity "${o}" of "${a.id}" must be written channel:id`;let l=`${i.channel}:${i.value}`,d=t.get(l);if(d&&d!==a.id)return`identity "${o}" belongs to both "${d}" and "${a.id}"`;t.set(l,a.id)}}return null}function Xt(r,n,t){let a=P(n),i=(a==="whatsapp"?[t?.id]:[t?.id,t?.username]).filter(l=>typeof l=="string"&&!!l).map(l=>ke(a,l)).filter(Boolean);return i.length?r.find(l=>l.identities.some(d=>{let m=we(d);return!!m&&m.channel===a&&i.includes(m.value)}))??null:null}function Zt(r){let n=r.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(r,n){let t=M(n);if(t)return t.person?{id:t.person}:null;if(!n||B(n)!=="human")return null;let a=String(n.channel??"");if(T.has(P(a)))return ye(n)?Zt(r):null;let o=l=>typeof l=="string"?l:void 0,i=Xt(r,a,{id:o(n.senderId),username:o(n.senderUsername)});return i?{id:i.id,role:i.role}:null}function Gt(r,n){let t=r.agents??[];return r.role==="owner"||t.length===0||t.includes(n)}function gr(r,n,t){let a=Ee(r,t);if(!a)return null;let o=r.find(l=>l.id===a.id);if(!o||Gt(o,n))return null;let i=(o.agents??[]).join(", ");return{person:o,note:`${o.name}, you can reach ${i} here, not ${n}. Ask the owner if you need ${n}.`}}function fr(r,n){let t=r.trim().split("*").map(a=>a.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${t}$`,"i").test(n.trim())}function pr(r,n){let t=Ee(r,n);if(!t)return null;let a=r.find(l=>l.id===t.id);if(!a||a.role==="owner")return null;let o=a.deny?.tools??[],i=a.deny?.skills??[];return!o.length&&!i.length?null:{personId:a.id,name:a.name,tools:[...o],skills:[...i]}}var cr,A,P,Te=g(()=>{"use strict";Ge();pe();Se();cr=["owner","member","client","guest"],A="owner";P=r=>r.toLowerCase().split("@")[0]});function xr(r){return typeof r=="string"&&Vt.includes(r)}function Ae(r){let n=new Set(Yt);return r.map(t=>t.trim()).filter(t=>t&&!n.has(t))}var Yt,Vt,hr,Re=g(()=>{"use strict";Yt=["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"],Vt=["read","full"],hr=["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 Tn={};Xe(Tn,{INTEGRATION_KINDS:()=>on,WIKI_CONTRIBUTE_JOB:()=>He,WIKI_CONTRIBUTE_MERGE_JOB:()=>We,approvalsConfigSchema:()=>Fe,callsSchema:()=>Pe,cameraBotSchema:()=>Ne,daemonConfigSchema:()=>ze,eventSubscriptionSchema:()=>Le,expandEnvVars:()=>C,loadDaemonConfig:()=>wn,membersConfigSchema:()=>Be,peopleConfigSchema:()=>Me,personSchema:()=>De,requestStatusConfigSchema:()=>Ue,requestsConfigSchema:()=>qe,validateWorkspaces:()=>_n,withContributionJobs:()=>Ke});import{z as e}from"zod";import{readFileSync as Ie,existsSync as v}from"fs";import{resolve as I}from"path";function Jt(r){let n=I(r,".env");if(!v(n))return;let t=Ie(n,"utf-8");for(let a of t.split(`
43
+ `)){let o=a.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i===-1)continue;let l=o.slice(0,i).trim(),d=o.slice(i+1).trim();process.env[l]||(process.env[l]=d)}}function C(r){if(typeof r=="string")return r.replace(/\$\{(\w+)\}/g,(n,t)=>process.env[t]||"");if(Array.isArray(r))return r.map(C);if(r!==null&&typeof r=="object"){let n={};for(let[t,a]of Object.entries(r))n[t]=C(a);return n}return r}function kn(r,n){let t=[],a=new Set;for(let o of r){let i=o.path.join("."),l=/^channels\.telegram\.accounts\.([^.]+)\.token$/.exec(i);if(l&&o.message.toLowerCase().includes("required")){let d=l[1],m=`tg:${d}`;if(a.has(m))continue;a.add(m),t.push(`Hint: Telegram account "${d}" is enabled but has no bot token.
44
+ Either:
45
+ A) Open ${n} and set channels.telegram.accounts.${d}.token to your bot token (or "\${TG_${d.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.${d}).`)}}return t}function wn(r){let n=r?[r]:[I(process.cwd(),"agentx.json"),I(process.cwd(),".agentx/config.json")];Jt(process.cwd());let t,a;for(let d of n)if(v(d)){t=Ie(d,"utf-8"),a=d;break}if(!t||!a)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(d){throw new Error(`Invalid JSON in ${a}: ${d.message}`)}let i=C(o),l=ze.safeParse(i);if(!l.success){let d=l.error.issues.map(q=>` ${q.path.join(".")}: ${q.message}`).join(`
48
+ `),m=kn(l.error.issues,a),b=m.length?`
49
+
50
+ ${m.join(`
51
+
52
+ `)}`:"";throw new Error(`Config validation failed (${a}):
53
+ ${d}${b}`)}return Ke(l.data)}function _n(r){let n=[];for(let[t,a]of Object.entries(r.agents)){if(!v(a.workspace)){n.push(`Agent "${t}": workspace not found at ${a.workspace}`);continue}if(a.tier==="claude-code"){let l=I(a.workspace,".claude");v(l)||n.push(`Agent "${t}": no .claude/ directory in workspace ${a.workspace}. Claude Code native features (hooks, MCP, skills) won't be available.`)}let o=a.provider||"claude",i=r.providers[o];!["claude-code","codex-cli","opencode"].includes(a.tier)&&(!i||!i.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,a]of Object.entries(r.crons))r.agents[a.agent]||n.push(`Cron "${t}": references unknown agent "${a.agent}"`);if(r.channels.telegram.enabled)for(let[t,a]of Object.entries(r.channels.telegram.accounts))r.agents[a.agentBinding]||n.push(`Telegram account "${t}": references unknown agent "${a.agentBinding}"`);return n}function Ke(r,n=En()){let t=Object.entries(r.agents).filter(([,l])=>l.wiki?.contribute?.enabled).map(([l])=>l).sort();if(t.length===0)return r;let a=r.wiki.contributions,o=(l,d)=>$e.parse({schedule:l,timezone:a.timezone,agent:t[0],command:d,timeout:3600,onError:"log"}),i={[He]:o(a.schedule,`${n} wiki contribute --all`),[We]:o(a.mergeSchedule,`${n} wiki contributions merge`)};return{...r,crons:{...i,...r.crons}}}function En(){let r=process.argv[1]??"";return/[\\/]cli\.(?:c|m)?js$/.test(r)?`"${process.execPath}" "${r}"`:"agentx"}var ve,Qt,en,tn,nn,rn,an,on,Ce,Oe,R,je,Le,sn,ln,Ne,un,$e,dn,cn,mn,gn,fn,pn,bn,hn,Pe,xn,yn,Sn,qe,De,Me,Be,Ue,Fe,ze,He,We,An=g(()=>{H();X();Ze();Y();ee();re();oe();le();Te();Re();ve=e.array(e.string().min(1)).superRefine((r,n)=>{let t=Ae(r);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__".`})}),Qt=e.object({apiKey:e.string().optional(),defaultModel:e.string().optional(),baseUrl:e.string().optional(),thinking:e.boolean().optional()}),en=e.object({type:e.literal("stdio").optional(),command:e.string(),args:e.array(e.string()).default([]),env:e.record(e.string(),e.string()).optional()}),tn=e.object({type:e.literal("http"),url:e.string().url(),headers:e.record(e.string(),e.string()).optional()}),nn=e.union([tn,en]),rn=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(),an=e.object({kind:e.string().min(1),label:e.string().min(1),credentials:rn.default({}),metadata:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()])).default({}),enabled:e.boolean().default(!0)}),on=["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"]),Oe=e.union([e.string(),e.record(e.string(),e.string())]),R=e.string().superRefine((r,n)=>{let t=G(r);t&&n.addIssue({code:e.ZodIssueCode.custom,message:`shortcut ${t}`})}),je=e.object({provider:Ce.optional(),system:Oe.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()}),Le=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)}),sn=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(),nn).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(),wiki:e.object({contribute:e.object({enabled:e.boolean().default(!1),maxPatches:e.number().int().min(1).max(200).default(30),maxCostUsd:e.number().min(0).max(20).optional(),model:e.string().optional()}).default({})}).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(Le).default([]),integrations:e.array(an).default([]),voice:je.optional(),presence:e.object({color:e.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),palette:e.enum(O).optional(),initial:e.string().max(2).optional(),label:e.string().optional(),allowActions:e.boolean().optional()}).optional()}),ln=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({}),un=e.object({telegram:e.object({enabled:e.boolean().default(!1),accounts:e.record(e.string(),ln).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({})}),$e=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(r=>Array.isArray(r)?r:[r]),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(r=>!!(r.command?.trim()||r.prompt?.trim()),{message:"a cron needs either a prompt (dispatch an agent) or a command (run it directly)"}).refine(r=>!(r.command?.trim()&&r.autonomy&&r.autonomy!=="act"),{message:"autonomy applies to agent routines; a command cron runs no agent (remove autonomy or the command)"}),dn=e.object({enabled:e.boolean().default(!1),inbox:e.string().min(1).optional(),crons:e.array(e.string().min(1)).default([]),maxNotesPerRun:e.number().int().min(1).max(100).default(20),maxDeferrals:e.number().int().min(1).max(20).default(3)}).refine(r=>!r.enabled||!!r.inbox,{message:"wikiNotes.enabled needs wikiNotes.inbox: the agent that runs the wiki observe/sweep schedule"}),cn=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()}),mn=e.object({url:e.string(),name:e.string(),token:e.string().optional()}),gn=e.object({name:e.string(),agent:e.string(),enabled:e.boolean().default(!0)}),fn=e.object({enabled:e.boolean().default(!1),peers:e.array(mn).default([]),inboxes:e.array(gn).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({})}),pn=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({}),bn=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({}),hn=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(),bn).default({}),routing:e.object({cheapModel:e.string().optional(),cheapModels:e.object({"claude-code":e.string().optional(),"codex-cli":e.string().optional()}).optional()}).default({})}).default({}),Pe=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({}),xn=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({}),yn=e.object({x:e.number(),y:e.number(),width:e.number().positive(),height:e.number().positive()}),Sn=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-]*$/),yn).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({}),De=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({})}),Me=e.array(De).default([]).superRefine((r,n)=>{let t=_e(r);t&&n.addIssue({code:e.ZodIssueCode.custom,message:t})}),Be=e.object({logRetentionDays:e.number().int().min(1).max(3650).default(90)}).default({}),Ue=e.object({channels:e.array(e.string().min(1)).default([])}).default({}),Fe=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(r=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:r}),!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(r=>{try{return new Intl.DateTimeFormat("en-US",{timeZone:r}),!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({}),ze=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(),Qt).default({}),agents:e.record(e.string(),sn).default({}),wiki:e.object({contributions:e.object({schedule:e.string().default("40 22 * * *"),mergeSchedule:e.string().default("20 23 * * *"),timezone:e.string().default("UTC"),maxCostUsd:e.number().min(0).max(20).default(.5),model:e.string().default("sonnet")}).default({}),query:e.object({shared:e.boolean().default(!0)}).default({})}).default({}),channels:un.default({}),crons:e.record(e.string(),$e).default({}),wikiNotes:dn.default({}),services:e.record(e.string(),cn).default({}),notifications:xn,calls:Pe,whatsappTriage:se,approvals:Fe,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:Me,members:Be,requestStatus:Ue,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:Sn,mesh:fn.default({}),meshVoices:e.record(e.string(),je.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:Oe.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(j),noiseFilter:e.object({enabled:e.boolean().default(!0),markers:e.array(e.string()).default(L)}).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(O).default(w),card:e.object({timeout:e.number().min(0).max(600).default(30),maxHeight:e.number().min(120).max(800).default(320)}).default({})}).default({}),business:z.optional(),boards:W,dashboard:K,graph:pn,decisions:hn,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({})});He="wiki-contribute",We="wiki-contribute-merge"});export{Cn as a,On as b,X as c,xt as d,Ln as e,k as f,Y as g,y as h,V as i,J as j,O as k,$n as l,ee as m,te as n,ne as o,Mn as p,re as q,Un as r,Fn as s,oe as t,se as u,le as v,x as w,f as x,N as y,Xn as z,ue as A,de as B,Yn as C,Vn as D,T as E,Jn as F,me as G,pe as H,Mt as I,ar as J,ye as K,or as L,zt as M,ir as N,Se as O,cr as P,A as Q,mr as R,we as S,Xt as T,Zt as U,Ee as V,gr as W,fr as X,pr as Y,Te as Z,Vt as _,hr as $,xr as aa,Re as ba,on as ca,Le as da,Ne as ea,Pe as fa,qe as ga,De as ha,Me as ia,Be as ja,Ue as ka,Fe as la,ze as ma,C as na,wn as oa,_n as pa,He as qa,We as ra,Ke as sa,Tn as ta,An as ua};
54
+ //# sourceMappingURL=chunk-MRYA4J5F.js.map