agentix-cli 0.139.1 → 0.140.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 (147) hide show
  1. package/README.md +15 -2
  2. package/dist/{App-VINKWTYN.js → App-RJRJLBCF.js} +2 -2
  3. package/dist/{ChatApp-RGHQCRBX.js → ChatApp-YTGLBN47.js} +2 -2
  4. package/dist/{absorb-eval-AERHBOQA.js → absorb-eval-DZ6SCGT7.js} +2 -2
  5. package/dist/{agent-PRHZGF6J.js → agent-G32GSRUE.js} +2 -2
  6. package/dist/{board-dashboard-GBEBQUFJ.js → board-dashboard-HOZVSYMJ.js} +4 -4
  7. package/dist/{builtin-YD7MC572.js → builtin-U5S2XCNJ.js} +2 -2
  8. package/dist/{chunk-KO6BU3B3.js → chunk-2JQSWX7U.js} +3 -3
  9. package/dist/chunk-2JQSWX7U.js.map +1 -0
  10. package/dist/{chunk-JJZVFDG6.js → chunk-2NTRAVHC.js} +2 -2
  11. package/dist/{chunk-STIZFWDJ.js → chunk-4ZKXEUQP.js} +2 -2
  12. package/dist/chunk-6TTGRTDO.js +3 -0
  13. package/dist/chunk-6TTGRTDO.js.map +1 -0
  14. package/dist/{chunk-O6WW7ATO.js → chunk-BGKIKZMZ.js} +2 -2
  15. package/dist/{chunk-B65EC44C.js → chunk-C5ABUPRU.js} +2 -2
  16. package/dist/{chunk-QN2OTBVC.js → chunk-E47LEY5I.js} +2 -2
  17. package/dist/{chunk-IMUTN7PT.js → chunk-EBYG3NS3.js} +2 -2
  18. package/dist/{chunk-NQGLKWDO.js → chunk-EVQQZNZY.js} +2 -2
  19. package/dist/{chunk-J7U3BASX.js → chunk-FUGDD6UW.js} +2 -2
  20. package/dist/{chunk-ANDEMOYE.js → chunk-GG6K5ZL6.js} +2 -2
  21. package/dist/{chunk-JS2LEURJ.js → chunk-GPDVETDE.js} +2 -2
  22. package/dist/{chunk-RIYQNADV.js → chunk-GQOMV52Y.js} +57 -57
  23. package/dist/chunk-GQOMV52Y.js.map +1 -0
  24. package/dist/{chunk-FUJ4KEWS.js → chunk-HYVRS3G3.js} +301 -270
  25. package/dist/chunk-HYVRS3G3.js.map +1 -0
  26. package/dist/{chunk-XQVL2RYG.js → chunk-IOT5REOO.js} +2 -2
  27. package/dist/{chunk-2BEZU5OF.js → chunk-O6KRXVN7.js} +3 -3
  28. package/dist/chunk-O6KRXVN7.js.map +1 -0
  29. package/dist/{chunk-MUC7MMTT.js → chunk-OCTWRSOI.js} +2 -2
  30. package/dist/{chunk-EJIY45FZ.js → chunk-P5G6EYBL.js} +2 -2
  31. package/dist/{chunk-LMZCB7TT.js → chunk-PILE2SH3.js} +2 -2
  32. package/dist/{chunk-HXLB2XCT.js → chunk-PPT2MXQY.js} +3 -3
  33. package/dist/{chunk-NMYPZR4W.js → chunk-QHXKELKQ.js} +2 -2
  34. package/dist/{chunk-Z5IHT6RK.js → chunk-QSQWVQLD.js} +2 -2
  35. package/dist/chunk-TF5356HW.js +54 -0
  36. package/dist/{chunk-MGM33GOW.js.map → chunk-TF5356HW.js.map} +1 -1
  37. package/dist/{chunk-AXHP6TMT.js → chunk-U72JN4YF.js} +2 -2
  38. package/dist/{chunk-HF5EF335.js → chunk-VE3SSOQX.js} +4 -4
  39. package/dist/chunk-VE3SSOQX.js.map +1 -0
  40. package/dist/{chunk-H4NSB54D.js → chunk-XVTD6I34.js} +2 -2
  41. package/dist/{chunk-JBYLG3CQ.js → chunk-YVRQ7KWB.js} +2 -2
  42. package/dist/{chunk-U6EJ53DA.js → chunk-YWEGKAE2.js} +2 -2
  43. package/dist/{chunk-7KAQHNLT.js → chunk-Z46SZWMO.js} +2 -2
  44. package/dist/{chunk-HGU5B7IY.js → chunk-ZKNSNSV2.js} +2 -2
  45. package/dist/cli.js +1 -1
  46. package/dist/{client-2KZWK6YT.js → client-B275LQZY.js} +2 -2
  47. package/dist/config-PYDMLFAM.js +2 -0
  48. package/dist/{config-mutate-HXWAXWHC.js → config-mutate-BYRF4RJT.js} +2 -2
  49. package/dist/config-mutator-LZSY6S4H.js +2 -0
  50. package/dist/{contributions-OSIKL25B.js → contributions-SQVBSENQ.js} +2 -2
  51. package/dist/{doctor-TOSA3RWP.js → doctor-L6XMYZPY.js} +2 -2
  52. package/dist/{enrich-R2LIDLPZ.js → enrich-FPK3OW77.js} +2 -2
  53. package/dist/{event-levels-WOYYEWSZ.js → event-levels-NBOMTB23.js} +2 -2
  54. package/dist/{follow-up-tool-M2KCLRQQ.js → follow-up-tool-C72BXO4B.js} +2 -2
  55. package/dist/{hub-XGWCWKMT.js → hub-5OSJMIOO.js} +2 -2
  56. package/dist/index.d.ts +138 -1
  57. package/dist/index.js +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/{program-X6EKIO24.js → program-QJKOF3OJ.js} +24 -24
  60. package/dist/program-QJKOF3OJ.js.map +1 -0
  61. package/dist/{promote-YVWRKIAU.js → promote-C65WVH5K.js} +2 -2
  62. package/dist/{query-X4AFOKZ7.js → query-3LO5OP6O.js} +2 -2
  63. package/dist/{query-settings-HV2RFQK7.js → query-settings-TWT6XZNV.js} +2 -2
  64. package/dist/{registry-B276QJ75.js → registry-YI7NLDAL.js} +2 -2
  65. package/dist/{request-planner-MY6VKTVC.js → request-planner-D6XVDOJN.js} +2 -2
  66. package/dist/{review-candidates-BRTBB5XV.js → review-candidates-6BQ25RIY.js} +2 -2
  67. package/dist/{routing-CSVLOGNS.js → routing-KBNYAPTC.js} +2 -2
  68. package/dist/{rules-UVUJTVOE.js → rules-5ZZQZLQA.js} +2 -2
  69. package/dist/schedule-tool-GDUREPVN.js +2 -0
  70. package/dist/{scheduler-OUAVAU4O.js → scheduler-R6N7FT27.js} +2 -2
  71. package/dist/{seat-H2QR3CRX.js → seat-5AF4CN52.js} +2 -2
  72. package/dist/{select-EEL5AZ2I.js → select-TJZXA74W.js} +2 -2
  73. package/dist/send-answer-ZG7UHCVS.js +2 -0
  74. package/dist/{set-enabled-IBGEH6U6.js → set-enabled-RQPZBVZP.js} +2 -2
  75. package/dist/{tool-GJ75MWV5.js → tool-2RJYOQE7.js} +2 -2
  76. package/dist/{tool-DFPOFXGA.js → tool-C7Z56DOT.js} +2 -2
  77. package/dist/{wiki-ISKHNG3P.js → wiki-3DX53GJ4.js} +2 -2
  78. package/dist/wiki-enrich-KQNC45FM.js +2 -0
  79. package/dist/wiki-enrich-KQNC45FM.js.map +1 -0
  80. package/package.json +3 -2
  81. package/dist/chunk-2BEZU5OF.js.map +0 -1
  82. package/dist/chunk-FUJ4KEWS.js.map +0 -1
  83. package/dist/chunk-HF5EF335.js.map +0 -1
  84. package/dist/chunk-KO6BU3B3.js.map +0 -1
  85. package/dist/chunk-MGM33GOW.js +0 -54
  86. package/dist/chunk-RIYQNADV.js.map +0 -1
  87. package/dist/config-THFRJMZD.js +0 -2
  88. package/dist/config-mutator-JZOAWRBH.js +0 -2
  89. package/dist/program-X6EKIO24.js.map +0 -1
  90. package/dist/schedule-tool-GUKYTQTY.js +0 -2
  91. package/dist/wiki-enrich-7SBCPK2E.js +0 -2
  92. /package/dist/{App-VINKWTYN.js.map → App-RJRJLBCF.js.map} +0 -0
  93. /package/dist/{ChatApp-RGHQCRBX.js.map → ChatApp-YTGLBN47.js.map} +0 -0
  94. /package/dist/{absorb-eval-AERHBOQA.js.map → absorb-eval-DZ6SCGT7.js.map} +0 -0
  95. /package/dist/{agent-PRHZGF6J.js.map → agent-G32GSRUE.js.map} +0 -0
  96. /package/dist/{board-dashboard-GBEBQUFJ.js.map → board-dashboard-HOZVSYMJ.js.map} +0 -0
  97. /package/dist/{builtin-YD7MC572.js.map → builtin-U5S2XCNJ.js.map} +0 -0
  98. /package/dist/{chunk-JJZVFDG6.js.map → chunk-2NTRAVHC.js.map} +0 -0
  99. /package/dist/{chunk-STIZFWDJ.js.map → chunk-4ZKXEUQP.js.map} +0 -0
  100. /package/dist/{chunk-O6WW7ATO.js.map → chunk-BGKIKZMZ.js.map} +0 -0
  101. /package/dist/{chunk-B65EC44C.js.map → chunk-C5ABUPRU.js.map} +0 -0
  102. /package/dist/{chunk-QN2OTBVC.js.map → chunk-E47LEY5I.js.map} +0 -0
  103. /package/dist/{chunk-IMUTN7PT.js.map → chunk-EBYG3NS3.js.map} +0 -0
  104. /package/dist/{chunk-NQGLKWDO.js.map → chunk-EVQQZNZY.js.map} +0 -0
  105. /package/dist/{chunk-J7U3BASX.js.map → chunk-FUGDD6UW.js.map} +0 -0
  106. /package/dist/{chunk-ANDEMOYE.js.map → chunk-GG6K5ZL6.js.map} +0 -0
  107. /package/dist/{chunk-JS2LEURJ.js.map → chunk-GPDVETDE.js.map} +0 -0
  108. /package/dist/{chunk-XQVL2RYG.js.map → chunk-IOT5REOO.js.map} +0 -0
  109. /package/dist/{chunk-MUC7MMTT.js.map → chunk-OCTWRSOI.js.map} +0 -0
  110. /package/dist/{chunk-EJIY45FZ.js.map → chunk-P5G6EYBL.js.map} +0 -0
  111. /package/dist/{chunk-LMZCB7TT.js.map → chunk-PILE2SH3.js.map} +0 -0
  112. /package/dist/{chunk-HXLB2XCT.js.map → chunk-PPT2MXQY.js.map} +0 -0
  113. /package/dist/{chunk-NMYPZR4W.js.map → chunk-QHXKELKQ.js.map} +0 -0
  114. /package/dist/{chunk-Z5IHT6RK.js.map → chunk-QSQWVQLD.js.map} +0 -0
  115. /package/dist/{chunk-AXHP6TMT.js.map → chunk-U72JN4YF.js.map} +0 -0
  116. /package/dist/{chunk-H4NSB54D.js.map → chunk-XVTD6I34.js.map} +0 -0
  117. /package/dist/{chunk-JBYLG3CQ.js.map → chunk-YVRQ7KWB.js.map} +0 -0
  118. /package/dist/{chunk-U6EJ53DA.js.map → chunk-YWEGKAE2.js.map} +0 -0
  119. /package/dist/{chunk-7KAQHNLT.js.map → chunk-Z46SZWMO.js.map} +0 -0
  120. /package/dist/{chunk-HGU5B7IY.js.map → chunk-ZKNSNSV2.js.map} +0 -0
  121. /package/dist/{client-2KZWK6YT.js.map → client-B275LQZY.js.map} +0 -0
  122. /package/dist/{config-THFRJMZD.js.map → config-PYDMLFAM.js.map} +0 -0
  123. /package/dist/{config-mutate-HXWAXWHC.js.map → config-mutate-BYRF4RJT.js.map} +0 -0
  124. /package/dist/{config-mutator-JZOAWRBH.js.map → config-mutator-LZSY6S4H.js.map} +0 -0
  125. /package/dist/{contributions-OSIKL25B.js.map → contributions-SQVBSENQ.js.map} +0 -0
  126. /package/dist/{doctor-TOSA3RWP.js.map → doctor-L6XMYZPY.js.map} +0 -0
  127. /package/dist/{enrich-R2LIDLPZ.js.map → enrich-FPK3OW77.js.map} +0 -0
  128. /package/dist/{event-levels-WOYYEWSZ.js.map → event-levels-NBOMTB23.js.map} +0 -0
  129. /package/dist/{follow-up-tool-M2KCLRQQ.js.map → follow-up-tool-C72BXO4B.js.map} +0 -0
  130. /package/dist/{hub-XGWCWKMT.js.map → hub-5OSJMIOO.js.map} +0 -0
  131. /package/dist/{promote-YVWRKIAU.js.map → promote-C65WVH5K.js.map} +0 -0
  132. /package/dist/{query-X4AFOKZ7.js.map → query-3LO5OP6O.js.map} +0 -0
  133. /package/dist/{query-settings-HV2RFQK7.js.map → query-settings-TWT6XZNV.js.map} +0 -0
  134. /package/dist/{registry-B276QJ75.js.map → registry-YI7NLDAL.js.map} +0 -0
  135. /package/dist/{request-planner-MY6VKTVC.js.map → request-planner-D6XVDOJN.js.map} +0 -0
  136. /package/dist/{review-candidates-BRTBB5XV.js.map → review-candidates-6BQ25RIY.js.map} +0 -0
  137. /package/dist/{routing-CSVLOGNS.js.map → routing-KBNYAPTC.js.map} +0 -0
  138. /package/dist/{rules-UVUJTVOE.js.map → rules-5ZZQZLQA.js.map} +0 -0
  139. /package/dist/{schedule-tool-GUKYTQTY.js.map → schedule-tool-GDUREPVN.js.map} +0 -0
  140. /package/dist/{scheduler-OUAVAU4O.js.map → scheduler-R6N7FT27.js.map} +0 -0
  141. /package/dist/{seat-H2QR3CRX.js.map → seat-5AF4CN52.js.map} +0 -0
  142. /package/dist/{select-EEL5AZ2I.js.map → select-TJZXA74W.js.map} +0 -0
  143. /package/dist/{wiki-ISKHNG3P.js.map → send-answer-ZG7UHCVS.js.map} +0 -0
  144. /package/dist/{set-enabled-IBGEH6U6.js.map → set-enabled-RQPZBVZP.js.map} +0 -0
  145. /package/dist/{tool-GJ75MWV5.js.map → tool-2RJYOQE7.js.map} +0 -0
  146. /package/dist/{tool-DFPOFXGA.js.map → tool-C7Z56DOT.js.map} +0 -0
  147. /package/dist/{wiki-enrich-7SBCPK2E.js.map → wiki-3DX53GJ4.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-LMZCB7TT.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-PILE2SH3.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-7KAQHNLT.js.map
6
+ //# sourceMappingURL=chunk-Z46SZWMO.js.map
@@ -1,8 +1,8 @@
1
- import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-ANDEMOYE.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-NMYPZR4W.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
1
+ import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-GG6K5ZL6.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-QHXKELKQ.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
2
2
  `)}async function b(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
3
3
  `):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
