agentix-cli 0.182.0 → 0.184.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 (165) hide show
  1. package/apps/mac-helper/Sources/AgentXHelper/Presence.swift +9 -0
  2. package/apps/mac-helper/Sources/AgentXHelper/PresenceTag.swift +25 -9
  3. package/dist/{App-XWSSUYKF.js → App-WIHCYMHM.js} +2 -2
  4. package/dist/{ChatApp-UT2BRHYE.js → ChatApp-V3UASKNG.js} +2 -2
  5. package/dist/{absorb-eval-SFGUURBD.js → absorb-eval-EAGXITJH.js} +2 -2
  6. package/dist/{adapter-UHR7FVM7.js → adapter-7IDPCEJ7.js} +2 -2
  7. package/dist/{agent-5NTFSCEO.js → agent-H75SWYT6.js} +2 -2
  8. package/dist/{board-dashboard-7HIME2W4.js → board-dashboard-MHPJY4JB.js} +709 -2204
  9. package/dist/board-dashboard-MHPJY4JB.js.map +1 -0
  10. package/dist/{chunk-QGNV2HA4.js → chunk-2GIYVYIM.js} +2 -2
  11. package/dist/{chunk-5YG2ZQQW.js → chunk-2LTZUZJU.js} +3 -3
  12. package/dist/{chunk-343MPMLD.js → chunk-2V6ZGE74.js} +2 -2
  13. package/dist/{chunk-4KNHLHE3.js → chunk-4HYIERJ4.js} +2 -2
  14. package/dist/{chunk-XHJ5SVO5.js → chunk-4IKZSV5A.js} +302 -297
  15. package/dist/chunk-4IKZSV5A.js.map +1 -0
  16. package/dist/{chunk-QB6UPODO.js → chunk-56F5UTTA.js} +2 -2
  17. package/dist/chunk-5ELIX7BQ.js +3 -0
  18. package/dist/chunk-5ELIX7BQ.js.map +1 -0
  19. package/dist/{chunk-NIPMVM3G.js → chunk-7EMPPP3E.js} +2 -2
  20. package/dist/{chunk-IFHVAHQM.js → chunk-A4PW7EIK.js} +2 -2
  21. package/dist/chunk-AHWWJ7AF.js +2 -0
  22. package/dist/chunk-AHWWJ7AF.js.map +1 -0
  23. package/dist/{chunk-7WGJZLVJ.js → chunk-BITVUKT7.js} +2 -2
  24. package/dist/{chunk-MD2HCGSC.js → chunk-BZJF7DJR.js} +3 -3
  25. package/dist/chunk-BZJF7DJR.js.map +1 -0
  26. package/dist/{chunk-5NGQQOVK.js → chunk-CVPERUWT.js} +2 -2
  27. package/dist/chunk-CZMVJP7O.js +2 -0
  28. package/dist/chunk-CZMVJP7O.js.map +1 -0
  29. package/dist/chunk-DPV4M4AQ.js +2903 -0
  30. package/dist/chunk-DPV4M4AQ.js.map +1 -0
  31. package/dist/{chunk-GEFZMDDX.js → chunk-FJMTCU4S.js} +2 -2
  32. package/dist/{chunk-IGBW4VVM.js → chunk-GSQ2RCOZ.js} +2 -2
  33. package/dist/chunk-I5TUF6U7.js +888 -0
  34. package/dist/chunk-I5TUF6U7.js.map +1 -0
  35. package/dist/{chunk-YX4R2VGD.js → chunk-LR4QUAJT.js} +2 -2
  36. package/dist/{chunk-RDWDDPBI.js → chunk-NBWSZ53L.js} +2 -2
  37. package/dist/{chunk-4WSJKKSA.js → chunk-NHW4IY6N.js} +2 -2
  38. package/dist/{chunk-FDX4IGLK.js → chunk-NS2HSAHF.js} +2 -2
  39. package/dist/{chunk-YSPBVLTZ.js → chunk-OJ53ATNN.js} +2 -2
  40. package/dist/{chunk-JNWXHOJE.js → chunk-PN42ECV3.js} +2 -2
  41. package/dist/{chunk-Y4TVCWWF.js → chunk-R2KSORSK.js} +2 -2
  42. package/dist/{chunk-FYFJ7IQJ.js → chunk-RTIGD4NG.js} +2 -2
  43. package/dist/{chunk-Y5TBOMHY.js → chunk-UASRZKZQ.js} +6 -6
  44. package/dist/{chunk-H2KOXGDX.js → chunk-V4IOGISL.js} +2 -2
  45. package/dist/{chunk-Z4XVPGPZ.js → chunk-V6QFBL6F.js} +3 -3
  46. package/dist/{chunk-XI2HH5NR.js → chunk-WKHRKYCY.js} +2 -2
  47. package/dist/{chunk-BY3AUZYM.js → chunk-YTS54UZ5.js} +2 -2
  48. package/dist/cli.js +1 -1
  49. package/dist/{client-SQMU25PS.js → client-57TCFIV5.js} +2 -2
  50. package/dist/{compaction-26OHHULF.js → compaction-R7VWQB6X.js} +2 -2
  51. package/dist/{config-56NBA4SF.js → config-RHCIE7VE.js} +2 -2
  52. package/dist/{config-mutate-PD4O3HZ7.js → config-mutate-HCYXR2WP.js} +2 -2
  53. package/dist/config-mutator-JQ2R4J5Z.js +2 -0
  54. package/dist/{contributions-DKTJ623L.js → contributions-R4HXLJXU.js} +2 -2
  55. package/dist/{doctor-OI6GJZR5.js → doctor-22PZVT6A.js} +2 -2
  56. package/dist/{follow-up-tool-DYSLS6ZI.js → follow-up-tool-MC4TBGLP.js} +2 -2
  57. package/dist/hub-HXVIO4U5.js +2 -0
  58. package/dist/index.d.ts +55 -1
  59. package/dist/index.js +1 -1
  60. package/dist/{program-4GDIWCDM.js → program-736BTK4B.js} +260 -259
  61. package/dist/program-736BTK4B.js.map +1 -0
  62. package/dist/{promote-3272TZNI.js → promote-D24WO52J.js} +2 -2
  63. package/dist/push-bridge-NR7SLHGX.js +1 -1
  64. package/dist/{query-7XM6V4QG.js → query-J5NRZZUQ.js} +2 -2
  65. package/dist/{query-settings-HHVBIIVQ.js → query-settings-NT6ACLQY.js} +2 -2
  66. package/dist/{registry-QL3AM3UH.js → registry-SBIZVSQV.js} +2 -2
  67. package/dist/{request-planner-WNEDEA7X.js → request-planner-2CVL22EB.js} +2 -2
  68. package/dist/{review-candidates-TGPDJMWJ.js → review-candidates-MMNDJOTD.js} +2 -2
  69. package/dist/{routing-ALXY25NE.js → routing-KRST324W.js} +2 -2
  70. package/dist/schedule-tool-KOFUKVX5.js +2 -0
  71. package/dist/{scheduler-5PHNW243.js → scheduler-GCCE4FQP.js} +2 -2
  72. package/dist/{seat-ZYVVEILY.js → seat-E6F56TUM.js} +2 -2
  73. package/dist/{select-6QLEV6AC.js → select-D2VUSUCJ.js} +2 -2
  74. package/dist/self-SO6GCVYD.js +2 -0
  75. package/dist/{set-enabled-SYYTKJPC.js → set-enabled-GBI7JREU.js} +2 -2
  76. package/dist/signal-exit-C5EUGHKI.js +3 -0
  77. package/dist/signal-exit-C5EUGHKI.js.map +1 -0
  78. package/dist/{sprint-tool-PYVHPHR2.js → sprint-tool-HZ24VIC2.js} +2 -2
  79. package/dist/{tool-GIYOYXXM.js → tool-7BEFI5SJ.js} +2 -2
  80. package/dist/{tool-ZKZ4KYJT.js → tool-OXZ4TQBG.js} +2 -2
  81. package/dist/{tool-TDOUM3BJ.js → tool-QLQEYQYM.js} +2 -2
  82. package/dist/wiki-RFDU6SVD.js +2 -0
  83. package/dist/wiki-enrich-LDI67VQU.js +2 -0
  84. package/package.json +4 -1
  85. package/dist/board-dashboard-7HIME2W4.js.map +0 -1
  86. package/dist/chunk-7PQQZC6B.js +0 -310
  87. package/dist/chunk-7PQQZC6B.js.map +0 -1
  88. package/dist/chunk-MD2HCGSC.js.map +0 -1
  89. package/dist/chunk-NRUUT5TL.js +0 -256
  90. package/dist/chunk-NRUUT5TL.js.map +0 -1
  91. package/dist/chunk-OKADR5QO.js +0 -869
  92. package/dist/chunk-OKADR5QO.js.map +0 -1
  93. package/dist/chunk-QOYAX2FT.js +0 -2
  94. package/dist/chunk-QOYAX2FT.js.map +0 -1
  95. package/dist/chunk-R3CDFSNF.js +0 -580
  96. package/dist/chunk-R3CDFSNF.js.map +0 -1
  97. package/dist/chunk-XHJ5SVO5.js.map +0 -1
  98. package/dist/chunk-ZRALOFEG.js +0 -2035
  99. package/dist/chunk-ZRALOFEG.js.map +0 -1
  100. package/dist/config-mutator-ITL64FBW.js +0 -2
  101. package/dist/hub-4HDMTSR7.js +0 -2
  102. package/dist/processes-M7YPWX7H.js +0 -2
  103. package/dist/program-4GDIWCDM.js.map +0 -1
  104. package/dist/schedule-tool-22UBZXCG.js +0 -2
  105. package/dist/signal-exit-WL7G3EEZ.js +0 -2
  106. package/dist/signal-exit-WL7G3EEZ.js.map +0 -1
  107. package/dist/wiki-ZRGLGMII.js +0 -2
  108. package/dist/wiki-enrich-CTID7JQW.js +0 -2
  109. /package/dist/{App-XWSSUYKF.js.map → App-WIHCYMHM.js.map} +0 -0
  110. /package/dist/{ChatApp-UT2BRHYE.js.map → ChatApp-V3UASKNG.js.map} +0 -0
  111. /package/dist/{absorb-eval-SFGUURBD.js.map → absorb-eval-EAGXITJH.js.map} +0 -0
  112. /package/dist/{adapter-UHR7FVM7.js.map → adapter-7IDPCEJ7.js.map} +0 -0
  113. /package/dist/{agent-5NTFSCEO.js.map → agent-H75SWYT6.js.map} +0 -0
  114. /package/dist/{chunk-QGNV2HA4.js.map → chunk-2GIYVYIM.js.map} +0 -0
  115. /package/dist/{chunk-5YG2ZQQW.js.map → chunk-2LTZUZJU.js.map} +0 -0
  116. /package/dist/{chunk-343MPMLD.js.map → chunk-2V6ZGE74.js.map} +0 -0
  117. /package/dist/{chunk-4KNHLHE3.js.map → chunk-4HYIERJ4.js.map} +0 -0
  118. /package/dist/{chunk-QB6UPODO.js.map → chunk-56F5UTTA.js.map} +0 -0
  119. /package/dist/{chunk-NIPMVM3G.js.map → chunk-7EMPPP3E.js.map} +0 -0
  120. /package/dist/{chunk-IFHVAHQM.js.map → chunk-A4PW7EIK.js.map} +0 -0
  121. /package/dist/{chunk-7WGJZLVJ.js.map → chunk-BITVUKT7.js.map} +0 -0
  122. /package/dist/{chunk-5NGQQOVK.js.map → chunk-CVPERUWT.js.map} +0 -0
  123. /package/dist/{chunk-GEFZMDDX.js.map → chunk-FJMTCU4S.js.map} +0 -0
  124. /package/dist/{chunk-IGBW4VVM.js.map → chunk-GSQ2RCOZ.js.map} +0 -0
  125. /package/dist/{chunk-YX4R2VGD.js.map → chunk-LR4QUAJT.js.map} +0 -0
  126. /package/dist/{chunk-RDWDDPBI.js.map → chunk-NBWSZ53L.js.map} +0 -0
  127. /package/dist/{chunk-4WSJKKSA.js.map → chunk-NHW4IY6N.js.map} +0 -0
  128. /package/dist/{chunk-FDX4IGLK.js.map → chunk-NS2HSAHF.js.map} +0 -0
  129. /package/dist/{chunk-YSPBVLTZ.js.map → chunk-OJ53ATNN.js.map} +0 -0
  130. /package/dist/{chunk-JNWXHOJE.js.map → chunk-PN42ECV3.js.map} +0 -0
  131. /package/dist/{chunk-Y4TVCWWF.js.map → chunk-R2KSORSK.js.map} +0 -0
  132. /package/dist/{chunk-FYFJ7IQJ.js.map → chunk-RTIGD4NG.js.map} +0 -0
  133. /package/dist/{chunk-Y5TBOMHY.js.map → chunk-UASRZKZQ.js.map} +0 -0
  134. /package/dist/{chunk-H2KOXGDX.js.map → chunk-V4IOGISL.js.map} +0 -0
  135. /package/dist/{chunk-Z4XVPGPZ.js.map → chunk-V6QFBL6F.js.map} +0 -0
  136. /package/dist/{chunk-XI2HH5NR.js.map → chunk-WKHRKYCY.js.map} +0 -0
  137. /package/dist/{chunk-BY3AUZYM.js.map → chunk-YTS54UZ5.js.map} +0 -0
  138. /package/dist/{client-SQMU25PS.js.map → client-57TCFIV5.js.map} +0 -0
  139. /package/dist/{compaction-26OHHULF.js.map → compaction-R7VWQB6X.js.map} +0 -0
  140. /package/dist/{config-56NBA4SF.js.map → config-RHCIE7VE.js.map} +0 -0
  141. /package/dist/{config-mutate-PD4O3HZ7.js.map → config-mutate-HCYXR2WP.js.map} +0 -0
  142. /package/dist/{config-mutator-ITL64FBW.js.map → config-mutator-JQ2R4J5Z.js.map} +0 -0
  143. /package/dist/{contributions-DKTJ623L.js.map → contributions-R4HXLJXU.js.map} +0 -0
  144. /package/dist/{doctor-OI6GJZR5.js.map → doctor-22PZVT6A.js.map} +0 -0
  145. /package/dist/{follow-up-tool-DYSLS6ZI.js.map → follow-up-tool-MC4TBGLP.js.map} +0 -0
  146. /package/dist/{hub-4HDMTSR7.js.map → hub-HXVIO4U5.js.map} +0 -0
  147. /package/dist/{processes-M7YPWX7H.js.map → promote-D24WO52J.js.map} +0 -0
  148. /package/dist/{promote-3272TZNI.js.map → query-J5NRZZUQ.js.map} +0 -0
  149. /package/dist/{query-settings-HHVBIIVQ.js.map → query-settings-NT6ACLQY.js.map} +0 -0
  150. /package/dist/{query-7XM6V4QG.js.map → registry-SBIZVSQV.js.map} +0 -0
  151. /package/dist/{request-planner-WNEDEA7X.js.map → request-planner-2CVL22EB.js.map} +0 -0
  152. /package/dist/{review-candidates-TGPDJMWJ.js.map → review-candidates-MMNDJOTD.js.map} +0 -0
  153. /package/dist/{registry-QL3AM3UH.js.map → routing-KRST324W.js.map} +0 -0
  154. /package/dist/{routing-ALXY25NE.js.map → schedule-tool-KOFUKVX5.js.map} +0 -0
  155. /package/dist/{schedule-tool-22UBZXCG.js.map → scheduler-GCCE4FQP.js.map} +0 -0
  156. /package/dist/{scheduler-5PHNW243.js.map → seat-E6F56TUM.js.map} +0 -0
  157. /package/dist/{select-6QLEV6AC.js.map → select-D2VUSUCJ.js.map} +0 -0
  158. /package/dist/{seat-ZYVVEILY.js.map → self-SO6GCVYD.js.map} +0 -0
  159. /package/dist/{set-enabled-SYYTKJPC.js.map → set-enabled-GBI7JREU.js.map} +0 -0
  160. /package/dist/{sprint-tool-PYVHPHR2.js.map → sprint-tool-HZ24VIC2.js.map} +0 -0
  161. /package/dist/{tool-GIYOYXXM.js.map → tool-7BEFI5SJ.js.map} +0 -0
  162. /package/dist/{tool-ZKZ4KYJT.js.map → tool-OXZ4TQBG.js.map} +0 -0
  163. /package/dist/{tool-TDOUM3BJ.js.map → tool-QLQEYQYM.js.map} +0 -0
  164. /package/dist/{wiki-ZRGLGMII.js.map → wiki-RFDU6SVD.js.map} +0 -0
  165. /package/dist/{wiki-enrich-CTID7JQW.js.map → wiki-enrich-LDI67VQU.js.map} +0 -0