4
4
  `),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
5
5
  `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
6
  `),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
7
  `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
8
- //# sourceMappingURL=chunk-HGU5B7IY.js.map
8
+ //# sourceMappingURL=chunk-ZKNSNSV2.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-X6EKIO24.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
2
+ import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-QJKOF3OJ.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
3
3
  //# sourceMappingURL=cli.js.map
@@ -1,2 +1,2 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-QN2OTBVC.js";import"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
2
- //# sourceMappingURL=client-2KZWK6YT.js.map
1
+ import{a,b,c,d,e,f,g}from"./chunk-E47LEY5I.js";import"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
2
+ //# sourceMappingURL=client-B275LQZY.js.map
@@ -0,0 +1,2 @@
1
+ import{Ba as v,fa as a,ga as b,ha as c,ia as d,ja as e,ka as f,la as g,ma as h,na as i,oa as j,pa as k,qa as l,ra as m,sa as n,ta as o,ua as p,va as q,wa as r,xa as s,ya as t,za as u}from"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";v();export{a as INTEGRATION_KINDS,q as WIKI_CONTRIBUTE_JOB,r as WIKI_CONTRIBUTE_MERGE_JOB,t as WIKI_SUMMARIZE_JOB,l as approvalsConfigSchema,e as callsSchema,c as cameraBotSchema,m as daemonConfigSchema,b as eventSubscriptionSchema,n as expandEnvVars,d as isCronExpression,o as loadDaemonConfig,j as membersConfigSchema,i as peopleConfigSchema,h as personSchema,k as requestStatusConfigSchema,g as requestsConfigSchema,p as validateWorkspaces,f as watchersConfigSchema,s as withContributionJobs,u as withSummariesJob};
2
+ //# sourceMappingURL=config-PYDMLFAM.js.map
@@ -1,2 +1,2 @@
1
- import{a,b}from"./chunk-EJIY45FZ.js";import"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
2
- //# sourceMappingURL=config-mutate-HXWAXWHC.js.map
1
+ import{a,b}from"./chunk-P5G6EYBL.js";import"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
2
+ //# sourceMappingURL=config-mutate-BYRF4RJT.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e}from"./chunk-QHXKELKQ.js";import"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
2
+ //# sourceMappingURL=config-mutator-LZSY6S4H.js.map
@@ -1,4 +1,4 @@
1
- import{a as ee}from"./chunk-O6WW7ATO.js";import"./chunk-B65EC44C.js";import{f as Q,k as V}from"./chunk-QSKG754X.js";import{b as O}from"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-HXLB2XCT.js";import"./chunk-SKSYII3K.js";import"./chunk-7KAQHNLT.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-LMZCB7TT.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
1
+ import{a as ee}from"./chunk-BGKIKZMZ.js";import"./chunk-C5ABUPRU.js";import{f as Q,k as V}from"./chunk-QSKG754X.js";import{b as O}from"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-PPT2MXQY.js";import"./chunk-SKSYII3K.js";import"./chunk-Z46SZWMO.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-PILE2SH3.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
2
2
  `),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
3
3
  ${k.join(`
4
4
  `)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
54
54
  `).replace(/\n{3,}/g,`
55
55
 
56
56
  `).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
57
- //# sourceMappingURL=contributions-OSIKL25B.js.map
57
+ //# sourceMappingURL=contributions-SQVBSENQ.js.map
@@ -1,2 +1,2 @@
1
- import{b as a,c as b,d as c,e as d,f as e}from"./chunk-IMUTN7PT.js";import"./chunk-S2GAEH2F.js";import"./chunk-JXF54PT7.js";import"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
2
- //# sourceMappingURL=doctor-TOSA3RWP.js.map
1
+ import{b as a,c as b,d as c,e as d,f as e}from"./chunk-EBYG3NS3.js";import"./chunk-S2GAEH2F.js";import"./chunk-JXF54PT7.js";import"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
2
+ //# sourceMappingURL=doctor-L6XMYZPY.js.map
@@ -1,2 +1,2 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q}from"./chunk-U6EJ53DA.js";import"./chunk-H4NSB54D.js";import"./chunk-MTX4UPNB.js";import"./chunk-QAWKN2N4.js";import"./chunk-IMLAPB7G.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QIJLFPWE.js";export{a as ENRICH_BY,b as ENRICH_TYPES,h as buildEnrichPrompt,j as checkEnrichment,n as createEntityPage,e as enrichContext,g as fingerprint,c as lensProperties,o as loadEnrichState,f as mentionsOf,l as mergedMeta,i as parseEnrichReply,d as readableAlongside,q as runEnrich,p as saveEnrichState,m as targetPage,k as withOverview};
2
- //# sourceMappingURL=enrich-R2LIDLPZ.js.map
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q}from"./chunk-YWEGKAE2.js";import"./chunk-XVTD6I34.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import"./chunk-IMLAPB7G.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QIJLFPWE.js";export{a as ENRICH_BY,b as ENRICH_TYPES,h as buildEnrichPrompt,j as checkEnrichment,n as createEntityPage,e as enrichContext,g as fingerprint,c as lensProperties,o as loadEnrichState,f as mentionsOf,l as mergedMeta,i as parseEnrichReply,d as readableAlongside,q as runEnrich,p as saveEnrichState,m as targetPage,k as withOverview};
2
+ //# sourceMappingURL=enrich-FPK3OW77.js.map
@@ -1,3 +1,3 @@
1
- import{a as A,k as R}from"./chunk-H4NSB54D.js";import"./chunk-MTX4UPNB.js";import{f as g}from"./chunk-QAWKN2N4.js";import"./chunk-IMLAPB7G.js";import{c as I}from"./chunk-OWNQ2FD4.js";import{a as E}from"./chunk-ROLSSYXE.js";import"./chunk-QIJLFPWE.js";var b="wiki-events",x="importance_set",S=new Set(["event","due_date","topic"]),L=10,j=320;function _(t,e,c){let o=new Set(c.map(r=>r.toLowerCase()));for(let r of t??[])if(!(!E.includes(r.level)||!r.title&&!r.tags?.length)){if(r.title){let i;try{i=new RegExp(r.title,"i")}catch{continue}if(!i.test(e))continue}if(r.unless){let i;try{i=new RegExp(r.unless,"i")}catch{continue}if(i.test(e))continue}if(!(r.tags?.length&&!r.tags.some(i=>o.has(i.toLowerCase()))))return r.level}}function O(t,e){let c=` ${g(e)} `,o=[];for(let r of t.entities.values()){if(S.has(r.type))continue;let i=g(r.title);i.length>=4&&c.includes(` ${i} `)&&o.push(r)}return o}function C(t,e){let c=A(t,e,null).filter(r=>!S.has(r.type)),o=O(t,e.title);return[...new Map([...o,...c].map(r=>[r.id,r])).values()].slice(0,L)}function W(t,e){return e.pages.find(c=>!t.syncedFrom(c.agentId))}function $(t){return(t.statements??[]).some(e=>e.by===b&&e.property===x)}function G(t){return t.pages.some(e=>e.article.meta.importance&&!$(e.article.meta))}function U(t,e,c){let o=new Set;for(let s of c.about){let l=e.names.get(g(s))??(e.entities.has(s)?s:void 0);l&&o.add(l)}let r=[],i=[],a=[...e.entities.values()].filter(s=>s.type==="event").sort((s,l)=>(l.date||"").localeCompare(s.date||""));for(let s of a){if(s.pages.some(n=>n.article.meta.importance)&&(!c.force||G(s)))continue;let f=C(e,s);if(c.about.length&&!f.some(n=>o.has(n.id)))continue;let d=W(t,s);if(!d){i.push(s);continue}r.push({event:s,page:d,candidates:f})}return{items:r,noPage:i}}var M=(t,e)=>t.length>e?`${t.slice(0,e)}\u2026`:t;function V(t,e){let c=["You are sorting the event pages of a company wiki by importance, and saying what each event is about.","","Levels:","- minor: routine upkeep or a small incident with no lasting effect (a disk filled and was cleaned, a job was restarted, a reminder was sent).","- normal: something a person would want in the history of the thing it is about (a delivery, a payment, an outage that was noticed, a meeting with an outcome).","- major: a turning point (a client won or lost, a contract signed, a legal or financial deadline missed, data lost, a decision that changes how things are done).","When unsure between two levels, pick the lower one.","","## Events"];return t.forEach((o,r)=>{let i=M(R(o.page.article.content).replace(/\s+/g," ").trim(),j);c.push(`### ${r+1}. ${o.event.title} (${o.event.date||"no date"})`,i||"(no text)"),c.push(o.candidates.length?`May be about: ${o.candidates.map(a=>`"${a.title}" (${a.type})`).join(", ")}`:"May be about: nothing listed","")}),c.push("## Task","Return one JSON object and nothing else:",'{"events": [{"n": 1, "importance": "minor", "about": ["Exact Title"], "why": "one short reason"}]}',"","Rules:",`- One item per event, with its number. importance is one of ${E.join(", ")}.`,`- about: only titles from that event's own "May be about" list, copied exactly, and only the ones the event really concerns: the machine that failed, the client it was for, the person it happened to. Often one, at most three. Leave it empty when none fits.`,"- why: under 15 words, in English.",...e.importance.major_set_by==="owner"?["- major is only a suggestion here: the owner confirms it."]:[]),c.join(`
1
+ import{a as A,k as R}from"./chunk-XVTD6I34.js";import{f as g}from"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import"./chunk-IMLAPB7G.js";import{c as I}from"./chunk-OWNQ2FD4.js";import{a as E}from"./chunk-ROLSSYXE.js";import"./chunk-QIJLFPWE.js";var b="wiki-events",x="importance_set",S=new Set(["event","due_date","topic"]),L=10,j=320;function _(t,e,c){let o=new Set(c.map(r=>r.toLowerCase()));for(let r of t??[])if(!(!E.includes(r.level)||!r.title&&!r.tags?.length)){if(r.title){let i;try{i=new RegExp(r.title,"i")}catch{continue}if(!i.test(e))continue}if(r.unless){let i;try{i=new RegExp(r.unless,"i")}catch{continue}if(i.test(e))continue}if(!(r.tags?.length&&!r.tags.some(i=>o.has(i.toLowerCase()))))return r.level}}function O(t,e){let c=` ${g(e)} `,o=[];for(let r of t.entities.values()){if(S.has(r.type))continue;let i=g(r.title);i.length>=4&&c.includes(` ${i} `)&&o.push(r)}return o}function C(t,e){let c=A(t,e,null).filter(r=>!S.has(r.type)),o=O(t,e.title);return[...new Map([...o,...c].map(r=>[r.id,r])).values()].slice(0,L)}function W(t,e){return e.pages.find(c=>!t.syncedFrom(c.agentId))}function $(t){return(t.statements??[]).some(e=>e.by===b&&e.property===x)}function G(t){return t.pages.some(e=>e.article.meta.importance&&!$(e.article.meta))}function U(t,e,c){let o=new Set;for(let s of c.about){let l=e.names.get(g(s))??(e.entities.has(s)?s:void 0);l&&o.add(l)}let r=[],i=[],a=[...e.entities.values()].filter(s=>s.type==="event").sort((s,l)=>(l.date||"").localeCompare(s.date||""));for(let s of a){if(s.pages.some(n=>n.article.meta.importance)&&(!c.force||G(s)))continue;let f=C(e,s);if(c.about.length&&!f.some(n=>o.has(n.id)))continue;let d=W(t,s);if(!d){i.push(s);continue}r.push({event:s,page:d,candidates:f})}return{items:r,noPage:i}}var M=(t,e)=>t.length>e?`${t.slice(0,e)}\u2026`:t;function V(t,e){let c=["You are sorting the event pages of a company wiki by importance, and saying what each event is about.","","Levels:","- minor: routine upkeep or a small incident with no lasting effect (a disk filled and was cleaned, a job was restarted, a reminder was sent).","- normal: something a person would want in the history of the thing it is about (a delivery, a payment, an outage that was noticed, a meeting with an outcome).","- major: a turning point (a client won or lost, a contract signed, a legal or financial deadline missed, data lost, a decision that changes how things are done).","When unsure between two levels, pick the lower one.","","## Events"];return t.forEach((o,r)=>{let i=M(R(o.page.article.content).replace(/\s+/g," ").trim(),j);c.push(`### ${r+1}. ${o.event.title} (${o.event.date||"no date"})`,i||"(no text)"),c.push(o.candidates.length?`May be about: ${o.candidates.map(a=>`"${a.title}" (${a.type})`).join(", ")}`:"May be about: nothing listed","")}),c.push("## Task","Return one JSON object and nothing else:",'{"events": [{"n": 1, "importance": "minor", "about": ["Exact Title"], "why": "one short reason"}]}',"","Rules:",`- One item per event, with its number. importance is one of ${E.join(", ")}.`,`- about: only titles from that event's own "May be about" list, copied exactly, and only the ones the event really concerns: the machine that failed, the client it was for, the person it happened to. Often one, at most three. Leave it empty when none fits.`,"- why: under 15 words, in English.",...e.importance.major_set_by==="owner"?["- major is only a suggestion here: the owner confirms it."]:[]),c.join(`
2
2
  `)}function N(t){let e=t.match(/```(?:json)?\s*\n([\s\S]*?)\n```/),c=e?e[1]:t.slice(t.indexOf("{"),t.lastIndexOf("}")+1);try{let o=JSON.parse(c);return o&&typeof o=="object"&&!Array.isArray(o)?o:null}catch{return null}}function P(t,e){return t==="major"&&e.importance.major_set_by==="owner"?{importance:"normal",proposed:"major"}:{importance:t}}function T(t,e,c){let o=new Map,r=N(t);for(let i of Array.isArray(r?.events)?r.events:[]){let a=i??{},s=Number(a.n)-1,l=e[s];if(!Number.isInteger(s)||!l||o.has(s))continue;let f=String(a.importance??"").trim().toLowerCase();if(!E.includes(f))continue;let d=[],n=new Map(l.candidates.map(u=>[g(u.title),u.title])),p=[];for(let u of Array.isArray(a.about)?a.about:[]){let m=n.get(g(String(u??"")));m&&!p.includes(m)?p.push(m):!m&&String(u??"").trim()&&d.push(`about ${String(u).trim().slice(0,80)}: not in the list shown`)}p.length>3&&d.push(`about: kept the first 3 of ${p.length}`);let h=typeof a.why=="string"?M(a.why.trim(),160):void 0;o.set(s,{verdict:{...P(f,c),about:p.slice(0,3),why:h||void 0,by:"model"},dropped:d})}return o}function B(t,e,c){let o=(t.statements??[]).filter(a=>a.by!==b),r=new Set(o.filter(a=>a.property==="involves").map(a=>g(a.value))),i=e.about.filter(a=>!r.has(g(a))).map(a=>({property:"involves",value:a,checked_at:c,by:b}));return i.push({property:x,value:e.proposed??e.importance,checked_at:c,by:b,...e.why?{note:e.why}:{}}),{...t,importance:e.importance,importanceProposed:e.proposed,statements:[...o,...i]}}async function K(t,e,c,o){let r=e.ontology,{items:i,noPage:a}=U(t,e,o),s=i.slice(0,o.max),l={outcomes:[],costUsd:0,calls:0,capped:!1,left:i.length-s.length};for(let n of o.about.length?a:[])l.outcomes.push({event:n.id,title:n.title,date:n.date,status:"no-page",about:[],dropped:["its pages are copied from another node"]});let f=(n,p,h)=>{let u=`${n.page.agentId}/${n.page.article.path}`,m={event:n.event.id,title:n.event.title,date:n.event.date,page:u,status:"dry-run",importance:p.importance,proposed:p.proposed,about:p.about,by:p.by,why:p.why,dropped:h};if(o.dryRun){l.outcomes.push(m);return}let v=t.getAgentWiki(n.page.agentId),k=n.page.article.path,w;try{w=v.withArticleLock(k,()=>{let y=v.readArticle(k);return y?y.meta.importance&&!$(y.meta)?"a level was set on the page during the run":v.writeArticle(k,B(y.meta,p,o.today),y.content,y.meta.owner||n.page.agentId)?void 0:"write refused":"the page was moved or removed during the run"})}catch(y){if(!(y instanceof I))throw y;w="the page was busy; run again"}l.outcomes.push(w?{...m,status:"failed",dropped:[...h,w]}:{...m,status:"written"})},d=[];for(let n of s){let p=_(r.importance.rules,n.event.title,n.page.article.meta.tags??[]);if(!p){d.push(n);continue}let h=new Set(O(e,n.event.title).map(m=>m.id)),u=n.candidates.filter(m=>h.has(m.id)).slice(0,3).map(m=>m.title);f(n,{...P(p,r),about:u,why:"matched an importance rule",by:"rule"},[])}if(o.rulesOnly)return l.left+=d.length,l;for(let n=0;n<d.length;n+=o.batch){let p=d.slice(n,n+o.batch);if(l.costUsd>=o.maxCostUsd){l.capped=!0,l.left+=d.length-n;break}l.calls++;let h;try{let u=await c(V(p,r));l.costUsd+=u.costUsd,h=T(u.text,p,r)}catch(u){for(let m of p)l.outcomes.push({event:m.event.id,title:m.event.title,date:m.event.date,page:`${m.page.agentId}/${m.page.article.path}`,status:"failed",about:[],dropped:[u.message.slice(0,200)]});continue}p.forEach((u,m)=>{let v=h.get(m);v?f(u,v.verdict,v.dropped):l.outcomes.push({event:u.event.id,title:u.event.title,date:u.event.date,page:`${u.page.agentId}/${u.page.article.path}`,status:"no-answer",about:[],dropped:["the reply had no usable item for this event"]})})}if(!o.dryRun)for(let n of new Set(l.outcomes.filter(p=>p.status==="written").map(p=>p.page.split("/")[0])))t.getAgentWiki(n).rebuildIndex();return l}function z(t,e,c,o){let r=e.names.get(g(c))??(e.entities.has(c)?c:void 0),i=r?e.entities.get(r):void 0;if(!i)return{ok:!1,reason:`no page is titled "${c}"`};if(i.type!=="event")return{ok:!1,title:i.title,reason:`"${i.title}" is a ${i.type}, not an event`};let a=W(t,i);if(!a)return{ok:!1,title:i.title,reason:"its pages are copied from another node; set the level there"};let s=t.getAgentWiki(a.agentId),l,f="write refused";try{l=s.withArticleLock(a.article.path,()=>{let d=s.readArticle(a.article.path)??a.article,n=(d.meta.statements??[]).filter(h=>!(h.by===b&&h.property===x)),p={...d.meta,importance:o,importanceProposed:void 0,statements:n.length?n:void 0};return s.writeArticle(a.article.path,p,d.content,d.meta.owner||a.agentId)})}catch(d){if(!(d instanceof I))throw d;l=!1,f="the page was busy; run again"}return l&&s.rebuildIndex(),{ok:l,title:i.title,page:`${a.agentId}/${a.article.path}`,reason:l?void 0:f}}function X(t,e,c){let o=[],r=new Map(e.outcomes.filter(i=>i.importance).map(i=>[i.event,i]));for(let i of c){let a=t.names.get(g(i))??(t.entities.has(i)?i:void 0),s=a?t.entities.get(a):void 0;if(!s)continue;let l=new Set(A(t,s,new Set(["event"])).map(n=>n.id)),f={minor:0,normal:0,major:0},d=new Set;for(let n of t.entities.values()){if(n.type!=="event")continue;let p=r.get(n.id);!(l.has(n.id)||p?.about.some(u=>g(u)===g(s.title)))||d.has(n.id)||(d.add(n.id),f[p?.importance??n.importance]++)}o.push({title:s.title,type:s.type,before:l.size,after:f})}return o}export{b as EVENTS_BY,V as buildEventsPrompt,T as checkEventsReply,C as eventCandidates,B as eventMeta,U as pickEvents,_ as ruleLevel,K as runEvents,z as setEventLevel,X as summariseAbout};
3
- //# sourceMappingURL=event-levels-WOYYEWSZ.js.map
3
+ //# sourceMappingURL=event-levels-NBOMTB23.js.map
@@ -1,7 +1,7 @@
1
- import{b as h}from"./chunk-HGU5B7IY.js";import"./chunk-RKPAVWXF.js";import{b as I}from"./chunk-3W2BHUGM.js";import"./chunk-SHEUCITK.js";import"./chunk-ANDEMOYE.js";import"./chunk-JS2LEURJ.js";import"./chunk-NMYPZR4W.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function $(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(s=>`- ${String(s.at).slice(0,16).replace("T"," ")} ${s.step} ${s.status}${s.note?`: ${s.note}`:""}`)].filter(Boolean).join(`
1
+ import{b as h}from"./chunk-ZKNSNSV2.js";import"./chunk-RKPAVWXF.js";import{b as I}from"./chunk-3W2BHUGM.js";import"./chunk-SHEUCITK.js";import"./chunk-GG6K5ZL6.js";import"./chunk-GPDVETDE.js";import"./chunk-QHXKELKQ.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function $(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(s=>`- ${String(s.at).slice(0,16).replace("T"," ")} ${s.step} ${s.status}${s.note?`: ${s.note}`:""}`)].filter(Boolean).join(`
2
2
  `)}async function T(t,c){let s=c.fetch??fetch,m=c.daemonUrl.replace(/\/$/,""),r=(p(t.action)||"list").toLowerCase(),f=c.env??process.env,w=async i=>{let l=await s(`${m}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(r==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(d=>[`${d.tag}:`,...d.rows.map(a=>`- ${a.runId} "${a.title}" on ${a.step}: waiting on ${a.waitingOn} (since ${String(a.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
3
3
  `)).join(`
4
4
  `):"No follow-up workflows are running."}if(r==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),d=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!d.ok)return`Error: ${d.data?.error||`HTTP ${d.status}`}`;let a=d.data.matches??[];return a.length?["Saved workflows, best fit first (confidence 0-1):",...a.map(u=>`- ${u.workflowId} "${u.title}" (${u.confidence}${u.autoStart?", starts without asking":""}): ${u.steps.map(k=>k.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
5
5
  `):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(r==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?$(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await s(`${m}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...I(f)},body:JSON.stringify({action:r,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun,status:t.status}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(r==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return r==="plan"?[`Plan recorded on run ${n.run?.runId??t.runId}:`,...(n.plan??[]).map(e=>`- ${e.id} ${e.title}`),'Report each step with {action:"step", runId, step:"<id>", status:"started"|"done"|"failed"}.'].join(`
6
6
  `):r==="step"?`Step recorded. ${n.run?$(n.run):""}`.trim():r==="done"?`Step recorded as done. ${n.run?$(n.run):""}`.trim():r==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
7
- //# sourceMappingURL=follow-up-tool-M2KCLRQQ.js.map
7
+ //# sourceMappingURL=follow-up-tool-C72BXO4B.js.map
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-AXHP6TMT.js";import"./chunk-STIZFWDJ.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-7KAQHNLT.js";import"./chunk-WPNRDEHW.js";import"./chunk-LMZCB7TT.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
2
- //# sourceMappingURL=hub-XGWCWKMT.js.map
1
+ import{a}from"./chunk-U72JN4YF.js";import"./chunk-4ZKXEUQP.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-Z46SZWMO.js";import"./chunk-WPNRDEHW.js";import"./chunk-PILE2SH3.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
2
+ //# sourceMappingURL=hub-5OSJMIOO.js.map
package/dist/index.d.ts CHANGED
@@ -5762,6 +5762,94 @@ declare const daemonConfigSchema: z.ZodObject<{
5762
5762
  disabledAgents?: string[] | undefined;
5763
5763
  } | undefined;
5764
5764
  }>>;
5765
+ /** Task watchers (src/watchers, #1030): every task start decides whether
5766
+ * the task needs a watcher and attaches one. Off by default. */
5767
+ watchers: z.ZodEffects<z.ZodDefault<z.ZodObject<{
5768
+ enabled: z.ZodDefault<z.ZodBoolean>;
5769
+ /** Channels whose runs are never checked (the watchers' own alert turns
5770
+ * never are). */
5771
+ skipChannels: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
5772
+ /** The due time of a task that gives none, from its start. */
5773
+ defaultDueMinutes: z.ZodDefault<z.ZodNumber>;
5774
+ /** A seat probability below this is a confident "no". Only an active
5775
+ * seat skips the watcher on it. */
5776
+ noBelow: z.ZodDefault<z.ZodNumber>;
5777
+ /** At or above: "yes". Between `noBelow` and this: "uncertain", which
5778
+ * attaches a watcher (fail-safe). */
5779
+ yesAt: z.ZodDefault<z.ZodNumber>;
5780
+ /** After the delegating agent is told, the owner is told this much later
5781
+ * if the task is still not done. */
5782
+ escalateAfterMinutes: z.ZodDefault<z.ZodNumber>;
5783
+ /** Where the owner is told. Unset: the default notification channel. */
5784
+ owner: z.ZodDefault<z.ZodObject<{
5785
+ channel: z.ZodOptional<z.ZodString>;
5786
+ chatId: z.ZodOptional<z.ZodString>;
5787
+ }, "strip", z.ZodTypeAny, {
5788
+ channel?: string | undefined;
5789
+ chatId?: string | undefined;
5790
+ }, {
5791
+ channel?: string | undefined;
5792
+ chatId?: string | undefined;
5793
+ }>>;
5794
+ /** Finished watchers are deleted after this many days. */
5795
+ retentionDays: z.ZodDefault<z.ZodNumber>;
5796
+ /** What closes a watcher. "result": the run ends with a reply, or the
5797
+ * delegation answers. "explicit": only POST /watchers/:id/done, so a
5798
+ * reply that only promises ("I'll publish at 18:00") keeps it open. */
5799
+ doneSignal: z.ZodDefault<z.ZodEnum<["result", "explicit"]>>;
5800
+ }, "strip", z.ZodTypeAny, {
5801
+ enabled: boolean;
5802
+ owner: {
5803
+ channel?: string | undefined;
5804
+ chatId?: string | undefined;
5805
+ };
5806
+ retentionDays: number;
5807
+ skipChannels: string[];
5808
+ defaultDueMinutes: number;
5809
+ noBelow: number;
5810
+ yesAt: number;
5811
+ escalateAfterMinutes: number;
5812
+ doneSignal: "result" | "explicit";
5813
+ }, {
5814
+ enabled?: boolean | undefined;
5815
+ owner?: {
5816
+ channel?: string | undefined;
5817
+ chatId?: string | undefined;
5818
+ } | undefined;
5819
+ retentionDays?: number | undefined;
5820
+ skipChannels?: string[] | undefined;
5821
+ defaultDueMinutes?: number | undefined;
5822
+ noBelow?: number | undefined;
5823
+ yesAt?: number | undefined;
5824
+ escalateAfterMinutes?: number | undefined;
5825
+ doneSignal?: "result" | "explicit" | undefined;
5826
+ }>>, {
5827
+ enabled: boolean;
5828
+ owner: {
5829
+ channel?: string | undefined;
5830
+ chatId?: string | undefined;
5831
+ };
5832
+ retentionDays: number;
5833
+ skipChannels: string[];
5834
+ defaultDueMinutes: number;
5835
+ noBelow: number;
5836
+ yesAt: number;
5837
+ escalateAfterMinutes: number;
5838
+ doneSignal: "result" | "explicit";
5839
+ }, {
5840
+ enabled?: boolean | undefined;
5841
+ owner?: {
5842
+ channel?: string | undefined;
5843
+ chatId?: string | undefined;
5844
+ } | undefined;
5845
+ retentionDays?: number | undefined;
5846
+ skipChannels?: string[] | undefined;
5847
+ defaultDueMinutes?: number | undefined;
5848
+ noBelow?: number | undefined;
5849
+ yesAt?: number | undefined;
5850
+ escalateAfterMinutes?: number | undefined;
5851
+ doneSignal?: "result" | "explicit" | undefined;
5852
+ } | undefined>;
5765
5853
  people: z.ZodEffects<z.ZodDefault<z.ZodArray<z.ZodObject<{
5766
5854
  id: z.ZodString;
5767
5855
  name: z.ZodString;
@@ -8776,6 +8864,20 @@ declare const daemonConfigSchema: z.ZodObject<{
8776
8864
  allowPeers: string[];
8777
8865
  maxPerRoot: number;
8778
8866
  };
8867
+ watchers: {
8868
+ enabled: boolean;
8869
+ owner: {
8870
+ channel?: string | undefined;
8871
+ chatId?: string | undefined;
8872
+ };
8873
+ retentionDays: number;
8874
+ skipChannels: string[];
8875
+ defaultDueMinutes: number;
8876
+ noBelow: number;
8877
+ yesAt: number;
8878
+ escalateAfterMinutes: number;
8879
+ doneSignal: "result" | "explicit";
8880
+ };
8779
8881
  people: {
8780
8882
  agents: string[];
8781
8883
  id: string;
@@ -9816,6 +9918,20 @@ declare const daemonConfigSchema: z.ZodObject<{
9816
9918
  allowPeers?: string[] | undefined;
9817
9919
  maxPerRoot?: number | undefined;
9818
9920
  } | undefined;
9921
+ watchers?: {
9922
+ enabled?: boolean | undefined;
9923
+ owner?: {
9924
+ channel?: string | undefined;
9925
+ chatId?: string | undefined;
9926
+ } | undefined;
9927
+ retentionDays?: number | undefined;
9928
+ skipChannels?: string[] | undefined;
9929
+ defaultDueMinutes?: number | undefined;
9930
+ noBelow?: number | undefined;
9931
+ yesAt?: number | undefined;
9932
+ escalateAfterMinutes?: number | undefined;
9933
+ doneSignal?: "result" | "explicit" | undefined;
9934
+ } | undefined;
9819
9935
  people?: {
9820
9936
  id: string;
9821
9937
  name: string;
@@ -10449,6 +10565,9 @@ interface AgentXEvents {
10449
10565
  * node's own surfaces (requests/operator): it started the turn itself,
10450
10566
  * or the /task caller showed the operator key (#393). */
10451
10567
  operator?: boolean;
10568
+ /** When the task is due (ms), when the caller gave one in the run's
10569
+ * context as `dueAt` (watchers, #1030). */
10570
+ dueAt?: number;
10452
10571
  };
10453
10572
  /** A single step inside an in-flight task — typically a tool call or
10454
10573
  * tool result inside the Claude streaming response. Producer is the
@@ -10807,6 +10926,12 @@ declare class AgentXDaemon {
10807
10926
  /** In-flight work the drain waits for: local agent tasks + mesh forwards. */
10808
10927
  /** The runs in flight, oldest first: what a restart would cut off. */
10809
10928
  private runningSummaries;
10929
+ /** Which token a GitLab write for this agent would use (#984). */
10930
+ private postingIdentity;
10931
+ /** GitLab token health for /health: absent when the channel is off. A
10932
+ * rejected global token is called out, since every agent without its
10933
+ * own token posts with it (#984). */
10934
+ private gitlabHealth;
10810
10935
  private inflightCounts;
10811
10936
  /** Set by start(): the same graceful path a SIGTERM takes. */
10812
10937
  private requestShutdown?;
@@ -10872,6 +10997,9 @@ declare class AgentXDaemon {
10872
10997
  * is the owner's (requests/operator, #393). */
10873
10998
  private operatorKey;
10874
10999
  private requestsSweeping;
11000
+ /** Task watchers (src/watchers, #1030). */
11001
+ private watchers;
11002
+ private watchersSweeping;
10875
11003
  private status;
10876
11004
  /** Send a status-comment edit to the peer that holds the agent's token. */
10877
11005
  private forwardCommentEdit;
@@ -10918,6 +11046,8 @@ declare class AgentXDaemon {
10918
11046
  * closed ones are deleted (src/requests/sweep.ts). Plans first: a
10919
11047
  * blocked step marks its request told, so the owner hears once. */
10920
11048
  private sweepRequests;
11049
+ /** The watcher checkpoint at every task start (src/watchers, #1030). */
11050
+ private attachTaskWatchers;
10921
11051
  /** Tell the owner through the notify path: a push to the default
10922
11052
  * channel, the Mac banner where there is one (#788). */
10923
11053
  private notifyOwner;
@@ -16910,7 +17040,9 @@ declare class WhatsAppAdapter implements ChannelAdapter {
16910
17040
  private routes;
16911
17041
  private handler?;
16912
17042
  private sock;
16913
- private reconnectAttempts;
17043
+ private reconnect;
17044
+ /** Resets the reconnect counters once a connection has stayed open for a while. */
17045
+ private stableTimer;
16914
17046
  /** Generation counter — incremented on each start() to ignore stale socket events */
16915
17047
  private generation;
16916
17048
  private sentMessageIds;
@@ -16930,6 +17062,8 @@ declare class WhatsAppAdapter implements ChannelAdapter {
16930
17062
  private onQR?;
16931
17063
  /** Fires whenever the connection state changes (connecting / open / close). */
16932
17064
  private onStatus?;
17065
+ /** Fires once when the adapter stops reconnecting, so the owner hears about a silent channel. */
17066
+ private onGiveUp?;
16933
17067
  constructor(config: {
16934
17068
  sessionDir: string;
16935
17069
  defaultAgent?: string;
@@ -16937,6 +17071,7 @@ declare class WhatsAppAdapter implements ChannelAdapter {
16937
17071
  routes?: WhatsAppRoute[];
16938
17072
  onQR?: (qr: string | null) => void;
16939
17073
  onStatus?: (status: "connecting" | "open" | "close", detail?: string) => void;
17074
+ onGiveUp?: (message: string) => void;
16940
17075
  /** Throttle settings for live Baileys reads. Falls back to safe defaults. */
16941
17076
  throttle?: {
16942
17077
  minMsBetweenCalls?: number;
@@ -16957,6 +17092,8 @@ declare class WhatsAppAdapter implements ChannelAdapter {
16957
17092
  onMessage(handler: (msg: IncomingMessage) => Promise<void>): void;
16958
17093
  start(): Promise<void>;
16959
17094
  stop(): Promise<void>;
17095
+ private clearStableTimer;
17096
+ private resetReconnect;
16960
17097
  send(msg: OutgoingMessage): Promise<string>;
16961
17098
  editMessage(chatId: string, messageId: string, text: string): Promise<boolean>;
16962
17099
  sendTyping(chatId: string): Promise<void>;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-FUJ4KEWS.js";import"./chunk-KO6BU3B3.js";import"./chunk-GTJIKXDB.js";import"./chunk-J7U3BASX.js";import"./chunk-7LN4VKDU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-UNIXYV3U.js";import"./chunk-AKWBDCMU.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-EMGB23H5.js";import"./chunk-JAML6222.js";import"./chunk-YMX3QCV7.js";import"./chunk-JWDJMFU6.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-A5GYG56I.js";import"./chunk-Z5IHT6RK.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-RIYQNADV.js";import"./chunk-2BEZU5OF.js";import"./chunk-QSKG754X.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-UG2OF2EI.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-MUC7MMTT.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-3W2BHUGM.js";import"./chunk-SHEUCITK.js";import"./chunk-ANDEMOYE.js";import"./chunk-SZDACK6O.js";import"./chunk-HF5EF335.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-JS2LEURJ.js";import"./chunk-NMYPZR4W.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-AXHP6TMT.js";import{a as ht}from"./chunk-STIZFWDJ.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-HXLB2XCT.js";import"./chunk-SKSYII3K.js";import{f as gt,g as ft}from"./chunk-7KAQHNLT.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-JJZVFDG6.js";import{j as it,k as rt,l as at}from"./chunk-LMZCB7TT.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Aa as nt,qa as tt,sa as st,ta as ot}from"./chunk-MGM33GOW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-HYVRS3G3.js";import"./chunk-2JQSWX7U.js";import"./chunk-GTJIKXDB.js";import"./chunk-FUGDD6UW.js";import"./chunk-S2GAEH2F.js";import"./chunk-7LN4VKDU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-UNIXYV3U.js";import"./chunk-AKWBDCMU.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-QSQWVQLD.js";import"./chunk-EMGB23H5.js";import"./chunk-JAML6222.js";import"./chunk-YMX3QCV7.js";import"./chunk-JWDJMFU6.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-Y4CYQV7G.js";import"./chunk-3W2BHUGM.js";import"./chunk-SHEUCITK.js";import"./chunk-A5GYG56I.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-GQOMV52Y.js";import"./chunk-O6KRXVN7.js";import"./chunk-QSKG754X.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-UG2OF2EI.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-OCTWRSOI.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-GG6K5ZL6.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-GPDVETDE.js";import"./chunk-QHXKELKQ.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-U72JN4YF.js";import{a as ht}from"./chunk-4ZKXEUQP.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PPT2MXQY.js";import"./chunk-SKSYII3K.js";import{f as gt,g as ft}from"./chunk-Z46SZWMO.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-2NTRAVHC.js";import{j as it,k as rt,l as at}from"./chunk-PILE2SH3.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Ba as nt,ra as tt,ta as st,ua as ot}from"./chunk-TF5356HW.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).