@@ -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-YX4R2VGD.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-LR4QUAJT.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-QB6UPODO.js.map
6
+ //# sourceMappingURL=chunk-56F5UTTA.js.map
@@ -0,0 +1,3 @@
1
+ import{createHash as B}from"crypto";import{mkdirSync as I,readdirSync as T,readFileSync as v,renameSync as E,rmSync as d,writeFileSync as y}from"fs";import{resolve as c}from"path";var P=["agent","person"],x=1024*1024,m=512,F="image/webp",N="/api/agent-picture",w=/^[a-z0-9][a-z0-9_-]{0,63}$/,K=/^[0-9a-f]{16}$/,R=/^([a-z0-9][a-z0-9_-]{0,63})\.([0-9a-f]{16})\.webp$/,s=class extends Error{constructor(r,n=400){super(r);this.status=n}};function f(t,e){return e?c(t,".agentx","pictures",e):c(t,".agentx","pictures")}function _(t){if(t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"png";if(t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255)return"jpeg";if(t.length>=12&&t.toString("latin1",0,4)==="RIFF"&&t.toString("latin1",8,12)==="WEBP")return"webp";let e=t.toString("utf8",0,Math.min(t.length,512)).trimStart().toLowerCase();throw e.startsWith("<svg")||e.startsWith("<?xml")&&e.includes("<svg")||e.startsWith("<!doctype svg")?new s("SVG pictures are not accepted. Use a PNG, JPEG or WebP file."):new s("That file is not a picture. Use a PNG, JPEG or WebP file.")}function S(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${Math.ceil(t/1024)} KB`}var g=null;function M(){return g??=import("sharp").then(t=>t.default??t).catch(t=>{throw g=null,new s(`Pictures need the "sharp" package, which is not installed here (${t?.message??t}). Reinstall AgentX, or run: npm install -g sharp`,503)}),g}async function U(t){if(!t.length)throw new s("The file is empty. Use a PNG, JPEG or WebP picture.");if(t.length>x)throw new s(`The picture is ${S(t.length)}; the limit is 1 MB. Make it smaller and try again.`,413);_(t);let e=await M();try{return await e(t,{failOn:"error",limitInputPixels:5e7}).rotate().resize(m,m,{fit:"cover",position:"centre"}).webp({quality:85}).toBuffer()}catch(r){throw new s(`The picture could not be read (${String(r?.message??r).split(`
2
+ `)[0]}). Try another file.`)}}function $(t,e){if(!P.includes(t))throw new s(`unknown kind "${t}"`);if(!w.test(e))throw new s(`"${e}" is not a valid ${t} id`)}function p(t,e){let r;try{r=T(f(t,e))}catch{return[]}return r.flatMap(n=>{let i=n.match(R);return i?[{id:i[1],version:i[2],name:n}]:[]})}function A(t,e){let r={};for(let n of p(t,e))r[n.id]=n.version;return r}function D(t,e,r){return p(t,e).find(n=>n.id===r)?.version??null}function C(t,e,r){return`/api/pictures/${t}/${encodeURIComponent(e)}?v=${r}`}function J(t,e,r,n){if(!P.includes(e)||!w.test(r)||!K.test(n))return null;let i=c(f(t,e),`${r}.${n}.webp`);try{return v(i)}catch{return null}}async function L(t,e,r,n){$(e,r);let i=await U(n),o=B("sha256").update(i).digest("hex").slice(0,16),a=f(t,e);I(a,{recursive:!0});let u=`${r}.${o}.webp`,h=c(a,`.${u}.${process.pid}.tmp`);y(h,i),E(h,c(a,u));for(let l of p(t,e))l.id===r&&l.name!==u&&d(c(a,l.name),{force:!0});return{version:o,url:C(e,r,o)}}function O(t,e,r){$(e,r);let n=f(t,e),i=p(t,e).filter(o=>o.id===r);for(let o of i)d(c(n,o.name),{force:!0});return i.length>0}function V(t,e=x){return new Promise((r,n)=>{let i=[],o=0,a=!1;t.on("data",u=>{o+=u.length,o>e?(a=!0,i.length=0):a||i.push(u)}),t.on("end",()=>a?n(new s(`The picture is ${S(o)}; the limit is 1 MB. Make it smaller and try again.`,413)):r(Buffer.concat(i))),t.on("error",n)})}export{P as a,x as b,F as c,N as d,w as e,s as f,_ as g,A as h,D as i,C as j,J as k,L as l,O as m,V as n};
3
+ //# sourceMappingURL=chunk-5ELIX7BQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pictures/pictures.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { IncomingMessage } from \"http\"\n\n// --- Profile pictures for agents and people (#1425) ---\n//\n// Every member of the org may have one picture: an agent (agentx.json\n// `agents`) or a person (agentx.json `people`). It is set by hand (Settings\n// for an agent, People for a person) or by an agent for itself\n// (`agentx agent picture set <file>`). Every path goes through\n// preparePicture: PNG, JPEG or WebP only, 1 MB at most, re-encoded to a\n// 512×512 square WebP. Re-encoding drops EXIF, GPS and every other\n// metadata block, and anything hidden after the image data.\n//\n// The pictures live under the daemon's folder, never in agentx.json:\n// .agentx/pictures/agent/<id>.<version>.webp\n// .agentx/pictures/person/<id>.<version>.webp\n// The version is the start of the picture's sha256, so a new picture is a\n// new address: browsers keep a picture for good and a change shows on the\n// next page load, with no restart. The CLI, the daemon and the dashboard\n// are separate processes; each reads the folder.\n\nexport type PictureKind = \"agent\" | \"person\"\nexport const PICTURE_KINDS: readonly PictureKind[] = [\"agent\", \"person\"]\n\n/** The largest file accepted, before re-encoding. */\nexport const PICTURE_MAX_BYTES = 1024 * 1024\n/** The side of the square every picture is re-encoded to. */\nexport const PICTURE_SIDE = 512\nexport const PICTURE_TYPE = \"image/webp\"\n/** The daemon route an agent sets its own picture through. */\nexport const AGENT_PICTURE_PATH = \"/api/agent-picture\"\n\n/** Agent and person ids, as agentx.json allows them. */\nexport const PICTURE_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/\nconst VERSION = /^[0-9a-f]{16}$/\nconst FILE = /^([a-z0-9][a-z0-9_-]{0,63})\\.([0-9a-f]{16})\\.webp$/\n\nexport class PictureError extends Error {\n constructor(message: string, readonly status = 400) { super(message) }\n}\n\nexport function picturesDir(root: string, kind?: PictureKind): string {\n return kind ? resolve(root, \".agentx\", \"pictures\", kind) : resolve(root, \".agentx\", \"pictures\")\n}\n\n/** The format the first bytes say, or why the file is refused. */\nexport function sniffPicture(bytes: Buffer): \"png\" | \"jpeg\" | \"webp\" {\n if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return \"png\"\n if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return \"jpeg\"\n if (bytes.length >= 12 && bytes.toString(\"latin1\", 0, 4) === \"RIFF\" && bytes.toString(\"latin1\", 8, 12) === \"WEBP\") return \"webp\"\n const head = bytes.toString(\"utf8\", 0, Math.min(bytes.length, 512)).trimStart().toLowerCase()\n if (head.startsWith(\"<svg\") || (head.startsWith(\"<?xml\") && head.includes(\"<svg\")) || head.startsWith(\"<!doctype svg\")) {\n throw new PictureError(\"SVG pictures are not accepted. Use a PNG, JPEG or WebP file.\")\n }\n throw new PictureError(\"That file is not a picture. Use a PNG, JPEG or WebP file.\")\n}\n\nfunction sizeText(n: number): string {\n return n >= 1024 * 1024 ? `${(n / (1024 * 1024)).toFixed(1)} MB` : `${Math.ceil(n / 1024)} KB`\n}\n\ntype Sharp = typeof import(\"sharp\")\nlet sharpLoad: Promise<Sharp> | null = null\n/** sharp is an optional dependency: a machine without it can still run\n * everything else, and says so when a picture is set. */\nfunction loadSharp(): Promise<Sharp> {\n sharpLoad ??= import(\"sharp\").then((m) => ((m as any).default ?? m) as Sharp).catch((e) => {\n sharpLoad = null\n throw new PictureError(`Pictures need the \"sharp\" package, which is not installed here (${e?.message ?? e}). Reinstall AgentX, or run: npm install -g sharp`, 503)\n })\n return sharpLoad\n}\n\n/**\n * Check a picture and re-encode it: a square WebP with no metadata, cut\n * from the middle of the original. Throws PictureError with words for the\n * person who sent it.\n */\nexport async function preparePicture(bytes: Buffer): Promise<Buffer> {\n if (!bytes.length) throw new PictureError(\"The file is empty. Use a PNG, JPEG or WebP picture.\")\n if (bytes.length > PICTURE_MAX_BYTES) {\n throw new PictureError(`The picture is ${sizeText(bytes.length)}; the limit is 1 MB. Make it smaller and try again.`, 413)\n }\n sniffPicture(bytes)\n const sharp = await loadSharp()\n try {\n return await sharp(bytes, { failOn: \"error\", limitInputPixels: 50_000_000 })\n .rotate() // turn it the way the camera said, before that note is dropped\n .resize(PICTURE_SIDE, PICTURE_SIDE, { fit: \"cover\", position: \"centre\" })\n .webp({ quality: 85 })\n .toBuffer()\n } catch (e: any) {\n throw new PictureError(`The picture could not be read (${String(e?.message ?? e).split(\"\\n\")[0]}). Try another file.`)\n }\n}\n\nfunction checkId(kind: PictureKind, id: string): void {\n if (!PICTURE_KINDS.includes(kind)) throw new PictureError(`unknown kind \"${kind}\"`)\n if (!PICTURE_ID.test(id)) throw new PictureError(`\"${id}\" is not a valid ${kind} id`)\n}\n\nfunction filesOf(root: string, kind: PictureKind): { id: string; version: string; name: string }[] {\n let names: string[]\n try { names = readdirSync(picturesDir(root, kind)) } catch { return [] }\n return names.flatMap((name) => {\n const m = name.match(FILE)\n return m ? [{ id: m[1], version: m[2], name }] : []\n })\n}\n\n/** Every picture of one kind: id -> version. */\nexport function listPictures(root: string, kind: PictureKind): Record<string, string> {\n const out: Record<string, string> = {}\n for (const f of filesOf(root, kind)) out[f.id] = f.version\n return out\n}\n\nexport function pictureVersion(root: string, kind: PictureKind, id: string): string | null {\n return filesOf(root, kind).find((f) => f.id === id)?.version ?? null\n}\n\n/** Where a page loads the picture from. */\nexport function pictureUrl(kind: PictureKind, id: string, version: string): string {\n return `/api/pictures/${kind}/${encodeURIComponent(id)}?v=${version}`\n}\n\n/** The picture's bytes, when `version` is the current one. */\nexport function readPicture(root: string, kind: PictureKind, id: string, version: string): Buffer | null {\n if (!PICTURE_KINDS.includes(kind) || !PICTURE_ID.test(id) || !VERSION.test(version)) return null\n const path = resolve(picturesDir(root, kind), `${id}.${version}.webp`)\n try { return readFileSync(path) } catch { return null }\n}\n\n/** Re-encode `bytes` and make it the picture of `id`, replacing any older one. */\nexport async function setPicture(root: string, kind: PictureKind, id: string, bytes: Buffer): Promise<{ version: string; url: string }> {\n checkId(kind, id)\n const out = await preparePicture(bytes)\n const version = createHash(\"sha256\").update(out).digest(\"hex\").slice(0, 16)\n const dir = picturesDir(root, kind)\n mkdirSync(dir, { recursive: true })\n const name = `${id}.${version}.webp`\n const tmp = resolve(dir, `.${name}.${process.pid}.tmp`)\n writeFileSync(tmp, out)\n renameSync(tmp, resolve(dir, name))\n for (const f of filesOf(root, kind)) if (f.id === id && f.name !== name) rmSync(resolve(dir, f.name), { force: true })\n return { version, url: pictureUrl(kind, id, version) }\n}\n\n/** Remove the picture of `id`: the initials show again. False when it had none. */\nexport function removePicture(root: string, kind: PictureKind, id: string): boolean {\n checkId(kind, id)\n const dir = picturesDir(root, kind)\n const mine = filesOf(root, kind).filter((f) => f.id === id)\n for (const f of mine) rmSync(resolve(dir, f.name), { force: true })\n return mine.length > 0\n}\n\n/** Read a request body, refusing one over `max` bytes without keeping it. */\nexport function readPictureBody(req: IncomingMessage, max = PICTURE_MAX_BYTES): Promise<Buffer> {\n return new Promise((done, fail) => {\n const chunks: Buffer[] = []\n let size = 0\n let over = false\n req.on(\"data\", (c: Buffer) => {\n size += c.length\n if (size > max) { over = true; chunks.length = 0 } else if (!over) chunks.push(c)\n })\n req.on(\"end\", () => over\n ? fail(new PictureError(`The picture is ${sizeText(size)}; the limit is 1 MB. Make it smaller and try again.`, 413))\n : done(Buffer.concat(chunks)))\n req.on(\"error\", fail)\n })\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,UAAAC,EAAQ,iBAAAC,MAAqB,KACxF,OAAS,WAAAC,MAAe,OAsBjB,IAAMC,EAAwC,CAAC,QAAS,QAAQ,EAG1DC,EAAoB,KAAO,KAE3BC,EAAe,IACfC,EAAe,aAEfC,EAAqB,qBAGrBC,EAAa,6BACpBC,EAAU,iBACVC,EAAO,qDAEAC,EAAN,cAA2B,KAAM,CACtC,YAAYC,EAA0BC,EAAS,IAAK,CAAE,MAAMD,CAAO,EAA7B,YAAAC,CAA+B,CACvE,EAEO,SAASC,EAAYC,EAAcC,EAA4B,CACpE,OAAOA,EAAOd,EAAQa,EAAM,UAAW,WAAYC,CAAI,EAAId,EAAQa,EAAM,UAAW,UAAU,CAChG,CAGO,SAASE,EAAaC,EAAwC,CACnE,GAAIA,EAAM,QAAU,GAAKA,EAAM,SAAS,EAAG,CAAC,EAAE,OAAO,OAAO,KAAK,CAAC,IAAM,GAAM,GAAM,GAAM,GAAM,GAAM,GAAM,EAAI,CAAC,CAAC,EAAG,MAAO,MAC5H,GAAIA,EAAM,QAAU,GAAKA,EAAM,CAAC,IAAM,KAAQA,EAAM,CAAC,IAAM,KAAQA,EAAM,CAAC,IAAM,IAAM,MAAO,OAC7F,GAAIA,EA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,IAAI,QAAQ,CAAC6C,EAAMC,IAAS,CACjC,IAAMC,EAAmB,CAAC,EACtBC,EAAO,EACPC,EAAO,GACXN,EAAI,GAAG,OAASO,GAAc,CAC5BF,GAAQE,EAAE,OACNF,EAAOJ,GAAOK,EAAO,GAAMF,EAAO,OAAS,GAAcE,GAAMF,EAAO,KAAKG,CAAC,CAClF,CAAC,EACDP,EAAI,GAAG,MAAO,IAAMM,EAChBH,EAAK,IAAIvC,EAAa,kBAAkBS,EAASgC,CAAI,uDAAwD,GAAG,CAAC,EACjHH,EAAK,OAAO,OAAOE,CAAM,CAAC,CAAC,EAC/BJ,EAAI,GAAG,QAASG,CAAI,CACtB,CAAC,CACH","names":["createHash","mkdirSync","readdirSync","readFileSync","renameSync","rmSync","writeFileSync","resolve","PICTURE_KINDS","PICTURE_MAX_BYTES","PICTURE_SIDE","PICTURE_TYPE","AGENT_PICTURE_PATH","PICTURE_ID","VERSION","FILE","PictureError","message","status","picturesDir","root","kind","sniffPicture","bytes","head","sizeText","n","sharpLoad","loadSharp","m","e","preparePicture","sharp","checkId","id","filesOf","names","name","listPictures","out","f","pictureVersion","pictureUrl","version","readPicture","path","setPicture","dir","tmp","removePicture","mine","readPictureBody","req","max","done","fail","chunks","size","over","c"]}
@@ -1,6 +1,6 @@
1
- import{d as h}from"./chunk-YSPBVLTZ.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(`
1
+ import{d as h}from"./chunk-OJ53ATNN.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
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
3
  `).filter(o=>o.trim()).length,a=c.split(`
4
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
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-NIPMVM3G.js.map
6
+ //# sourceMappingURL=chunk-7EMPPP3E.js.map
@@ -1,4 +1,4 @@
1
- import{Gb as m,xb as l}from"./chunk-MD2HCGSC.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{Gb as m,xb as l}from"./chunk-BZJF7DJR.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-IFHVAHQM.js.map
4
+ //# sourceMappingURL=chunk-A4PW7EIK.js.map
@@ -0,0 +1,2 @@
1
+ import{createHash as y}from"crypto";import{readFileSync as C,writeFileSync as S,existsSync as w}from"fs";var b=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","can","shall","to","of","in","for","on","with","at","by","from","as","into","about","through","and","but","or","not","no","if","then","so","what","how","when","where","who","which","that","this","it","i","you","we","they","he","she","me","my","your","our","their","please","just","also","very","much","some","any","all"]),p="4",M=/[؀-ۿ]/;function x(e){e=e.replace(/[ً-ٰٟـ]/g,"").replace(/[٠-٩]/g,t=>String(t.charCodeAt(0)-1632)).replace(/[۰-۹]/g,t=>String(t.charCodeAt(0)-1776));let n=/^[وبفك]?[اٱ]ل/.exec(e);return n&&e.length-n[0].length>=3&&(e=e.slice(n[0].length)),e.replace(/[أإآٱ]/g,"\u0627").replace(/ى/g,"\u064A").replace(/ة/g,"\u0647")}function l(e){return e.normalize("NFKC").toLowerCase().normalize("NFD").replace(/(?<=[a-z])\p{M}+/gu,"").normalize("NFC").split(/[^\p{L}\p{M}\p{N}]+/u).map(n=>M.test(n)?x(n):n).filter(n=>n.length>2&&!b.has(n))}function I(e){let n=new Map,t=new Map,o=[],r=0;for(let s=0;s<e.length;s++){let i=l(e[s]);o.push(i.length),r+=i.length;let u=new Map,a=new Set;for(let c of i)u.set(c,(u.get(c)??0)+1),a.has(c)||(n.set(c,(n.get(c)??0)+1),a.add(c));t.set(s,u)}return{docCount:e.length,avgDocLen:e.length>0?r/e.length:0,df:n,tf:t,docLens:o}}function L(e,n,t,o){let r=o?.k1??1.2,s=o?.b??.75,i=l(e),u=t.tf.get(n);if(!u)return 0;let a=t.docLens[n],c=0;for(let g of i){let d=t.df.get(g)??0;if(d===0)continue;let f=u.get(g)??0;if(f===0)continue;let h=Math.log((t.docCount-d+.5)/(d+.5)+1),m=f*(r+1)/(f+r*(1-s+s*(a/t.avgDocLen)));c+=h*m}return c}function v(e,n,t){let o=[];for(let r=0;r<n.docCount;r++){let s=L(e,r,n,t);s>0&&o.push({docIndex:r,score:s})}return o.sort((r,s)=>s.score-r.score)}function z(e){let n=y("sha256");n.update(`tokenizer:${p}\0`);for(let t of e)n.update(t);return n.digest("hex").slice(0,16)}function D(e,n){let t={};for(let[r,s]of e.df)t[r]=s;let o={};for(let[r,s]of e.tf){let i={};for(let[u,a]of s)i[u]=a;o[String(r)]=i}return{hash:n,docCount:e.docCount,avgDocLen:e.avgDocLen,df:t,tf:o,docLens:e.docLens}}function O(e){let n=new Map(Object.entries(e.df).map(([o,r])=>[o,r])),t=new Map;for(let[o,r]of Object.entries(e.tf))t.set(Number(o),new Map(Object.entries(r)));return{docCount:e.docCount,avgDocLen:e.avgDocLen,df:n,tf:t,docLens:e.docLens}}function N(e,n){let t=z(e);if(w(n))try{let r=JSON.parse(C(n,"utf-8"));if(r.hash===t&&r.docCount===e.length)return O(r)}catch{}let o=I(e);try{S(n,JSON.stringify(D(o,t)))}catch{}return o}export{l as a,I as b,v as c,N as d};
2
+ //# sourceMappingURL=chunk-AHWWJ7AF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory/bm25.ts"],"sourcesContent":["// --- BM25 scoring engine — zero dependencies ---\n// Drop-in replacement for word-overlap relevance scoring.\n// Standard Okapi BM25 with k1=1.2, b=0.75.\n\nexport interface BM25Index {\n docCount: number\n avgDocLen: number\n /** term → number of documents containing it */\n df: Map<string, number>\n /** docIndex → Map<term, frequency> */\n tf: Map<number, Map<string, number>>\n /** per-document token count */\n docLens: number[]\n}\n\nexport interface BM25Options {\n k1?: number // term frequency saturation, default 1.2\n b?: number // length normalization, default 0.75\n}\n\nexport const STOP_WORDS = new Set([\n \"the\", \"a\", \"an\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\n \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\", \"would\", \"could\",\n \"should\", \"may\", \"might\", \"can\", \"shall\", \"to\", \"of\", \"in\", \"for\",\n \"on\", \"with\", \"at\", \"by\", \"from\", \"as\", \"into\", \"about\", \"through\",\n \"and\", \"but\", \"or\", \"not\", \"no\", \"if\", \"then\", \"so\", \"what\", \"how\",\n \"when\", \"where\", \"who\", \"which\", \"that\", \"this\", \"it\", \"i\", \"you\",\n \"we\", \"they\", \"he\", \"she\", \"me\", \"my\", \"your\", \"our\", \"their\",\n \"please\", \"just\", \"also\", \"very\", \"much\", \"some\", \"any\", \"all\",\n])\n\n/** Bump when tokenize() output changes, so cached indexes on disk are rebuilt. */\nconst TOKENIZER_VERSION = \"4\"\n\nconst ARABIC = /[؀-ۿ]/\n\n/**\n * Arabic word normalisation (#1390): drop tashkeel, superscript alef and tatweel,\n * turn Arabic-Indic digits into 0-9, strip the article ال (with a و/ب/ف/ك glued\n * before it) when 3+ letters remain, then unify alef forms, ى → ي and ة → ه.\n * A bare و/ب is never stripped: it is often part of the word (بيانات, وزارة).\n * The article goes before alef unification so the إل in إلكتروني, إلغاء or\n * إلهام is not taken for ال.\n */\nfunction normalizeArabic(w: string): string {\n w = w\n .replace(/[ً-ٰٟـ]/g, \"\")\n .replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x0660))\n .replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x06F0))\n const article = /^[وبفك]?[اٱ]ل/.exec(w)\n if (article && w.length - article[0].length >= 3) w = w.slice(article[0].length)\n return w\n .replace(/[أإآٱ]/g, \"ا\")\n .replace(/ى/g, \"ي\")\n .replace(/ة/g, \"ه\")\n}\n\n/**\n * Tokenize text: NFKC, lowercase, fold Latin accents, split on anything that is\n * not a letter, mark or digit in any script (marks stay so Arabic vowel signs do\n * not cut a word), normalise Arabic words, drop stop words and short tokens.\n */\nexport function tokenize(text: string): string[] {\n return text\n .normalize(\"NFKC\")\n .toLowerCase()\n .normalize(\"NFD\").replace(/(?<=[a-z])\\p{M}+/gu, \"\").normalize(\"NFC\")\n .split(/[^\\p{L}\\p{M}\\p{N}]+/u)\n .map((w) => (ARABIC.test(w) ? normalizeArabic(w) : w))\n .filter((w) => w.length > 2 && !STOP_WORDS.has(w))\n}\n\n/**\n * Build a BM25 inverted index over a corpus of documents.\n */\nexport function buildIndex(docs: string[]): BM25Index {\n const df = new Map<string, number>()\n const tf = new Map<number, Map<string, number>>()\n const docLens: number[] = []\n let totalLen = 0\n\n for (let i = 0; i < docs.length; i++) {\n const tokens = tokenize(docs[i])\n docLens.push(tokens.length)\n totalLen += tokens.length\n\n const termFreq = new Map<string, number>()\n const seen = new Set<string>()\n\n for (const token of tokens) {\n termFreq.set(token, (termFreq.get(token) ?? 0) + 1)\n if (!seen.has(token)) {\n df.set(token, (df.get(token) ?? 0) + 1)\n seen.add(token)\n }\n }\n\n tf.set(i, termFreq)\n }\n\n return {\n docCount: docs.length,\n avgDocLen: docs.length > 0 ? totalLen / docs.length : 0,\n df,\n tf,\n docLens,\n }\n}\n\n/**\n * Score a single document against a query using BM25.\n */\nexport function score(\n query: string,\n docIndex: number,\n index: BM25Index,\n opts?: BM25Options,\n): number {\n const k1 = opts?.k1 ?? 1.2\n const b = opts?.b ?? 0.75\n const queryTokens = tokenize(query)\n const docTf = index.tf.get(docIndex)\n if (!docTf) return 0\n\n const docLen = index.docLens[docIndex]\n let total = 0\n\n for (const term of queryTokens) {\n const termDf = index.df.get(term) ?? 0\n if (termDf === 0) continue\n\n const termTf = docTf.get(term) ?? 0\n if (termTf === 0) continue\n\n // IDF with +1 inside ln() to prevent negative values\n const idf = Math.log(\n (index.docCount - termDf + 0.5) / (termDf + 0.5) + 1,\n )\n\n // BM25 term score\n const tfNorm =\n (termTf * (k1 + 1)) /\n (termTf + k1 * (1 - b + b * (docLen / index.avgDocLen)))\n\n total += idf * tfNorm\n }\n\n return total\n}\n\n/**\n * Score all documents against a query. Returns sorted descending, zero-score docs excluded.\n */\nexport function scoreAll(\n query: string,\n index: BM25Index,\n opts?: BM25Options,\n): Array<{ docIndex: number; score: number }> {\n const results: Array<{ docIndex: number; score: number }> = []\n\n for (let i = 0; i < index.docCount; i++) {\n const s = score(query, i, index, opts)\n if (s > 0) {\n results.push({ docIndex: i, score: s })\n }\n }\n\n return results.sort((a, b) => b.score - a.score)\n}\n\n// --- Cached BM25 Index ---\n// Persists the index to _index.json alongside a content hash.\n// Rebuilds only when documents change.\n\nimport { createHash } from \"crypto\"\nimport { readFileSync, writeFileSync, existsSync } from \"fs\"\n\ninterface SerializedIndex {\n hash: string\n docCount: number\n avgDocLen: number\n df: Record<string, number>\n tf: Record<string, Record<string, number>>\n docLens: number[]\n}\n\nfunction hashDocs(docs: string[]): string {\n const h = createHash(\"sha256\")\n h.update(`tokenizer:${TOKENIZER_VERSION}\\0`)\n for (const d of docs) h.update(d)\n return h.digest(\"hex\").slice(0, 16)\n}\n\nfunction serializeIndex(index: BM25Index, hash: string): SerializedIndex {\n const df: Record<string, number> = {}\n for (const [k, v] of index.df) df[k] = v\n\n const tf: Record<string, Record<string, number>> = {}\n for (const [docIdx, termMap] of index.tf) {\n const terms: Record<string, number> = {}\n for (const [t, f] of termMap) terms[t] = f\n tf[String(docIdx)] = terms\n }\n\n return { hash, docCount: index.docCount, avgDocLen: index.avgDocLen, df, tf, docLens: index.docLens }\n}\n\nfunction deserializeIndex(data: SerializedIndex): BM25Index {\n const df = new Map(Object.entries(data.df).map(([k, v]) => [k, v]))\n const tf = new Map<number, Map<string, number>>()\n for (const [docIdx, terms] of Object.entries(data.tf)) {\n tf.set(Number(docIdx), new Map(Object.entries(terms)))\n }\n\n return { docCount: data.docCount, avgDocLen: data.avgDocLen, df, tf, docLens: data.docLens }\n}\n\n/**\n * Build a BM25 index with disk caching.\n * Stores the index in `cachePath` and only rebuilds when the content hash changes.\n */\nexport function buildIndexCached(docs: string[], cachePath: string): BM25Index {\n const hash = hashDocs(docs)\n\n // Try loading cached index\n if (existsSync(cachePath)) {\n try {\n const cached: SerializedIndex = JSON.parse(readFileSync(cachePath, \"utf-8\"))\n if (cached.hash === hash && cached.docCount === docs.length) {\n return deserializeIndex(cached)\n }\n } catch {\n // Corrupted cache — rebuild\n }\n }\n\n // Build fresh index\n const index = buildIndex(docs)\n\n // Save to disk (best-effort)\n try {\n writeFileSync(cachePath, JSON.stringify(serializeIndex(index, hash)))\n } catch {\n // Can't write cache — still return the index\n }\n\n return index\n}\n"],"mappings":"AA8KA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,gBAAAC,EAAc,iBAAAC,EAAe,cAAAC,MAAkB,KA3JjD,IAAMC,EAAa,IAAI,IAAI,CAChC,MAAO,IAAK,KAAM,KAAM,MAAO,MAAO,OAAQ,KAAM,OAAQ,QAC5D,OAAQ,MAAO,MAAO,KAAM,OAAQ,MAAO,OAAQ,QAAS,QAC5D,SAAU,MAAO,QAAS,MAAO,QAAS,KAAM,KAAM,KAAM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AAG,IAAI,IAAI,OAAO,QAAQE,CAAK,CAAC,CAAC,EAGvD,MAAO,CAAE,SAAUI,EAAK,SAAU,UAAWA,EAAK,UAAW,GAAAxC,EAAI,GAAAC,EAAI,QAASuC,EAAK,OAAQ,CAC7F,CAMO,SAASC,EAAiB1C,EAAgB2C,EAA8B,CAC7E,IAAMX,EAAOH,EAAS7B,CAAI,EAG1B,GAAIX,EAAWsD,CAAS,EACtB,GAAI,CACF,IAAMC,EAA0B,KAAK,MAAMzD,EAAawD,EAAW,OAAO,CAAC,EAC3E,GAAIC,EAAO,OAASZ,GAAQY,EAAO,WAAa5C,EAAK,OACnD,OAAOwC,EAAiBI,CAAM,CAElC,MAAE,CAEF,CAIF,IAAM/B,EAAQd,EAAWC,CAAI,EAG7B,GAAI,CACFZ,EAAcuD,EAAW,KAAK,UAAUZ,EAAelB,EAAOmB,CAAI,CAAC,CAAC,CACtE,MAAE,CAEF,CAEA,OAAOnB,CACT","names":["createHash","readFileSync","writeFileSync","existsSync","STOP_WORDS","TOKENIZER_VERSION","ARABIC","normalizeArabic","w","d","article","tokenize","text","buildIndex","docs","df","tf","docLens","totalLen","i","tokens","termFreq","seen","token","score","query","docIndex","index","opts","k1","b","queryTokens","docTf","docLen","total","term","termDf","termTf","idf","tfNorm","scoreAll","results","a","hashDocs","h","serializeIndex","hash","k","v","docIdx","termMap","terms","t","f","deserializeIndex","data","buildIndexCached","cachePath","cached"]}
@@ -1,4 +1,4 @@
1
- import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-QB6UPODO.js";import{y as C,z as K}from"./chunk-YX4R2VGD.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
1
+ import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-56F5UTTA.js";import{y as C,z as K}from"./chunk-LR4QUAJT.js";import{c as _,d as x}from"./chunk-AHWWJ7AF.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
4
4
  `));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
105
- //# sourceMappingURL=chunk-7WGJZLVJ.js.map
105
+ //# sourceMappingURL=chunk-BITVUKT7.js.map