agentix-cli 0.218.0 → 0.219.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 (148) hide show
  1. package/README.md +87 -207
  2. package/dist/{App-2IEK5HWX.js → App-ET75JEWK.js} +2 -2
  3. package/dist/{ChatApp-YHC7ASGR.js → ChatApp-F2NT5M2O.js} +2 -2
  4. package/dist/{absorb-eval-GJ47IOFG.js → absorb-eval-EA5ESP4Y.js} +2 -2
  5. package/dist/{adapter-WROHSAHE.js → adapter-7PKOKXO5.js} +2 -2
  6. package/dist/{agent-5MYO4YCO.js → agent-SDNU6MUI.js} +2 -2
  7. package/dist/{board-dashboard-3CSSUGNZ.js → board-dashboard-PI22IXZN.js} +5 -5
  8. package/dist/{board-dashboard-3CSSUGNZ.js.map → board-dashboard-PI22IXZN.js.map} +1 -1
  9. package/dist/{chunk-CHCAPQ6E.js → chunk-34TEBXFP.js} +2 -2
  10. package/dist/{chunk-MSOAI54R.js → chunk-3XUAIA7U.js} +2 -2
  11. package/dist/{chunk-QEGBOPAP.js → chunk-5OEW46QP.js} +2 -2
  12. package/dist/{chunk-HCQX6LVZ.js → chunk-6HCCMU57.js} +2 -2
  13. package/dist/{chunk-EVFQINOQ.js → chunk-6X7SABYJ.js} +2 -2
  14. package/dist/{chunk-GP56ZRAF.js → chunk-7ATCEK7R.js} +2 -2
  15. package/dist/{chunk-B7WQT7GG.js → chunk-CR37IINZ.js} +2 -2
  16. package/dist/{chunk-K5VZS747.js → chunk-DGCYSQAZ.js} +2 -2
  17. package/dist/{chunk-GMQLDXEM.js → chunk-EPOQUX4G.js} +2 -2
  18. package/dist/{chunk-WZIFXZZX.js → chunk-EWXY73XA.js} +2 -2
  19. package/dist/{chunk-JE2EV6NS.js → chunk-EZDHAX4Z.js} +31 -30
  20. package/dist/chunk-EZDHAX4Z.js.map +1 -0
  21. package/dist/{chunk-NJLWS44P.js → chunk-GPX4LDAX.js} +2 -2
  22. package/dist/{chunk-ETMUGFPI.js → chunk-HHSPOS7O.js} +2 -2
  23. package/dist/{chunk-B5JK4MQX.js → chunk-IIJB3OPV.js} +2 -2
  24. package/dist/{chunk-NLMQ7ZAE.js → chunk-IKOJM4GM.js} +2 -2
  25. package/dist/{chunk-IATCZJP7.js → chunk-IQNKEUEL.js} +2 -2
  26. package/dist/{chunk-QAMVAZ67.js → chunk-KCS737RC.js} +2 -2
  27. package/dist/{chunk-D3HNIOZ7.js → chunk-MELXJ5AR.js} +2 -2
  28. package/dist/{chunk-FJJ5PVQK.js → chunk-MUCWUVOW.js} +5 -5
  29. package/dist/{chunk-AKPLNPUY.js → chunk-PTVDVI2U.js} +2 -2
  30. package/dist/{chunk-2REJBHT5.js → chunk-SQJ3IHNL.js} +2 -2
  31. package/dist/{chunk-ZXABOPXF.js → chunk-TCBIAKGS.js} +2 -2
  32. package/dist/chunk-U4AUJ6XI.js +39 -0
  33. package/dist/chunk-U4AUJ6XI.js.map +1 -0
  34. package/dist/{chunk-M75VNIVM.js → chunk-UYDC2YMH.js} +2 -2
  35. package/dist/{chunk-YG5GPPGI.js → chunk-V75JESS5.js} +3 -3
  36. package/dist/{chunk-VFG7GZC6.js → chunk-W2KIJ5LL.js} +2 -2
  37. package/dist/{chunk-PJ2OFOAL.js → chunk-XTXFA5EJ.js} +2 -2
  38. package/dist/{chunk-X23I2U26.js → chunk-Y3TXTZYG.js} +2 -2
  39. package/dist/{chunk-QW5WOBSU.js → chunk-YMMGY7GR.js} +2 -2
  40. package/dist/{chunk-FSEJ2LX5.js → chunk-Z3FJRBTG.js} +337 -336
  41. package/dist/chunk-Z3FJRBTG.js.map +1 -0
  42. package/dist/{chunk-OQEP2Q32.js → chunk-ZT4FCL5B.js} +2 -2
  43. package/dist/cli.js +1 -1
  44. package/dist/{client-2TJ3TOCH.js → client-7PLIDORM.js} +2 -2
  45. package/dist/{config-JHSM6KFT.js → config-3R4EGNUG.js} +2 -2
  46. package/dist/{config-mutate-YERBKGAB.js → config-mutate-3PGEBKJ6.js} +2 -2
  47. package/dist/{config-mutator-WNNU4EDV.js → config-mutator-LQQOOUZR.js} +2 -2
  48. package/dist/{contributions-HAWUHQWM.js → contributions-D4O76KGX.js} +2 -2
  49. package/dist/{doctor-GOMB6LDS.js → doctor-QM4KUMQJ.js} +2 -2
  50. package/dist/{follow-up-tool-5YFJS2JZ.js → follow-up-tool-X3YPYSP2.js} +2 -2
  51. package/dist/{hub-3M4HJMYR.js → hub-PBJHXL2G.js} +2 -2
  52. package/dist/index.d.ts +48 -0
  53. package/dist/index.js +1 -1
  54. package/dist/{org-tool-JS4WKB35.js → org-tool-37GNUUAD.js} +2 -2
  55. package/dist/{program-OFMRVB7N.js → program-243AGBJJ.js} +26 -26
  56. package/dist/program-243AGBJJ.js.map +1 -0
  57. package/dist/{promote-BME3QLM6.js → promote-CFI4HJDJ.js} +2 -2
  58. package/dist/{query-BFZDI667.js → query-J6S3GWPY.js} +2 -2
  59. package/dist/{query-settings-ICYJNA6H.js → query-settings-2NKI7UFN.js} +2 -2
  60. package/dist/{registry-NUO4JEA5.js → registry-R2QIR6GI.js} +2 -2
  61. package/dist/{request-planner-CUAEVQKB.js → request-planner-NKGUSV4N.js} +2 -2
  62. package/dist/{review-candidates-PGF3IRZR.js → review-candidates-43HXKXWD.js} +2 -2
  63. package/dist/{routing-CXGJMM55.js → routing-72F2DJTV.js} +2 -2
  64. package/dist/{schedule-tool-G3RBORJS.js → schedule-tool-V3KMSJHK.js} +2 -2
  65. package/dist/{scheduler-FKCNMUB7.js → scheduler-ZBTMOE3T.js} +2 -2
  66. package/dist/{seat-6TUUPDR6.js → seat-GYYH2IW5.js} +2 -2
  67. package/dist/{select-ARQMXFFV.js → select-JNVP4P5N.js} +2 -2
  68. package/dist/{set-enabled-CYS6NYKQ.js → set-enabled-U26A4RMI.js} +2 -2
  69. package/dist/{sprint-tool-5RNJZDQJ.js → sprint-tool-YCDVAF2Y.js} +2 -2
  70. package/dist/{tool-CHHSFKU2.js → tool-CF7OTKDV.js} +2 -2
  71. package/dist/tool-GHQ2FM4T.js +10 -0
  72. package/dist/tool-GHQ2FM4T.js.map +1 -0
  73. package/dist/{tool-YQFTOJJL.js → tool-JEHJS2SA.js} +2 -2
  74. package/dist/tool-K3RAEZKE.js +2 -0
  75. package/dist/{tool-KY7WN3HV.js → tool-MB3IYEP7.js} +2 -2
  76. package/dist/{wiki-RJKQ6ZLV.js → wiki-6UFGH2OO.js} +2 -2
  77. package/dist/wiki-enrich-7LMT3CFV.js +2 -0
  78. package/package.json +2 -2
  79. package/dist/chunk-FSEJ2LX5.js.map +0 -1
  80. package/dist/chunk-JE2EV6NS.js.map +0 -1
  81. package/dist/chunk-YB2QYUXG.js +0 -38
  82. package/dist/chunk-YB2QYUXG.js.map +0 -1
  83. package/dist/program-OFMRVB7N.js.map +0 -1
  84. package/dist/tool-243ZBIYG.js +0 -2
  85. package/dist/tool-JAVKPEKS.js +0 -10
  86. package/dist/tool-JAVKPEKS.js.map +0 -1
  87. package/dist/wiki-enrich-4ZKID3ZU.js +0 -2
  88. /package/dist/{App-2IEK5HWX.js.map → App-ET75JEWK.js.map} +0 -0
  89. /package/dist/{ChatApp-YHC7ASGR.js.map → ChatApp-F2NT5M2O.js.map} +0 -0
  90. /package/dist/{absorb-eval-GJ47IOFG.js.map → absorb-eval-EA5ESP4Y.js.map} +0 -0
  91. /package/dist/{adapter-WROHSAHE.js.map → adapter-7PKOKXO5.js.map} +0 -0
  92. /package/dist/{agent-5MYO4YCO.js.map → agent-SDNU6MUI.js.map} +0 -0
  93. /package/dist/{chunk-CHCAPQ6E.js.map → chunk-34TEBXFP.js.map} +0 -0
  94. /package/dist/{chunk-MSOAI54R.js.map → chunk-3XUAIA7U.js.map} +0 -0
  95. /package/dist/{chunk-QEGBOPAP.js.map → chunk-5OEW46QP.js.map} +0 -0
  96. /package/dist/{chunk-HCQX6LVZ.js.map → chunk-6HCCMU57.js.map} +0 -0
  97. /package/dist/{chunk-EVFQINOQ.js.map → chunk-6X7SABYJ.js.map} +0 -0
  98. /package/dist/{chunk-GP56ZRAF.js.map → chunk-7ATCEK7R.js.map} +0 -0
  99. /package/dist/{chunk-B7WQT7GG.js.map → chunk-CR37IINZ.js.map} +0 -0
  100. /package/dist/{chunk-K5VZS747.js.map → chunk-DGCYSQAZ.js.map} +0 -0
  101. /package/dist/{chunk-GMQLDXEM.js.map → chunk-EPOQUX4G.js.map} +0 -0
  102. /package/dist/{chunk-WZIFXZZX.js.map → chunk-EWXY73XA.js.map} +0 -0
  103. /package/dist/{chunk-NJLWS44P.js.map → chunk-GPX4LDAX.js.map} +0 -0
  104. /package/dist/{chunk-ETMUGFPI.js.map → chunk-HHSPOS7O.js.map} +0 -0
  105. /package/dist/{chunk-B5JK4MQX.js.map → chunk-IIJB3OPV.js.map} +0 -0
  106. /package/dist/{chunk-NLMQ7ZAE.js.map → chunk-IKOJM4GM.js.map} +0 -0
  107. /package/dist/{chunk-IATCZJP7.js.map → chunk-IQNKEUEL.js.map} +0 -0
  108. /package/dist/{chunk-QAMVAZ67.js.map → chunk-KCS737RC.js.map} +0 -0
  109. /package/dist/{chunk-D3HNIOZ7.js.map → chunk-MELXJ5AR.js.map} +0 -0
  110. /package/dist/{chunk-FJJ5PVQK.js.map → chunk-MUCWUVOW.js.map} +0 -0
  111. /package/dist/{chunk-AKPLNPUY.js.map → chunk-PTVDVI2U.js.map} +0 -0
  112. /package/dist/{chunk-2REJBHT5.js.map → chunk-SQJ3IHNL.js.map} +0 -0
  113. /package/dist/{chunk-ZXABOPXF.js.map → chunk-TCBIAKGS.js.map} +0 -0
  114. /package/dist/{chunk-M75VNIVM.js.map → chunk-UYDC2YMH.js.map} +0 -0
  115. /package/dist/{chunk-YG5GPPGI.js.map → chunk-V75JESS5.js.map} +0 -0
  116. /package/dist/{chunk-VFG7GZC6.js.map → chunk-W2KIJ5LL.js.map} +0 -0
  117. /package/dist/{chunk-PJ2OFOAL.js.map → chunk-XTXFA5EJ.js.map} +0 -0
  118. /package/dist/{chunk-X23I2U26.js.map → chunk-Y3TXTZYG.js.map} +0 -0
  119. /package/dist/{chunk-QW5WOBSU.js.map → chunk-YMMGY7GR.js.map} +0 -0
  120. /package/dist/{chunk-OQEP2Q32.js.map → chunk-ZT4FCL5B.js.map} +0 -0
  121. /package/dist/{client-2TJ3TOCH.js.map → client-7PLIDORM.js.map} +0 -0
  122. /package/dist/{config-JHSM6KFT.js.map → config-3R4EGNUG.js.map} +0 -0
  123. /package/dist/{config-mutate-YERBKGAB.js.map → config-mutate-3PGEBKJ6.js.map} +0 -0
  124. /package/dist/{config-mutator-WNNU4EDV.js.map → config-mutator-LQQOOUZR.js.map} +0 -0
  125. /package/dist/{contributions-HAWUHQWM.js.map → contributions-D4O76KGX.js.map} +0 -0
  126. /package/dist/{doctor-GOMB6LDS.js.map → doctor-QM4KUMQJ.js.map} +0 -0
  127. /package/dist/{follow-up-tool-5YFJS2JZ.js.map → follow-up-tool-X3YPYSP2.js.map} +0 -0
  128. /package/dist/{hub-3M4HJMYR.js.map → hub-PBJHXL2G.js.map} +0 -0
  129. /package/dist/{org-tool-JS4WKB35.js.map → org-tool-37GNUUAD.js.map} +0 -0
  130. /package/dist/{promote-BME3QLM6.js.map → promote-CFI4HJDJ.js.map} +0 -0
  131. /package/dist/{query-BFZDI667.js.map → query-J6S3GWPY.js.map} +0 -0
  132. /package/dist/{query-settings-ICYJNA6H.js.map → query-settings-2NKI7UFN.js.map} +0 -0
  133. /package/dist/{registry-NUO4JEA5.js.map → registry-R2QIR6GI.js.map} +0 -0
  134. /package/dist/{request-planner-CUAEVQKB.js.map → request-planner-NKGUSV4N.js.map} +0 -0
  135. /package/dist/{review-candidates-PGF3IRZR.js.map → review-candidates-43HXKXWD.js.map} +0 -0
  136. /package/dist/{routing-CXGJMM55.js.map → routing-72F2DJTV.js.map} +0 -0
  137. /package/dist/{schedule-tool-G3RBORJS.js.map → schedule-tool-V3KMSJHK.js.map} +0 -0
  138. /package/dist/{scheduler-FKCNMUB7.js.map → scheduler-ZBTMOE3T.js.map} +0 -0
  139. /package/dist/{seat-6TUUPDR6.js.map → seat-GYYH2IW5.js.map} +0 -0
  140. /package/dist/{select-ARQMXFFV.js.map → select-JNVP4P5N.js.map} +0 -0
  141. /package/dist/{set-enabled-CYS6NYKQ.js.map → set-enabled-U26A4RMI.js.map} +0 -0
  142. /package/dist/{sprint-tool-5RNJZDQJ.js.map → sprint-tool-YCDVAF2Y.js.map} +0 -0
  143. /package/dist/{tool-CHHSFKU2.js.map → tool-CF7OTKDV.js.map} +0 -0
  144. /package/dist/{tool-YQFTOJJL.js.map → tool-JEHJS2SA.js.map} +0 -0
  145. /package/dist/{tool-243ZBIYG.js.map → tool-K3RAEZKE.js.map} +0 -0
  146. /package/dist/{tool-KY7WN3HV.js.map → tool-MB3IYEP7.js.map} +0 -0
  147. /package/dist/{wiki-RJKQ6ZLV.js.map → wiki-6UFGH2OO.js.map} +0 -0
  148. /package/dist/{wiki-enrich-4ZKID3ZU.js.map → wiki-enrich-7LMT3CFV.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-QW5WOBSU.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-YMMGY7GR.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
- //# sourceMappingURL=chunk-AKPLNPUY.js.map
6
+ //# sourceMappingURL=chunk-PTVDVI2U.js.map
@@ -1,4 +1,4 @@
1
- import{a as l}from"./chunk-IATCZJP7.js";import{resolve as s}from"path";import{existsSync as h,readdirSync as p,mkdirSync as u,readFileSync as f,writeFileSync as m,renameSync as S}from"fs";var y=g=>{try{return p(g,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},b=g=>{let t=s(g,"agents");return y(t).some(r=>y(s(t,r)).some(e=>h(s(t,r,e,"_index.md"))))};function w(g){for(let t of[g,s(g,".agentx/wiki")])if(b(t))return t;return null}var k=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=s(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),e="graph"){this.baseDir=t,this.agentsDir=s(t,"agents"),this.mode=e,this.log=r,u(this.agentsDir,{recursive:!0}),this.sharedStore=new l(t,r)}getMode(){return this.mode}getAgentWiki(t){let r=`${t}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let e=s(this.agentsDir,t,this.mode),i=new l(e,this.log);return this.agentStores.set(r,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(t){return[...this.listAgentDirs().filter(e=>e!==t).map(e=>({id:e,store:this.getAgentWiki(e)})),{id:"shared",store:this.sharedStore,skip:e=>e.startsWith("agents/")}]}listAgentDirs(){return h(this.agentsDir)?p(this.agentsDir).filter(t=>!t.startsWith("_")&&!t.startsWith(".")&&h(s(this.agentsDir,t,this.mode))).sort():[]}listAgents(t=this.sharedStore.listEntries()){let r=new Set;for(let e of t)r.add(e.agentId);if(h(this.agentsDir))for(let e of p(this.agentsDir))!e.startsWith("_")&&!e.startsWith(".")&&r.add(e);return[...r].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){return this.classifyEntries(t).pending}markProcessed(t,r,e){let i=new Set(e),d=this.readLedger(t),c=new Date().toISOString();for(let n of r)d.entries[n]={at:c,cited:i.has(n)};let o=this.ledgerPath(t);u(s(o,".."),{recursive:!0});let a=`${o}.tmp`;m(a,`${JSON.stringify(d,null,2)}
1
+ import{a as l}from"./chunk-IQNKEUEL.js";import{resolve as s}from"path";import{existsSync as h,readdirSync as p,mkdirSync as u,readFileSync as f,writeFileSync as m,renameSync as S}from"fs";var y=g=>{try{return p(g,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}},b=g=>{let t=s(g,"agents");return y(t).some(r=>y(s(t,r)).some(e=>h(s(t,r,e,"_index.md"))))};function w(g){for(let t of[g,s(g,".agentx/wiki")])if(b(t))return t;return null}var k=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=s(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),e="graph"){this.baseDir=t,this.agentsDir=s(t,"agents"),this.mode=e,this.log=r,u(this.agentsDir,{recursive:!0}),this.sharedStore=new l(t,r)}getMode(){return this.mode}getAgentWiki(t){let r=`${t}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let e=s(this.agentsDir,t,this.mode),i=new l(e,this.log);return this.agentStores.set(r,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(t){return[...this.listAgentDirs().filter(e=>e!==t).map(e=>({id:e,store:this.getAgentWiki(e)})),{id:"shared",store:this.sharedStore,skip:e=>e.startsWith("agents/")}]}listAgentDirs(){return h(this.agentsDir)?p(this.agentsDir).filter(t=>!t.startsWith("_")&&!t.startsWith(".")&&h(s(this.agentsDir,t,this.mode))).sort():[]}listAgents(t=this.sharedStore.listEntries()){let r=new Set;for(let e of t)r.add(e.agentId);if(h(this.agentsDir))for(let e of p(this.agentsDir))!e.startsWith("_")&&!e.startsWith(".")&&r.add(e);return[...r].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){return this.classifyEntries(t).pending}markProcessed(t,r,e){let i=new Set(e),d=this.readLedger(t),c=new Date().toISOString();for(let n of r)d.entries[n]={at:c,cited:i.has(n)};let o=this.ledgerPath(t);u(s(o,".."),{recursive:!0});let a=`${o}.tmp`;m(a,`${JSON.stringify(d,null,2)}
2
2
  `),S(a,o)}summary(){let t=this.sharedStore.listEntries(),r=new Map;for(let e of t){let i=r.get(e.agentId);i?i.push(e):r.set(e.agentId,[e])}return this.listAgents(t).map(e=>{let{all:i,cited:d,read:c,pending:o,articles:a}=this.classifyEntries(e,r.get(e)??[]);return{agentId:e,totalEntries:i.length,totalArticles:a.length,cited:d.length,readNotCited:c.length,unabsorbed:o.length,articles:a}})}classifyEntries(t,r=this.getAgentEntries(t)){let e=this.getAgentWiki(t).rebuildIndex().articles,i=new Set;for(let n of e)if(n.sources)for(let W of n.sources)i.add(W);let d=this.readLedger(t).entries,c=[],o=[],a=[];for(let n of r)i.has(n.id)?c.push(n):d[n.id]?o.push(n):a.push(n);return{all:r,cited:c,read:o,pending:a,articles:e}}syncedFrom(t){let r=s(this.agentsDir,t,"_synced.json");if(!h(r))return null;try{return JSON.parse(f(r,"utf-8"))}catch(e){return this.log(`synced marker ${r} is not valid JSON: ${e.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(t,r){let e=s(this.agentsDir,t,"_synced.json");u(s(e,".."),{recursive:!0});let i=`${e}.tmp`;m(i,`${JSON.stringify(r,null,2)}
3
3
  `),S(i,e)}ledgerPath(t){return s(this.agentsDir,t,"_absorbed.json")}readLedger(t){let r=this.ledgerPath(t);if(!h(r))return{entries:{}};try{return{entries:JSON.parse(f(r,"utf-8")).entries??{}}}catch(e){throw new Error(`absorb ledger ${r} is not valid JSON: ${e.message}`)}}};export{w as a,k as b};
4
- //# sourceMappingURL=chunk-2REJBHT5.js.map
4
+ //# sourceMappingURL=chunk-SQJ3IHNL.js.map
@@ -1,4 +1,4 @@
1
- import{Bc as m,rc as l}from"./chunk-JE2EV6NS.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
1
+ import{Cc as m,sc as l}from"./chunk-EZDHAX4Z.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
2
2
  `,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
4
- //# sourceMappingURL=chunk-ZXABOPXF.js.map
4
+ //# sourceMappingURL=chunk-TCBIAKGS.js.map
@@ -0,0 +1,39 @@
1
+ import{a as I}from"./chunk-IMLAPB7G.js";import{d as le}from"./chunk-QPABR72X.js";import{b as ue}from"./chunk-KP7KDLZ2.js";import{o as k}from"./chunk-BXK5S2KK.js";import{Ra as oe,Sa as se,Ua as ie,Va as ae,ab as $,gb as ot,o as B,r as rt}from"./chunk-EZDHAX4Z.js";import{accessSync as lt,closeSync as ut,constants as ct,existsSync as fe,openSync as pt,readFileSync as dt,readSync as ft,statSync as mt}from"node:fs";import{dirname as O,join as L}from"node:path";import{fileURLToPath as gt}from"node:url";import{homedir as ht}from"node:os";import{join as ce,win32 as j}from"path";function E(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var U="agentx-helper.exe";function st(e){return j.join(e,"Programs","AgentX",U)}var pe="AgentX Helper.app";function X(e){return ce(e,"Applications",pe,"Contents/MacOS/agentx-mac-helper")}function it(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&E(e)==="macos"?r:void 0}function de(e){let t=it(e.platform,e.env);if(t)return t;let n=E(e.platform);if(n==="macos"){let r=X(e.home);return e.exists(r)||!e.root?r:ce(e.root,"apps/mac-helper/build",pe,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||j.join(e.home,"AppData","Local"),o=st(r);return e.exists(o)||!e.root?o:j.join(e.root,"apps","win-helper","build",U)}return null}function at(e){let t=E(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${U} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function fn(e){let t=E(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=at(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var J="tn.acme.agentx.voice",bn="AgentX Desktop.app",kn="AgentX Helper.app";function xn(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function vn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function G(e){return`'${e.replace(/'/g,"'\\''")}'`}var me="/usr/bin:/bin:/usr/sbin:/sbin";function An(e,t){return t||[...new Set([...e?[O(e)]:[],...me.split(":")])].join(":")}function T(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function Nn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?T(t[1]):me}var Pn=e=>/agentx\.voice.*\.plist$/.test(e);function Rn(e,t){let n=null,r=[];for(let{file:o,plist:s}of[...t].sort((i,a)=>i.file<a.file?-1:1)){let i=s.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],a=s.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!i||!a||!T(a).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:T(i)}):n={file:o,label:T(i)})}return{keep:n??{file:L(e,`${J}.plist`),label:J},remove:r}}function ge(e,t,n){for(let r of t.split(":"))if(r&&n(L(r,e)))return L(r,e);return null}function Cn(e){try{if(lt(e,ct.X_OK),!mt(e).isFile())return!1;let t=pt(e,"r"),n=Buffer.alloc(2);try{ft(t,n,0,2,0)}finally{ut(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function $n(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${G(e.cwd)} && ${G(e.node)} ${G(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>Label</key><string>${t(e.label??J)}</string>
5
+ <key>ProgramArguments</key><array><string>${t(e.executable)}</string></array>
6
+ <key>WorkingDirectory</key><string>${t(e.cwd)}</string>
7
+ <key>EnvironmentVariables</key><dict>${Object.entries(n).map(([r,o])=>`<key>${r}</key><string>${t(o)}</string>`).join("")}</dict>
8
+ <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
9
+ <key>ProcessType</key><string>Interactive</string>
10
+ <key>StandardErrorPath</key><string>${t(e.log)}</string>
11
+ </dict></plist>
12
+ `}function In(e){return e?["--icon",e]:[]}var En=X;function yt(e=O(gt(import.meta.url))){for(let t=e;;t=O(t)){try{if(JSON.parse(dt(L(t,"package.json"),"utf8")).name==="agentix-cli")return t}catch{}if(O(t)===t)return null}}function P(){let e=de({platform:process.platform,root:yt(),home:ht(),env:process.env,exists:fe});return e&&fe(e)?e:null}import{accessSync as vt,constants as At}from"fs";import{execFile as K}from"child_process";var he=5e3,y=(e,t)=>new Promise(n=>{try{K(e,t,{timeout:he},r=>n(!r))}catch{n(!1)}}),m=(e,t)=>new Promise(n=>{try{K(e,t,{timeout:he},(r,o)=>n(r?null:String(o)))}catch{n(null)}}),D=(e,t)=>new Promise((n,r)=>{K(e,t,{timeout:3e4,maxBuffer:8*1024*1024},(o,s,i)=>{o?r(new Error(`${e} ${t[0]}: ${(i||o.message).trim()}`)):n(s)})});var ye=e=>e.helper===void 0?P():e.helper;async function z(e,t=m){if(!e)return"missing";let n=await t(e,["notify-status"]),r=null;try{r=n?JSON.parse(n):null}catch{r=null}return r?r.authorization==="notDetermined"?"not-asked":r.authorization==="denied"?"not-allowed":r.alertStyle==="none"?"hidden":"ready":"outdated"}function we(e={}){let t=e.run??y;return{async post({title:n,message:r}){let o=ye(e);return o&&await t(o,["notify","--title",n,"--message",r])||await t("/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",n,r])?"posted":"failed"},status:()=>z(ye(e),e.capture)}}function wt(e){let t=e.match(/"HIDIdleTime"\s*=\s*(\d+)/);return t?Math.floor(Number(t[1])/1e9):null}function Se(e={}){let t=e.capture??m;return{async seconds(){let n=await t("/usr/sbin/ioreg",["-c","IOHIDSystem","-d","4"]);return n?wt(n):null}}}var St=`
13
+ function run(argv) {
14
+ var folderName = argv[0], title = argv[1], body = argv[2]
15
+ var Notes = Application("Notes")
16
+ var esc = function (s) { return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") }
17
+ var folder = Notes.folders.whose({ name: folderName })()[0]
18
+ if (!folder) {
19
+ folder = Notes.Folder({ name: folderName })
20
+ Notes.folders.push(folder)
21
+ folder = Notes.folders.whose({ name: folderName })()[0]
22
+ }
23
+ var lines = body.split("\\n").map(function (l) { return "<div>" + (l ? esc(l) : "<br>") + "</div>" })
24
+ // Notes takes the title from the first line: a name as well would show it twice.
25
+ var note = Notes.Note({ body: "<div><h1>" + esc(title) + "</h1></div>" + lines.join("") })
26
+ folder.notes.push(note)
27
+ return note.id()
28
+ }
29
+ `;function be(e=D){return{async add({folder:t,title:n,body:r}){let s=(await e("/usr/bin/osascript",["-l","JavaScript","-e",St,t,n,r])).trim();if(!s)throw new Error("Notes did not return the new note's id");return{id:s}}}}import{existsSync as bt,readdirSync as kt}from"fs";var xe="/System/Library/Sounds";function ke(e){if(!/^[\w -]+$/.test(e))return null;let t=`${xe}/${e}.aiff`;return bt(t)?t:null}function ve(e={}){let t=e.run??y;return{async play(n,r){let o=ke(n);o&&await t("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,r))),o])},has:n=>ke(n)!==null,async names(){try{return kt(xe).filter(n=>n.endsWith(".aiff")).map(n=>n.slice(0,-5)).sort()}catch{return[]}}}}var Ae={say:"a spoken line (say)",afplay:"a sound playing (afplay)"};function xt(e,t,n=process.pid){for(let r of e.split(`
30
+ `)){let o=r.trim().match(/^(\d+)\s+(\d+)\s+(\S+)/);if(!o)continue;let[s,i,a]=[Number(o[1]),Number(o[2]),o[3]],l=a.slice(a.lastIndexOf("/")+1);if(!(!(l in Ae)||s===n||t.includes(i)))return Ae[l]}return null}function Ne(e={}){let t=e.capture??m;return{async othersSpeaking(n={}){let r=await t("/bin/ps",["-axo","pid=,ppid=,comm="]);return r?xt(r,n.exceptParents??[]):null}}}var Ce="\u200B";function M(e){return e.startsWith("-")?Ce+e:e}var Pe=e=>e?.startsWith(Ce+"-")?e.slice(1):e;function V(e){if(!e.trim()||e.startsWith("-"))throw new Error(`Reminders list name "${e}" is not usable: it must not be empty or start with "-"`);return e}var Re=e=>new Date(Math.floor(e.getTime()/6e4)*6e4).toISOString().replace(/\.\d{3}Z$/,"Z");function $e(e="remindctl",t=D){return{async ensureList(n){let r=await t(e,["list","--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} list: expected a JSON array`);o.some(s=>s?.title===n)||await t(e,["list",V(n),"--create","--json","--no-input"])},async listOpen(n){let r=await t(e,["show","all","--list",V(n),"--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} show: expected a JSON array`);return o.filter(s=>s&&typeof s.id=="string"&&!s.isCompleted).map(s=>({...s,title:Pe(s.title)??"",...s.notes!==void 0?{notes:Pe(s.notes)}:{}}))},async add({list:n,title:r,notes:o,due:s,priority:i}){let a=["add","--title",M(r),"--list",V(n),"--notes",M(o)];s&&a.push("--due",Re(s)),i&&i!=="none"&&a.push("--priority",i);let l=await t(e,[...a,"--json","--no-input"]),c;try{c=JSON.parse(l.trim())?.id}catch{c=void 0}if(typeof c!="string"||!c)throw new Error(`${e} add: no reminder id in its answer`);return{id:c}},async update(n,r){let o=["edit",n];r.title!==void 0&&o.push("--title",M(r.title)),r.notes!==void 0&&o.push("--notes",M(r.notes)),r.due===null?o.push("--clear-due"):r.due&&o.push("--due",Re(r.due)),o.length!==2&&await t(e,[...o,"--json","--no-input"])},async complete(n){await t(e,["complete",n,"--json","--no-input"])},async remove(n){await t(e,["delete",n,"--force","--json","--no-input"])}}}var Nt=e=>{try{return vt(e,At.X_OK),!0}catch{return!1}},Pt={async active(){let e=ue();return e.active?!0:e.reason==="no active Focus assertion"?!1:null}};function Ie(e={},t={}){let n=e.reminders?.command||"remindctl";return{os:"macos",tasks:$e(n,t.output),notes:be(t.output),banner:we(t),sound:ve(t),focus:Pt,speech:Ne(t),idle:Se(t),async describe(){let r=[],o=t.isExecutable??Nt;return(n.includes("/")?o(n):!!ge(n,process.env.PATH||"",o))||r.push(`Reminders: ${n} not found (brew install steipete/tap/remindctl, or set reminders.command).`),{os:"macos",tasks:!0,notes:!0,banner:!0,sound:!0,focus:!0,problems:r}}}}function _(e){return{os:"none",async describe(){return{os:"none",tasks:!1,notes:!1,banner:!1,sound:!1,focus:!1,problems:[e]}}}}import{existsSync as Ot,readdirSync as Tt}from"fs";import{win32 as Lt}from"path";var x="powershell.exe";function v(e){return`'${e.replace(/['‘’‚‛]/g,t=>t+t)}'`}function A(e){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")]}var Rt="{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";function Ct(e,t){return["$ErrorActionPreference = 'Stop'","[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","$t = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)","$x = $t.GetElementsByTagName('text')",`$x.Item(0).AppendChild($t.CreateTextNode(${v(e)})) | Out-Null`,`$x.Item(1).AppendChild($t.CreateTextNode(${v(t)})) | Out-Null`,`[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${v(Rt)}).Show([Windows.UI.Notifications.ToastNotification]::new($t))`].join(`
31
+ `)}function Ee(e){let t=e.run??y;return{async post({title:n,message:r}){let o=e.helper();return o&&await t(o,["notify","--title",n,"--message",r])||await t(x,A(Ct(n,r)))?"posted":"failed"},status:()=>z(e.helper(),e.capture??m)}}var $t=["Add-Type -TypeDefinition @'","using System; using System.Runtime.InteropServices;","public static class AgentXIdle {"," [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }",' [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO p);'," public static long Ms() { var i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i);"," if (!GetLastInputInfo(ref i)) return -1; return (long)(uint)(Environment.TickCount - (int)i.dwTime); }","}","'@","[AgentXIdle]::Ms()"].join(`
32
+ `);function It(e){let t=Number(e.trim());return Number.isFinite(t)&&t>=0&&e.trim()!==""?Math.floor(t/1e3):null}function Oe(e={}){let t=e.capture??m;return{async seconds(){let n=await t(x,A($t));return n?It(n):null}}}import{win32 as Et}from"path";function Te(e,t){if(!/^[\w -]+$/.test(e))return null;let n=Et.join(t.media,`${e}.wav`);return t.exists(n)?n:null}function Le(e){let t=e.run??y;return{async play(n,r){let o=Te(n,e);!o||!(r>0)||await t(x,A(`(New-Object Media.SoundPlayer ${v(o)}).PlaySync()`))},has:n=>Te(n,e)!==null,async names(){try{return e.list(e.media).filter(n=>/\.wav$/i.test(n)).map(n=>n.slice(0,-4)).sort()}catch{return[]}}}}function De(e={},t={}){let n=()=>t.helper===void 0?P():t.helper,r=t.media??Lt.join(process.env.WINDIR||process.env.SystemRoot||"C:\\Windows","Media"),o=t.exists??Ot,s=t.list??(i=>Tt(i));return{os:"windows",banner:Ee({run:t.run,capture:t.capture,helper:n}),sound:Le({run:t.run,media:r,exists:o,list:s}),idle:Oe({capture:t.capture}),async describe(){let i=["Tasks, notes and Focus: AgentX has no Windows adapter for these yet."];return n()||i.push("Banners come from Windows PowerShell until the AgentX Windows helper is installed."),{os:"windows",tasks:!1,notes:!1,banner:!0,sound:!0,focus:!1,problems:i}}}}var Dt={darwin:Ie,win32:De};function Q(e={},t={}){if(e.native?.adapter==="none")return _('Turned off: native.adapter is "none".');let n=t.platform??process.platform,r=(t.factories??Dt)[n];return r?r(e,t.io??{}):_(`AgentX has no native adapter for ${n} yet.`)}import{existsSync as Mt}from"fs";import{homedir as _t}from"os";import{isAbsolute as qt}from"path";var Me={banner:!0,sound:!0,soundName:"Glass",volume:.4,quietWaitSeconds:15};function Dr(e){return{...Me,...e??{}}}function Mr(e,t={}){let n=Q({native:t.native},{platform:t.platform,io:{run:t.run,capture:t.capture,helper:t.helper}});return async(r,o)=>{let s=[];if(e.banner&&n.banner&&s.push(n.banner.post({title:r,message:o})),e.sound&&n.sound){let i=n.sound;s.push(Wt(n.speech,(e.quietWaitSeconds??Me.quietWaitSeconds)*1e3,t.pollMs??500).then(a=>a?i.play(e.soundName,e.volume):void 0))}await Promise.all(s)}}async function Wt(e,t,n){if(!e||t<=0)return!0;let r=Date.now()+t;for(;;){if(!await e.othersSpeaking())return!0;if(Date.now()>=r)return!1;await new Promise(o=>setTimeout(o,n))}}function _r(e,t,n=process.platform){let r={...e??{}},o=Q({},{platform:n});if("banner"in t&&(r.banner=!!t.banner),"sound"in t&&(r.sound=!!t.sound),"soundName"in t){let s=String(t.soundName).trim();if(!(o.sound?o.sound.has(s):/^[\w -]+$/.test(s)))throw new Error(`no system sound named "${s}" on this machine`);r.soundName=s}if("icon"in t){let s=String(t.icon??"").trim().replace(/^~(?=\/)/,_t());if(!s)delete r.icon;else{if(!qt(s)||!/\.(png|jpe?g|icns)$/i.test(s))throw new Error("icon must be the full path to a .png, .jpg or .icns file");if(o.banner&&!Mt(s))throw new Error(`no icon file at ${s}`);r.icon=s}}if("volume"in t){let s=Number(t.volume);if(!Number.isFinite(s)||s<0||s>1)throw new Error("volume must be between 0 and 1");r.volume=s}return r}import{existsSync as tn,mkdirSync as nn,readFileSync as rn,renameSync as on,writeFileSync as sn}from"fs";import{dirname as Ve,resolve as an}from"path";ie();ot();ie();rt();var Hr={mode:"off",perCheck:2,askPerCheck:3},qe=500,Ft=e=>e.trim().slice(0,qe)||"the check was met",Ht=[" (agent: ","; its plan stopped with steps left: "];function Bt(e,t){if(e==null)return!1;let n=Ft(t);if(e===n)return!0;if(!e.startsWith(n))return!1;let r=e.slice(n.length);return Ht.some(o=>r.startsWith(o)||e.length>=qe&&o.startsWith(r))}function Br(e,t){let n=e.filter(o=>o.state!=="skipped");if(!n.length)return null;let r=[];for(let o of n){let s=o.state==="done"&&o.evidence?t(o.evidence):null;s&&r.push({deliverable:o.name,link:s,at:o.updatedAt})}return{names:n.map(o=>o.name),proofs:r,fromPlan:!0}}function jt(e,t){return t||(e.deliverables==="unreadable"?{names:["what was asked"],proofs:e.deliverableProofs??[],fromPlan:!1}:e.deliverables?{names:e.deliverables,proofs:e.deliverableProofs??[],fromPlan:!1}:null)}var q=e=>e.trim().replace(/\/+$/,"").toLowerCase();function We(e){let t=[];e.home?.link&&t.push(q(e.home.link));let n=e.closeWhen?.ref;return typeof n=="string"&&n&&t.push(q(n)),t}function Fe(e,t){let n=e.closeWhen;if(n?.kind!=="issue"||n.provider!=="github"&&n.provider!=="gitlab"||typeof n.ref!="string")return!1;try{if(new URL(t).hash)return!1}catch{return!1}let r=B(n.provider,n.ref),o=B(n.provider,t);return!!r&&!!o&&r.project.toLowerCase()===o.project.toLowerCase()&&r.number===o.number&&r.mr===o.mr}function jr(e,t){return We(e).includes(q(t))||Fe(e,t)}function He(e,t,n){let r=e.deliverable.trim().toLowerCase();return r===n.trim().toLowerCase()||r===String(t+1)}function Ut(e,t){if(t.names.length<=1)return[];let n=We(e);return t.names.map((r,o)=>({name:r,i:o})).filter(({name:r,i:o})=>!t.proofs.some(s=>He(s,o,r)&&!n.includes(q(s.link))&&!Fe(e,s.link))).map(({name:r,i:o})=>`${o+1}. ${r}`)}var Xt="held: the owner-words check found this same result a mismatch; it closes again on a new proof link, a changed check result, or the owner's own close";function Gt(e,t,n,r){if(!r||e.ownerCheck!=="mismatch"||!Bt(e.evidence,t))return null;let o=Math.max(e.ownerCheckAt??0,e.sentBackAt??0);return(n?.proofs??e.deliverableProofs??[]).some(i=>i.at>o)?null:Xt}var Be={mode:"off",ownerCheckOn:!1},_e="reading what the owner's words ask for; the check runs again shortly";function je(e){return`no proof link yet for: ${e.join("; ")}`}function Jt(e,t,n,r,o,s){return e.tx(()=>{let i=e.get(t);if(!i||["done","declined","dropped"].includes(i.state))return{outcome:"lost"};let a=s.plan?.(i.id)??null,l=jt(i,a),c=Gt(i,n,l,s.ownerCheckOn);if(c)return e.markChecked(i.id,"held",c,o),{outcome:"held",detail:c};if(s.mode!=="off")if(l){let f=Ut(i,l);if(f.length){let h=je(f);if(s.mode==="block")return e.markChecked(i.id,"proof_missing",h,o),{outcome:"blocked",detail:h,missing:f};e.signalProofMissing(i.id,h,o)&&s.log?.(`[requests] ${i.id} closed by its check with ${h}`)}}else{if(s.mode==="block"&&s.read)return e.markChecked(i.id,"proof_missing",_e,o),{outcome:"reading",detail:_e};s.read&&s.log?.(`[requests] ${i.id} closes by its check before its deliverables were read`)}return e.closeVerified(i.id,r,o)?{outcome:"closed"}:{outcome:"lost"}})}async function Ue(e,t,n,r,o,s){s.mode!=="off"&&s.read&&t.deliverables==null&&!s.plan?.(t.id)&&await s.read(t).catch(a=>s.log?.(`[requests] ${t.id}: reading its deliverables failed: ${a?.message??a}`));let i=Jt(e,t.id,n,r,o,s);return i.outcome==="blocked"&&zt(e,t.id,i.missing,o,s),i}function Kt(e,t,n){return[`[agentx:request-proof id=${e.id}]`,"The check of this request is met, but the owner asked for several things and it does not close until each has its own proof link.","No link yet for:",...t.map(r=>`- ${r}`),"",n?'Report each of these plan steps done with agentx_request {action: "step", step: <n>, status: "done", evidence: "<link>"}.':`Give one link per item with agentx_request {action: "step", id: "${e.id}", proofs: [{deliverable: <number or name>, link: "<url>"}]}. A note or comment link that shows the item done is a proof; the issue itself is not.`].join(`
33
+ `)}function zt(e,t,n,r,o){let s=e.get(t);if(!s||s.proofAskedAt!=null||!o.tell||o.askBudget&&o.askBudget.left<=0)return;if(o.hasAgent&&!o.hasAgent(s.agentId)){e.markProofAsked(t,r),e.needsAttention(t,`Its check is met, but it has ${je(n)}, and ${s.agentId} is not on this node to give them`,r);return}o.askBudget&&o.askBudget.left--,e.markProofAsked(t,r);let i=!!o.plan?.(t);o.tell(s.agentId,Kt(s,n,i),s).catch(a=>{e.markProofAsked(t,null),o.log?.(`[requests] ${t}: could not ask ${s.agentId} for proof links: ${a?.message??a}`)})}function Ur(e){return!e||e.names.length<=1&&!e.proofs.length?[]:["","Proof per deliverable (one link or more each, given by the assistant):",...e.names.map((n,r)=>{let o=e.proofs.filter(s=>He(s,r,n)).map(s=>s.link);return`${r+1}. ${n}: ${o.length?o.join(" "):"(no link)"}`})]}var zr=["owner","agent","person"],Vt=36e5,Qt=e=>ae.includes(e.state);function Xe(e){return t=>!e||e.get(t)?.state!=="active"?null:e.steps(t).find(n=>n.state==="active")?.agentId??null}function Y(e,t){return e.state==="waiting_owner"?{group:"owner",who:$}:e.promise&&e.owedTo&&e.owedTo!==$&&!t.isAgent(e.owedTo)?{group:"person",who:e.owedTo}:e.state==="needs_attention"?{group:"owner",who:$}:{group:"agent",who:t.activeStepAgent?.(e.id)??e.agentId}}function Z(e,t,n){return Qt(e)?e.state==="needs_attention"?e.attentionReason??"needs attention":e.dueAt!==null?n>e.dueAt?`past its due time (${Yt(e.dueAt)})`:null:n-e.updatedAt>t*Vt?`no activity for ${t} h or more`:null:null}function Vr(e,t,n,r){let o={owner:[],agent:[],person:[]};for(let s of e){let i=Z(s,t,n);if(!i)continue;let{group:a,who:l}=Y(s,r);o[a].push({request:s,group:a,who:l,why:i})}return o}function Qr(e,t){return e==="owner"?"you":e==="agent"?`agent ${t}`:`${t} (outside person)`}var Yt=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function Yr(e){if(e==null||e==="")return;let t=typeof e=="number"?e:typeof e=="string"?Date.parse(e.trim()):NaN;return!Number.isFinite(t)||t<=0?"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds":t}function Zr(e){return t=>oe(t,e())}var Zt=10;async function eo(e,t,n){let r=n.proof??Be,o=e.dueForCheck(n.now-n.everyMinutes*6e4,Zt),s=0;return await Promise.all(o.map(async i=>{e.markChecked(i.id,i.verifyState,i.verifyDetail??"",n.now);let a=await t(i.closeWhen,i).catch(l=>({verdict:"unverifiable",detail:String(l?.message??l)}));if(a.verdict==="met"){(await Ue(e,i,a.detail,a.detail,n.now,r)).outcome==="closed"&&(s++,n.log(`[requests] ${i.id} closed by its check: ${a.detail}`));return}e.markChecked(i.id,a.verdict==="unverifiable"?"unverified":i.verifyState==="failed"?"failed":null,a.detail,n.now)})),{checked:o.length,closed:s}}var Ke=200,Ge=4e3,Je="Nothing, just so you know.";function ee(e,t=Ke){let n=e.headline?e.headline.length>t?`${e.headline.slice(0,t-1)}\u2026`:e.headline:w(e.text,t),r=e.state==="needs_attention"?`Hand it back to ${e.agentId}, or drop it.`:e.state==="waiting_owner"?e.need??(e.question?`Answer: ${w(e.question,150)}`:"Your answer."):e.state==="candidate"||e.state==="in_progress"||e.state==="waiting_other"?e.need??Je:Je;return{headline:n,need:r,said:ze(e.text)}}function ze(e){return e.replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm,"").replace(/[*_~`]+/g,"").replace(/\s+/g," ").trim()}function w(e,t=Ke){let n=ze(e);if(n.length<=t)return n;let r=n.slice(0,t),o=Math.max(r.lastIndexOf(". "),r.lastIndexOf("? "),r.lastIndexOf("! "));return o>t/2?r.slice(0,o+1):`${r.slice(0,t-1).trimEnd()}\u2026`}function en(e){return e.promise||e.dueAt!==null||e.closeWhen?{owedTo:e.owedTo,promise:e.promise,dueAt:e.dueAt,check:e.closeWhen?se(e.closeWhen):null,verifyState:e.verifyState,verifyDetail:e.verifyDetail}:null}function io(e,t,n,r){let o=n?.get(e.id),s=r?Z(e,r.staleAfterHours,r.now):null,i=t.lastAnswer(e.id),a=i&&i.text.length>Ge?`${i.text.slice(0,Ge)}
34
+
35
+ \u2026`:i?.text,l=ee(e);return{...e,summary:l.headline,needed:l.need,textHtml:I(e.text),why:e.state==="waiting_owner"?e.question:e.state==="needs_attention"?e.attentionReason:null,ownerNoteHtml:e.ownerNote?I(e.ownerNote):null,lastAnswer:i?{agentId:i.agentId,at:i.at,html:I(a)}:null,loop:en(e),awaitingQa:le(e),stall:r&&s?{...Y(e,{isAgent:r.isAgent,activeStepAgent:Xe(n)}),why:s}:null,plan:o?{state:o.state,steps:n.steps(e.id).map(c=>({idx:c.idx,name:c.name,kind:c.kind,agentId:c.agentId,state:c.state,approval:c.needsApproval?c.approval:null,evidence:c.evidence,note:c.note,nudges:c.nudges,waitUntil:c.state==="active"?c.waitUntil:null}))}:null}}var te=3,ln=30*24*36e5;function Ze(e){return an(e,".agentx","native-mirror.json")}function ne(e){try{let t=JSON.parse(rn(Ze(e),"utf-8"));return{...t,items:t?.items&&typeof t.items=="object"?t.items:{}}}catch{return{items:{}}}}function Qe(e,t){let n=Ze(e);tn(Ve(n))||nn(Ve(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;sn(r,JSON.stringify(t,null,2)+`
36
+ `),on(r,n)}var un=5*6e4;function fo(e,t,n=Date.now()){let r=ne(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=un)?!1:r.items[`card:${t}`]?.state!=="failed"}var re=24*36e5;function et(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function cn(e,t,n,r){let o=Date.parse(e.expires),s=[w(e.ask,k.ask)];return e.choices?.length&&s.push(...e.choices.map((i,a)=>`${a+1}. ${i}`)),e.recommend&&s.push(`Recommended: ${w(e.recommend,k.recommend)}`),s.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,k.title),notes:s.join(`
37
+ `),due:et(r,t,o),priority:Number.isFinite(o)&&o-r<=re?"high":"none"}}function pn(e,t,n,r){let o=[w(e.question||e.text,k.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],s=e.dueAt??void 0;return{key:`request:${e.id}`,title:ee(e,k.title).headline,notes:o.join(`
38
+ `),due:et(r,t,s),priority:s!==void 0&&s-r<=re?"high":"none"}}async function mo(e){let{root:t,settings:n,tasks:r,log:o}=e,s=e.now??Date.now(),i=new Date(s).toISOString(),a={created:0,completed:0,dismissed:0,failed:0},l=ne(t);delete l.lastError;let c=u=>{l.lastError={at:i,message:u}},f=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>s&&f.set(`card:${u.id}`,cn(u,n,e.answerUrl,s));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&f.set(`request:${u.id}`,pn(u,n,e.answerUrl,s))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Qe(t,l),a}let h=!0,S=new Map,tt=async u=>{if(!S.has(u))try{S.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),S.set(u,null),h=!1}return S.get(u)};for(let[u,p]of Object.entries(l.items)){if(p.state!=="open"||!p.id)continue;let d=await tt(p.list);if(d)if(f.has(u))d.has(p.id)||(l.items[u]={...p,state:"dismissed",at:i},a.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(b){o(`[mirror] ${u}: could not complete its task: ${b?.message??b}`),c(String(b?.message??b));continue}l.items[u]={...p,state:"completed",at:i},a.completed++}}let R=null,W="",F=0,N=[];for(let[u,p]of f){let d=l.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=te)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(g){o(`[mirror] could not make list "${n.list}": ${g?.message??g}`),W=String(g?.message??g),c(W),R=!1}let b=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:g}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});l.items[u]={id:g,list:n.list,state:"open",at:i,createdAt:i,failures:0},a.created++}catch(g){let C=String(g?.message??g);u.startsWith("card:")&&F++;let H=b+1;l.items[u]={list:n.list,state:"failed",at:i,failures:H,lastError:C},c(C),a.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${te}): ${C}`),H===te&&N.push({title:p.title,message:C})}}F&&o(`[mirror] ${F} card(s) could not be added to Reminders; the Mac popup shows them instead`);let nt=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(N.length&&!(s-nt<re)){let u=N[0],p=N.length>1?` (and ${N.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),l.failureToldAt=i}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}h&&(l.checkedAt=i,l.cards=n.include.includes("card"));for(let[u,p]of Object.entries(l.items))p.state!=="open"&&!f.has(u)&&s-Date.parse(p.at)>ln&&delete l.items[u];return Qe(t,l),a}var Ye=5*6e4;function go(e,t,n,r,o=Date.now()){let s=ne(e),i=l=>{let c=l?Date.parse(l):NaN;return c>=n&&c<r},a={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[l,c]of Object.entries(s.items))!c.id||!i(c.createdAt)||(l.startsWith("card:")?a.created.cards++:a.created.requests++);for(let l of t){if(!i(l.created_at))continue;a.raised++;let c=s.items[`card:${l.id}`];if(c?.id)continue;let f=Date.parse(l.created_at);if((l.status==="pending"?NaN:Date.parse(l.decided_at??""))-f<=Ye){a.closedFast++;continue}if(l.status==="pending"&&o-f<=Ye){a.tooNew++;continue}let S=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";a.missed.push({id:l.id,title:l.title,reason:S})}return a}function ho(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Hr as a,Br as b,jt as c,jr as d,Be as e,Jt as f,Ue as g,Ur as h,zr as i,Xe as j,Y as k,Z as l,Vr as m,Qr as n,Yt as o,Yr as p,Zr as q,eo as r,ee as s,w as t,en as u,io as v,E as w,de as x,at as y,fn as z,bn as A,kn as B,xn as C,vn as D,An as E,Nn as F,Pn as G,Rn as H,ge as I,Cn as J,$n as K,In as L,En as M,yt as N,P as O,ke as P,Q,Me as R,Dr as S,Mr as T,_r as U,ne as V,fo as W,mo as X,go as Y,ho as Z};
39
+ //# sourceMappingURL=chunk-U4AUJ6XI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/desktop/install.ts","../src/computer-use/helper.ts","../src/native/macos/index.ts","../src/native/macos/run.ts","../src/native/macos/banner.ts","../src/native/macos/idle.ts","../src/native/macos/notes.ts","../src/native/macos/sound.ts","../src/native/macos/speech.ts","../src/native/macos/tasks.ts","../src/native/none.ts","../src/native/windows/index.ts","../src/native/windows/powershell.ts","../src/native/windows/banner.ts","../src/native/windows/idle.ts","../src/native/windows/sound.ts","../src/native/index.ts","../src/notify/local.ts","../src/approvals/mirror.ts","../src/requests/card-view.ts","../src/requests/loops.ts","../src/requests/close-proof.ts"],"sourcesContent":["import { accessSync, closeSync, constants, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { homedir } from 'node:os'\nimport { installedMacHelper, resolveDesktopHelper } from '@/computer-use/helper'\n\nexport const DESKTOP_LABEL = 'tn.acme.agentx.voice'\nexport const DESKTOP_APP = 'AgentX Desktop.app'\nexport const HELPER_APP = 'AgentX Helper.app'\nexport function desktopPlatformError(platform: string, arch: string, release: string): string | null {\n if (platform !== 'darwin' || arch !== 'arm64' || Number(release.split('.')[0]) < 23)\n return 'AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.'\n return null\n}\nexport function selectDesktopAgent(agents: Record<string, unknown>, requested?: string): string {\n if (requested && !Object.hasOwn(agents, requested)) throw new Error(`Unknown agent: ${requested}. Run agentx agent list.`)\n const id = requested || Object.keys(agents)[0]\n if (!id) throw new Error('No agents configured. Run agentx setup first.')\n return id\n}\nexport function shellQuote(value: string): string { return `'${value.replace(/'/g, \"'\\\\''\")}'` }\n/** launchd's default PATH, which is all a login item gets unless the plist sets one. */\nexport const LAUNCHD_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'\n/** PATH for the login item: AGENTX_VOICE_PATH when set, else the folder of\n * the ffmpeg found at install time (mlx_whisper needs it) ahead of launchd's default. */\nexport function desktopPath(ffmpeg: string | null, override?: string): string {\n if (override) return override\n return [...new Set([...(ffmpeg ? [dirname(ffmpeg)] : []), ...LAUNCHD_PATH.split(':')])].join(':')\n}\nfunction unxml(s: string): string {\n const ents: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" }\n return s.replace(/&(amp|lt|gt|quot|apos);/g, (_, e) => ents[e])\n}\n/** The PATH a login item plist sets, or launchd's default when it sets none. */\nexport function plistPathEnv(plist: string): string {\n const m = plist.match(/<key>PATH<\\/key>\\s*<string>([^<]*)<\\/string>/)\n return m ? unxml(m[1]) : LAUNCHD_PATH\n}\n/** Login item files the voice app may have been installed under. */\nexport const isVoiceLoginItemFile = (name: string) => /agentx\\.voice.*\\.plist$/.test(name)\nexport type LoginItem = { file: string; label: string }\n/** One login item per Mac. The label was renamed once and\n * apps/mac-voice/install.sh writes its own, so adopt the first existing\n * `*agentx.voice*` item that runs the voice app (any bundle name) and\n * retire the others; with none, use DESKTOP_LABEL. Plists are XML text. */\nexport function adoptLoginItem(dir: string, items: { file: string; plist: string }[]): { keep: LoginItem; remove: LoginItem[] } {\n let keep: LoginItem | null = null\n const remove: LoginItem[] = []\n for (const { file, plist } of [...items].sort((a, b) => (a.file < b.file ? -1 : 1))) {\n const label = plist.match(/<key>Label<\\/key>\\s*<string>([^<]*)<\\/string>/)?.[1]\n const program = plist.match(/<key>ProgramArguments<\\/key>\\s*<array>\\s*<string>([^<]*)<\\/string>/)?.[1]\n if (!label || !program || !unxml(program).endsWith('/Contents/MacOS/AgentXVoice')) continue\n if (keep) remove.push({ file, label: unxml(label) })\n else keep = { file, label: unxml(label) }\n }\n return { keep: keep ?? { file: join(dir, `${DESKTOP_LABEL}.plist`), label: DESKTOP_LABEL }, remove }\n}\n/** The file that a process with this PATH would run, or null. */\nexport function findOnPath(bin: string, path: string, isExecutable: (file: string) => boolean): string | null {\n for (const dir of path.split(':')) if (dir && isExecutable(join(dir, bin))) return join(dir, bin)\n return null\n}\n/** True for an executable file that is not a `#!` script. A wrapper script\n * named ffmpeg can sit ahead of the real one on a shell's PATH; its folder\n * would then shadow every other tool for the login item. */\nexport function isNativeExecutable(file: string): boolean {\n try {\n accessSync(file, constants.X_OK)\n if (!statSync(file).isFile()) return false\n const fd = openSync(file, 'r')\n const head = Buffer.alloc(2)\n try { readSync(fd, head, 0, 2, 0) } finally { closeSync(fd) }\n return head.toString('latin1') !== '#!'\n } catch { return false }\n}\n/** Without `agent` the app talks to the agent picked in its menu-bar\n * icon; with it, that agent is pinned and the menu cannot switch. */\nexport function desktopPlist(opts: { label?: string; executable: string; cwd: string; agent?: string; url: string; helper: string; cli: string; node: string; log: string; path: string }): string {\n const xml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;')\n const env = {\n PATH: opts.path,\n ...(opts.agent ? { AGENTX_VOICE_AGENT: opts.agent } : {}),\n AGENTX_DAEMON_URL: opts.url,\n AGENTX_MAC_HELPER: opts.helper,\n AGENTX_PASTE_COMMAND: `cd ${shellQuote(opts.cwd)} && ${shellQuote(opts.node)} ${shellQuote(opts.cli)} paste`,\n }\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${xml(opts.label ?? DESKTOP_LABEL)}</string>\n<key>ProgramArguments</key><array><string>${xml(opts.executable)}</string></array>\n<key>WorkingDirectory</key><string>${xml(opts.cwd)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k,v]) => `<key>${k}</key><string>${xml(v)}</string>`).join('')}</dict>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Interactive</string>\n<key>StandardErrorPath</key><string>${xml(opts.log)}</string>\n</dict></plist>\\n`\n}\n/** build.sh arguments for the helper: the banner icon from\n * notifications.local.icon, or none for the bundled AgentX logo. */\nexport function helperBuildArgs(icon?: string): string[] {\n return icon ? ['--icon', icon] : []\n}\nexport const installedHelper = installedMacHelper\n/** The AgentX package folder, found by walking up from this file (dist/\n * when installed, src/ in a checkout) — never from the caller's cwd, so\n * `agentx notify` finds a repo-built helper from any folder. */\nexport function packageRoot(from = dirname(fileURLToPath(import.meta.url))): string | null {\n for (let dir = from; ; dir = dirname(dir)) {\n try {\n if (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name === 'agentix-cli') return dir\n } catch { /* no package.json here — keep walking up */ }\n if (dirname(dir) === dir) return null\n }\n}\n/** The helper to run: an explicit path, else the one `agentx desktop\n * install` put in ~/Applications, else one built in the package. */\nexport function resolveHelper(root: string | null, home: string, override?: string): string {\n if (override) return override\n const installed = installedHelper(home)\n if (existsSync(installed) || !root) return installed\n return join(root, 'apps/mac-helper/build', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n/** The desktop helper for this OS when one is built or installed, else\n * null. AGENTX_DESKTOP_HELPER (or, on a Mac, AGENTX_MAC_HELPER) points at\n * a helper somewhere else. */\nexport function findHelper(): string | null {\n const path = resolveDesktopHelper({ platform: process.platform, root: packageRoot(), home: homedir(), env: process.env, exists: existsSync })\n return path && existsSync(path) ? path : null\n}\n","import { join, win32 } from \"path\"\n\n// --- Which desktop helper this machine runs (#1594) ---\n//\n// Computer use talks to one native CLI by subcommand, JSON on stdout (the\n// verbs are listed in ./contract.ts). macOS has the Swift helper in\n// apps/mac-helper. Windows gets its own binary that answers the same verbs,\n// so point, teach and act stay the same code on both. This file only picks\n// the binary; it never runs it.\n\nexport type HelperOs = \"macos\" | \"windows\"\n\n/** The helper family for this platform, or null where AgentX has none yet. */\nexport function helperOs(platform: NodeJS.Platform): HelperOs | null {\n if (platform === \"darwin\") return \"macos\"\n if (platform === \"win32\") return \"windows\"\n return null\n}\n\n/** Where the Windows helper is installed for one user. */\nexport const WINDOWS_HELPER_EXE = \"agentx-helper.exe\"\nexport function installedWindowsHelper(localAppData: string): string {\n return win32.join(localAppData, \"Programs\", \"AgentX\", WINDOWS_HELPER_EXE)\n}\n\nexport const MAC_HELPER_APP = \"AgentX Helper.app\"\nexport function installedMacHelper(home: string): string {\n return join(home, \"Applications\", MAC_HELPER_APP, \"Contents/MacOS/agentx-mac-helper\")\n}\n\n/** An explicit helper path from the environment. AGENTX_DESKTOP_HELPER\n * works on every OS; AGENTX_MAC_HELPER is the older name, still read on\n * a Mac so existing login items keep working. */\nexport function helperOverride(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string | undefined {\n const any = env.AGENTX_DESKTOP_HELPER?.trim()\n if (any) return any\n const mac = env.AGENTX_MAC_HELPER?.trim()\n return mac && helperOs(platform) === \"macos\" ? mac : undefined\n}\n\nexport interface HelperLookup {\n platform: NodeJS.Platform\n /** The AgentX package folder, or null when it can't be found. */\n root: string | null\n home: string\n env: NodeJS.ProcessEnv\n exists: (path: string) => boolean\n}\n\n/** The helper to run: an explicit path, else the installed one, else one\n * built inside the package. On a platform without a helper the answer is\n * null, and callers say so with helperMissingMessage. */\nexport function resolveDesktopHelper(l: HelperLookup): string | null {\n const override = helperOverride(l.platform, l.env)\n if (override) return override\n const os = helperOs(l.platform)\n if (os === \"macos\") {\n const installed = installedMacHelper(l.home)\n if (l.exists(installed) || !l.root) return installed\n return join(l.root, \"apps/mac-helper/build\", MAC_HELPER_APP, \"Contents/MacOS/agentx-mac-helper\")\n }\n if (os === \"windows\") {\n const localAppData = l.env.LOCALAPPDATA || win32.join(l.home, \"AppData\", \"Local\")\n const installed = installedWindowsHelper(localAppData)\n if (l.exists(installed) || !l.root) return installed\n return win32.join(l.root, \"apps\", \"win-helper\", \"build\", WINDOWS_HELPER_EXE)\n }\n return null\n}\n\n/** How to put the helper in place, as one instruction. */\nexport function helperInstallHint(platform: NodeJS.Platform): string {\n const os = helperOs(platform)\n if (os === \"macos\") return \"Run agentx desktop install (or build it with apps/mac-helper/build.sh).\"\n if (os === \"windows\") return `Put ${WINDOWS_HELPER_EXE} in %LOCALAPPDATA%\\\\Programs\\\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`\n return \"AgentX has no desktop helper for this system yet.\"\n}\n\n/** What to tell someone whose helper is not there, in plain words. */\nexport function helperMissingMessage(platform: NodeJS.Platform): string {\n const os = helperOs(platform)\n if (os === \"macos\") return \"helper not built — run apps/mac-helper/build.sh (or agentx desktop install)\"\n if (os === \"windows\") {\n const hint = helperInstallHint(platform)\n return `Windows helper not found — ${hint[0].toLowerCase()}${hint.slice(1, -1)}`\n }\n return `computer use (point, teach, act) is not available on ${platform} yet — macOS now, Windows in progress (#1594)`\n}\n","import { accessSync, constants } from \"fs\"\nimport { findOnPath } from \"@/desktop/install\"\nimport { readSystemFocus } from \"@/notify/focus\"\nimport type { NativeAdapter, NativeFocus } from \"../types\"\nimport { macosBanner } from \"./banner\"\nimport { macosIdle } from \"./idle\"\nimport { macosNotes } from \"./notes\"\nimport type { Capture, Output, Run } from \"./run\"\nimport { macosSound } from \"./sound\"\nimport { macosSpeech } from \"./speech\"\nimport { macosTasks } from \"./tasks\"\n\n/** Programs the adapter runs, so tests can stand in for them. */\nexport interface MacosIo {\n run?: Run\n capture?: Capture\n output?: Output\n /** The AgentX Helper binary; null means none. Unset: looked up on use. */\n helper?: string | null\n /** Is this file an executable? Used to find remindctl. */\n isExecutable?: (file: string) => boolean\n}\n\nconst executable = (file: string): boolean => {\n try { accessSync(file, constants.X_OK); return true } catch { return false }\n}\n\n/** System Focus from the private Focus database (notify/focus.ts). That\n * reader answers \"not in Focus\" when it can't read the file, so here\n * anything but a clean answer is null: the OS could not tell. */\nconst focus: NativeFocus = {\n async active() {\n const s = readSystemFocus()\n if (s.active) return true\n return s.reason === \"no active Focus assertion\" ? false : null\n },\n}\n\nexport function macosAdapter(cfg: { reminders?: { command?: string } } = {}, io: MacosIo = {}): NativeAdapter {\n const command = cfg.reminders?.command || \"remindctl\"\n return {\n os: \"macos\",\n tasks: macosTasks(command, io.output),\n notes: macosNotes(io.output),\n banner: macosBanner(io),\n sound: macosSound(io),\n focus,\n speech: macosSpeech(io),\n idle: macosIdle(io),\n async describe() {\n const problems: string[] = []\n const isExec = io.isExecutable ?? executable\n const found = command.includes(\"/\") ? isExec(command) : !!findOnPath(command, process.env.PATH || \"\", isExec)\n if (!found) problems.push(`Reminders: ${command} not found (brew install steipete/tap/remindctl, or set reminders.command).`)\n return { os: \"macos\", tasks: true, notes: true, banner: true, sound: true, focus: true, problems }\n },\n }\n}\n","import { execFile } from \"child_process\"\n\n/** Runs a program; resolves true when it exited 0. Never rejects. */\nexport type Run = (file: string, args: string[]) => Promise<boolean>\n\n/** Runs a program; resolves its stdout, or rejects with its stderr. */\nexport type Output = (file: string, args: string[]) => Promise<string>\n\n/** Runs a program; resolves its stdout, or null when it failed. */\nexport type Capture = (file: string, args: string[]) => Promise<string | null>\n\n/** A banner or a sound may not hold a caller hostage: afplay on a long\n * custom sound, or osascript stuck on a permission prompt, is cut off. */\nconst STEP_TIMEOUT_MS = 5_000\n\nexport const run: Run = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err) => done(!err))\n } catch {\n done(false) // the program is not on this machine: not worth reporting\n }\n })\n\nexport const capture: Capture = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err, stdout) => done(err ? null : String(stdout)))\n } catch {\n done(null)\n }\n })\n\nexport const output: Output = (file, args) =>\n new Promise((resolve, reject) => {\n execFile(file, args, { timeout: 30_000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {\n if (err) reject(new Error(`${file} ${args[0]}: ${(stderr || err.message).trim()}`))\n else resolve(stdout)\n })\n })\n","import { findHelper } from \"@/desktop/install\"\nimport type { BannerStatus, NativeBanner } from \"../types\"\nimport { capture as defaultCapture, run as defaultRun, type Capture, type Run } from \"./run\"\n\n// The banner is posted by the AgentX Helper app when it is installed, so it\n// carries the helper's icon (the AgentX logo by default). Without the\n// helper, or before macOS has allowed it to notify, osascript posts it, and\n// macOS shows it as coming from Script Editor.\n\nexport interface BannerIo {\n run?: Run\n capture?: Capture\n /** The helper binary; null means none. Unset: looked up on each use. */\n helper?: string | null\n}\n\nconst helperOf = (io: BannerIo): string | null => (io.helper === undefined ? findHelper() : io.helper)\n\n/** What the helper reports about its notification permission. Never shows\n * the macOS \"allow notifications\" prompt and never posts a banner. */\nexport async function helperBannerStatus(path: string | null, capture: Capture = defaultCapture): Promise<BannerStatus> {\n if (!path) return \"missing\"\n const out = await capture(path, [\"notify-status\"])\n let status: { authorization?: string; alertStyle?: string } | null = null\n try { status = out ? JSON.parse(out) : null } catch { status = null }\n if (!status) return \"outdated\"\n if (status.authorization === \"notDetermined\") return \"not-asked\"\n if (status.authorization === \"denied\") return \"not-allowed\"\n if (status.alertStyle === \"none\") return \"hidden\"\n return \"ready\"\n}\n\nexport function macosBanner(io: BannerIo = {}): NativeBanner {\n const exec = io.run ?? defaultRun\n return {\n async post({ title, message }) {\n const helper = helperOf(io)\n // A non-zero exit is usually \"not allowed to notify yet\" (the first\n // banner asks), so this one goes through osascript instead.\n if (helper && await exec(helper, [\"notify\", \"--title\", title, \"--message\", message])) return \"posted\"\n // Title and message travel as argv, never spliced into the script,\n // so a quote in either cannot turn into AppleScript.\n const ok = await exec(\"/usr/bin/osascript\", [\n \"-e\", \"on run argv\",\n \"-e\", \"display notification (item 2 of argv) with title (item 1 of argv)\",\n \"-e\", \"end run\",\n title, message,\n ])\n return ok ? \"posted\" : \"failed\"\n },\n status: () => helperBannerStatus(helperOf(io), io.capture),\n }\n}\n","import type { NativeIdle } from \"../types\"\nimport { capture as defaultCapture, type Capture } from \"./run\"\n\n// --- How long since the person touched this Mac (#1138 step B) ---\n//\n// The HID system keeps the time since the last keyboard, mouse or trackpad\n// input, in nanoseconds. ioreg prints it without any permission prompt.\n\n/** Seconds idle from `ioreg -c IOHIDSystem -d 4` output, or null. */\nexport function idleSecondsIn(ioreg: string): number | null {\n const m = ioreg.match(/\"HIDIdleTime\"\\s*=\\s*(\\d+)/)\n return m ? Math.floor(Number(m[1]) / 1e9) : null\n}\n\nexport function macosIdle(io: { capture?: Capture } = {}): NativeIdle {\n const capture = io.capture ?? defaultCapture\n return {\n async seconds() {\n const out = await capture(\"/usr/sbin/ioreg\", [\"-c\", \"IOHIDSystem\", \"-d\", \"4\"])\n return out ? idleSecondsIn(out) : null\n },\n }\n}\n","import type { NativeNotes } from \"../types\"\nimport { output as defaultOutput, type Output } from \"./run\"\n\n// Apple Notes through JXA (osascript -l JavaScript). The folder, title\n// and body travel as argv and are read by the script, never spliced into\n// it, so nothing in them can run as code. Notes stores a body as HTML:\n// the script escapes the text and keeps its line breaks. The first call\n// from the daemon's process asks for the macOS Automation permission\n// (System Settings › Privacy & Security › Automation › Notes).\n\nexport const NOTES_SCRIPT = `\nfunction run(argv) {\n var folderName = argv[0], title = argv[1], body = argv[2]\n var Notes = Application(\"Notes\")\n var esc = function (s) { return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\") }\n var folder = Notes.folders.whose({ name: folderName })()[0]\n if (!folder) {\n folder = Notes.Folder({ name: folderName })\n Notes.folders.push(folder)\n folder = Notes.folders.whose({ name: folderName })()[0]\n }\n var lines = body.split(\"\\\\n\").map(function (l) { return \"<div>\" + (l ? esc(l) : \"<br>\") + \"</div>\" })\n // Notes takes the title from the first line: a name as well would show it twice.\n var note = Notes.Note({ body: \"<div><h1>\" + esc(title) + \"</h1></div>\" + lines.join(\"\") })\n folder.notes.push(note)\n return note.id()\n}\n`\n\nexport function macosNotes(exec: Output = defaultOutput): NativeNotes {\n return {\n async add({ folder, title, body }) {\n const raw = await exec(\"/usr/bin/osascript\", [\"-l\", \"JavaScript\", \"-e\", NOTES_SCRIPT, folder, title, body])\n const id = raw.trim()\n if (!id) throw new Error(\"Notes did not return the new note's id\")\n return { id }\n },\n }\n}\n","import { existsSync, readdirSync } from \"fs\"\nimport type { NativeSound } from \"../types\"\nimport { run as defaultRun, type Run } from \"./run\"\n\nconst SOUNDS = \"/System/Library/Sounds\"\n\n/** The system sound file for a name, or null when there is none. Names\n * only: a path in the config must not reach afplay. */\nexport function soundPath(name: string): string | null {\n if (!/^[\\w -]+$/.test(name)) return null\n const path = `${SOUNDS}/${name}.aiff`\n return existsSync(path) ? path : null\n}\n\nexport function macosSound(io: { run?: Run } = {}): NativeSound {\n const exec = io.run ?? defaultRun\n return {\n async play(name, volume) {\n const path = soundPath(name)\n if (!path) return\n await exec(\"/usr/bin/afplay\", [\"-v\", String(Math.min(1, Math.max(0, volume))), path])\n },\n has: (name) => soundPath(name) !== null,\n async names() {\n try {\n return readdirSync(SOUNDS).filter((f) => f.endsWith(\".aiff\")).map((f) => f.slice(0, -5)).sort()\n } catch {\n return []\n }\n },\n }\n}\n","import type { NativeSpeech } from \"../types\"\nimport { capture as defaultCapture, type Capture } from \"./run\"\n\n// --- Is something else speaking on this Mac? (#1126) ---\n//\n// A script that narrates with `say`, or plays a recording with `afplay`,\n// talks to the person at this Mac without going through AgentX's speaking\n// queue. Before AgentX speaks or chimes, it looks at the process list:\n// one such program running, not started by AgentX itself, means wait.\n\n/** Programs that speak or play sound, and how the owner would say it. */\nconst SPEAKERS: Record<string, string> = { say: \"a spoken line (say)\", afplay: \"a sound playing (afplay)\" }\n\n/** \"pid ppid command\" lines from ps, the speakers among them. */\nexport function speakersIn(ps: string, exceptParents: number[], self = process.pid): string | null {\n for (const line of ps.split(\"\\n\")) {\n const m = line.trim().match(/^(\\d+)\\s+(\\d+)\\s+(\\S+)/)\n if (!m) continue\n const [pid, ppid, comm] = [Number(m[1]), Number(m[2]), m[3]]\n const name = comm.slice(comm.lastIndexOf(\"/\") + 1)\n if (!(name in SPEAKERS) || pid === self || exceptParents.includes(ppid)) continue\n return SPEAKERS[name]\n }\n return null\n}\n\nexport function macosSpeech(io: { capture?: Capture } = {}): NativeSpeech {\n const capture = io.capture ?? defaultCapture\n return {\n async othersSpeaking(opts = {}) {\n const ps = await capture(\"/bin/ps\", [\"-axo\", \"pid=,ppid=,comm=\"])\n return ps ? speakersIn(ps, opts.exceptParents ?? []) : null\n },\n }\n}\n","import type { NativeTask, NativeTasks } from \"../types\"\nimport { output as defaultOutput, type Output } from \"./run\"\n\n// Apple Reminders through remindctl (Homebrew). It is the same tool the\n// mac-pim skill uses, so the daemon and the skill see the same lists. The\n// first call from the daemon's process triggers the macOS Reminders\n// permission prompt.\n//\n// Every value travels as its own argv entry, never through a shell, so\n// quotes and newlines arrive as typed. remindctl 0.1.1 reads any value\n// that starts with \"-\" as an option (and a value equal to --help or\n// --version runs that), and has no \"--opt=value\" form, so such a value\n// gets an invisible zero-width space in front. Reminders keeps that\n// character; listOpen takes it off again. A list name is a lookup key and\n// cannot carry it, so a list name that starts with \"-\" is refused.\n//\n// Reminders keeps a due time to the minute, in this Mac's time zone:\n// seconds are dropped.\n\nconst ZWSP = \"\\u200b\"\n\n/** A value remindctl takes literally. */\nexport function argValue(v: string): string {\n return v.startsWith(\"-\") ? ZWSP + v : v\n}\n\nconst unArg = (v: string | undefined): string | undefined => (v?.startsWith(ZWSP + \"-\") ? v.slice(1) : v)\n\nfunction listName(list: string): string {\n if (!list.trim() || list.startsWith(\"-\")) throw new Error(`Reminders list name \"${list}\" is not usable: it must not be empty or start with \"-\"`)\n return list\n}\n\n/** ISO to the minute, which is all Reminders keeps. */\nconst isoDue = (d: Date): string => new Date(Math.floor(d.getTime() / 60_000) * 60_000).toISOString().replace(/\\.\\d{3}Z$/, \"Z\")\n\nexport function macosTasks(command = \"remindctl\", exec: Output = defaultOutput): NativeTasks {\n return {\n async ensureList(list) {\n const raw = await exec(command, [\"list\", \"--json\", \"--no-input\"])\n const lists = JSON.parse(raw.trim() || \"[]\")\n if (!Array.isArray(lists)) throw new Error(`${command} list: expected a JSON array`)\n if (lists.some((l: { title?: string }) => l?.title === list)) return\n await exec(command, [\"list\", listName(list), \"--create\", \"--json\", \"--no-input\"])\n },\n async listOpen(list) {\n const raw = await exec(command, [\"show\", \"all\", \"--list\", listName(list), \"--json\", \"--no-input\"])\n const items = JSON.parse(raw.trim() || \"[]\")\n if (!Array.isArray(items)) throw new Error(`${command} show: expected a JSON array`)\n return items\n .filter((r: NativeTask) => r && typeof r.id === \"string\" && !r.isCompleted)\n .map((r: NativeTask) => ({ ...r, title: unArg(r.title) ?? \"\", ...(r.notes !== undefined ? { notes: unArg(r.notes) } : {}) }))\n },\n async add({ list, title, notes, due, priority }) {\n const args = [\"add\", \"--title\", argValue(title), \"--list\", listName(list), \"--notes\", argValue(notes)]\n if (due) args.push(\"--due\", isoDue(due))\n if (priority && priority !== \"none\") args.push(\"--priority\", priority)\n const raw = await exec(command, [...args, \"--json\", \"--no-input\"])\n let id: unknown\n try { id = JSON.parse(raw.trim())?.id } catch { id = undefined }\n if (typeof id !== \"string\" || !id) throw new Error(`${command} add: no reminder id in its answer`)\n return { id }\n },\n async update(id, patch) {\n const args = [\"edit\", id]\n if (patch.title !== undefined) args.push(\"--title\", argValue(patch.title))\n if (patch.notes !== undefined) args.push(\"--notes\", argValue(patch.notes))\n if (patch.due === null) args.push(\"--clear-due\")\n else if (patch.due) args.push(\"--due\", isoDue(patch.due))\n // remindctl refuses an edit that changes nothing; so does this.\n if (args.length === 2) return\n await exec(command, [...args, \"--json\", \"--no-input\"])\n },\n async complete(id) {\n await exec(command, [\"complete\", id, \"--json\", \"--no-input\"])\n },\n async remove(id) {\n await exec(command, [\"delete\", id, \"--force\", \"--json\", \"--no-input\"])\n },\n }\n}\n","import type { NativeAdapter } from \"./types\"\n\n/** The adapter for a machine AgentX has no OS layer for, or where the owner\n * turned it off. Every capability is absent; describe() says why. */\nexport function noneAdapter(reason: string): NativeAdapter {\n return {\n os: \"none\",\n async describe() {\n return { os: \"none\", tasks: false, notes: false, banner: false, sound: false, focus: false, problems: [reason] }\n },\n }\n}\n","import { existsSync, readdirSync } from \"fs\"\nimport { win32 } from \"path\"\nimport { findHelper } from \"@/desktop/install\"\nimport type { NativeAdapter } from \"../types\"\nimport type { Capture, Run } from \"../macos/run\"\nimport { windowsBanner } from \"./banner\"\nimport { windowsIdle } from \"./idle\"\nimport { windowsSound } from \"./sound\"\n\n// --- Windows (#1594) ---\n//\n// Only what Windows does with nothing installed: toasts, system sounds and\n// idle time. Tasks, notes and Focus have no adapter here yet, so callers see\n// them as absent and keep their own fallbacks; describe() says so.\n\n/** Programs and files the adapter touches, so tests can stand in for them. */\nexport interface WindowsIo {\n run?: Run\n capture?: Capture\n /** The desktop helper binary; null means none. Unset: looked up on use. */\n helper?: string | null\n /** %WINDIR%\\Media; defaults from WINDIR. */\n media?: string\n exists?: (path: string) => boolean\n list?: (dir: string) => string[]\n}\n\nexport function windowsAdapter(_cfg: unknown = {}, io: WindowsIo = {}): NativeAdapter {\n const helper = () => (io.helper === undefined ? findHelper() : io.helper)\n const media = io.media ?? win32.join(process.env.WINDIR || process.env.SystemRoot || \"C:\\\\Windows\", \"Media\")\n const exists = io.exists ?? existsSync\n const list = io.list ?? ((dir: string) => readdirSync(dir))\n return {\n os: \"windows\",\n banner: windowsBanner({ run: io.run, capture: io.capture, helper }),\n sound: windowsSound({ run: io.run, media, exists, list }),\n idle: windowsIdle({ capture: io.capture }),\n async describe() {\n const problems = [\"Tasks, notes and Focus: AgentX has no Windows adapter for these yet.\"]\n if (!helper()) problems.push(\"Banners come from Windows PowerShell until the AgentX Windows helper is installed.\")\n return { os: \"windows\", tasks: false, notes: false, banner: true, sound: true, focus: false, problems }\n },\n }\n}\n","// --- Running a short PowerShell script safely (#1594) ---\n//\n// Windows PowerShell 5.1 ships with every Windows 10 and 11, so the adapter\n// needs nothing installed. Values never travel on a command line that cmd\n// or PowerShell would parse: the script goes as -EncodedCommand (base64\n// UTF-16LE), and every value inside it is a single-quoted literal.\n\nexport const POWERSHELL = \"powershell.exe\"\n\n/** A PowerShell single-quoted string literal. Inside one only a quote is\n * special, and PowerShell treats the curly quotes as quotes too, so each\n * is doubled. Nothing in it is expanded. */\nexport function psString(value: string): string {\n return `'${value.replace(/['‘’‚‛]/g, (q) => q + q)}'`\n}\n\n/** Arguments that run `script` with no profile and no prompt. */\nexport function psArgs(script: string): string[] {\n return [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-EncodedCommand\", Buffer.from(script, \"utf16le\").toString(\"base64\")]\n}\n","import type { NativeBanner } from \"../types\"\nimport { helperBannerStatus } from \"../macos/banner\"\nimport { capture as defaultCapture, run as defaultRun, type Capture, type Run } from \"../macos/run\"\nimport { POWERSHELL, psArgs, psString } from \"./powershell\"\n\n// A Windows toast. The AgentX Windows helper posts it when installed, so it\n// carries the helper's name; without it, PowerShell posts it and Windows\n// shows it as coming from Windows PowerShell. The helper answers the same\n// `notify` / `notify-status` verbs as the macOS one (computer-use/contract.ts).\n\n/** Windows PowerShell's own app id, which may post toasts with no setup. */\nexport const POWERSHELL_APP_ID = \"{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\"\n\n/** The PowerShell that shows one toast with a title line and a message line. */\nexport function toastScript(title: string, message: string): string {\n return [\n \"$ErrorActionPreference = 'Stop'\",\n \"[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null\",\n \"$t = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)\",\n \"$x = $t.GetElementsByTagName('text')\",\n `$x.Item(0).AppendChild($t.CreateTextNode(${psString(title)})) | Out-Null`,\n `$x.Item(1).AppendChild($t.CreateTextNode(${psString(message)})) | Out-Null`,\n `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${psString(POWERSHELL_APP_ID)}).Show([Windows.UI.Notifications.ToastNotification]::new($t))`,\n ].join(\"\\n\")\n}\n\nexport interface WindowsBannerIo {\n run?: Run\n capture?: Capture\n /** The helper binary; null means none. */\n helper: () => string | null\n}\n\nexport function windowsBanner(io: WindowsBannerIo): NativeBanner {\n const exec = io.run ?? defaultRun\n return {\n async post({ title, message }) {\n const helper = io.helper()\n if (helper && await exec(helper, [\"notify\", \"--title\", title, \"--message\", message])) return \"posted\"\n return (await exec(POWERSHELL, psArgs(toastScript(title, message)))) ? \"posted\" : \"failed\"\n },\n status: () => helperBannerStatus(io.helper(), io.capture ?? defaultCapture),\n }\n}\n","import type { NativeIdle } from \"../types\"\nimport { capture as defaultCapture, type Capture } from \"../macos/run\"\nimport { POWERSHELL, psArgs } from \"./powershell\"\n\n// --- How long since the person touched this PC ---\n//\n// GetLastInputInfo gives the tick of the last keyboard or mouse input for\n// this session, with no permission needed. PowerShell reaches it through a\n// small inline type; the script prints milliseconds idle.\n\nexport const IDLE_SCRIPT = [\n \"Add-Type -TypeDefinition @'\",\n \"using System; using System.Runtime.InteropServices;\",\n \"public static class AgentXIdle {\",\n \" [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }\",\n \" [DllImport(\\\"user32.dll\\\")] static extern bool GetLastInputInfo(ref LASTINPUTINFO p);\",\n \" public static long Ms() { var i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i);\",\n \" if (!GetLastInputInfo(ref i)) return -1; return (long)(uint)(Environment.TickCount - (int)i.dwTime); }\",\n \"}\",\n \"'@\",\n \"[AgentXIdle]::Ms()\",\n].join(\"\\n\")\n\n/** Seconds idle from the script's output, or null. */\nexport function idleSecondsFromMs(out: string): number | null {\n const ms = Number(out.trim())\n return Number.isFinite(ms) && ms >= 0 && out.trim() !== \"\" ? Math.floor(ms / 1000) : null\n}\n\nexport function windowsIdle(io: { capture?: Capture } = {}): NativeIdle {\n const capture = io.capture ?? defaultCapture\n return {\n async seconds() {\n const out = await capture(POWERSHELL, psArgs(IDLE_SCRIPT))\n return out ? idleSecondsFromMs(out) : null\n },\n }\n}\n","import { win32 } from \"path\"\nimport type { NativeSound } from \"../types\"\nimport { run as defaultRun, type Run } from \"../macos/run\"\nimport { POWERSHELL, psArgs, psString } from \"./powershell\"\n\n// Windows keeps its system sounds as .wav files in %WINDIR%\\Media\n// (\"Windows Notify System Generic\", \"chimes\", \"tada\" and so on). PowerShell's\n// SoundPlayer plays one with nothing installed. It has no volume control,\n// so the volume only decides whether the sound plays at all.\n\nexport interface WindowsSoundIo {\n run?: Run\n /** The Media folder; defaults to %WINDIR%\\Media. */\n media: string\n exists: (path: string) => boolean\n list: (dir: string) => string[]\n}\n\n/** The .wav for a sound name, or null. Names only: a path in the config\n * must not reach the player. */\nexport function windowsSoundPath(name: string, io: Pick<WindowsSoundIo, \"media\" | \"exists\">): string | null {\n if (!/^[\\w -]+$/.test(name)) return null\n const path = win32.join(io.media, `${name}.wav`)\n return io.exists(path) ? path : null\n}\n\nexport function windowsSound(io: WindowsSoundIo): NativeSound {\n const exec = io.run ?? defaultRun\n return {\n async play(name, volume) {\n const path = windowsSoundPath(name, io)\n if (!path || !(volume > 0)) return\n await exec(POWERSHELL, psArgs(`(New-Object Media.SoundPlayer ${psString(path)}).PlaySync()`))\n },\n has: (name) => windowsSoundPath(name, io) !== null,\n async names() {\n try {\n return io.list(io.media).filter((f) => /\\.wav$/i.test(f)).map((f) => f.slice(0, -4)).sort()\n } catch {\n return []\n }\n },\n }\n}\n","import { macosAdapter, type MacosIo } from \"./macos\"\nimport { noneAdapter } from \"./none\"\nimport { windowsAdapter, type WindowsIo } from \"./windows\"\nimport type { NativeAdapter } from \"./types\"\n\nexport * from \"./types\"\nexport { noneAdapter } from \"./none\"\n\nexport type NativeAdapterChoice = \"auto\" | \"none\"\n\nexport type NativeConfig = { native?: { adapter?: NativeAdapterChoice }; reminders?: { command?: string } }\n\n/** Programs an adapter runs, so tests can stand in for them. */\nexport type NativeIo = MacosIo & WindowsIo\n\n/** Builds the adapter for one OS. Each OS adapter registers here. */\nexport type NativeAdapterFactory = (cfg: NativeConfig, io: NativeIo) => NativeAdapter\n\nconst FACTORIES: Partial<Record<NodeJS.Platform, NativeAdapterFactory>> = {\n darwin: macosAdapter,\n win32: windowsAdapter,\n}\n\n/** The adapter for this machine. `native.adapter: \"none\"` forces none on\n * any OS; \"auto\" (the default) picks by platform. */\nexport function loadNativeAdapter(\n cfg: NativeConfig = {},\n opts: { platform?: NodeJS.Platform; factories?: Partial<Record<NodeJS.Platform, NativeAdapterFactory>>; io?: NativeIo } = {},\n): NativeAdapter {\n if (cfg.native?.adapter === \"none\") return noneAdapter(\"Turned off: native.adapter is \\\"none\\\".\")\n const platform = opts.platform ?? process.platform\n const make = (opts.factories ?? FACTORIES)[platform]\n return make ? make(cfg, opts.io ?? {}) : noneAdapter(`AgentX has no native adapter for ${platform} yet.`)\n}\n","import { existsSync } from \"fs\"\nimport { homedir } from \"os\"\nimport { isAbsolute } from \"path\"\nimport { loadNativeAdapter, type NativeConfig, type NativeIo, type NativeSpeech } from \"@/native\"\n\nexport { findHelper } from \"@/desktop/install\"\n\n// What happens on THIS machine when a notification is delivered: a banner\n// on screen and a short sound. The push goes to the phone; these are for\n// the person sitting at the computer that raised the event. Both go\n// through the native adapter (src/native); a machine without one skips\n// them.\n//\n// Both are awaited rather than fired and forgotten. A caller that exits\n// straight after notifying — a `launchctl submit` job that removes itself,\n// a cron one-liner — used to take the sound down with it before it\n// played. Waiting costs about a second and makes the step reliable.\n//\n// Never fatal: a notification whose banner failed still arrived, and no\n// caller should have to handle an audio error to say a build finished.\n\nexport interface LocalSettings {\n /** Show a desktop banner (macOS only; other platforms skip it). */\n banner: boolean\n /** Play a sound (macOS only). */\n sound: boolean\n /** A system sound, by name (on a Mac, one of the sounds in System Settings › Sound). */\n soundName: string\n /** 0 (silent) … 1 (full). */\n volume: number\n /** Seconds the sound waits while something else speaks on this machine\n * (#1126). Still speaking after that: no sound, the banner is enough.\n * 0: never wait. */\n quietWaitSeconds?: number\n /** Image for the helper's app icon, which macOS puts on its banners.\n * Unset: the AgentX logo. Applied when `agentx desktop install` builds\n * the helper, since macOS reads the icon from the app, not the banner. */\n icon?: string\n}\n\n/** Glass is the gentlest system sound that is still audible over a\n * keyboard — Basso and Sosumi are alerts, Funk and Frog are jokes, and\n * Ping is the one every other app already uses. */\nexport const DEFAULT_LOCAL: LocalSettings = { banner: true, sound: true, soundName: \"Glass\", volume: 0.4, quietWaitSeconds: 15 }\n\n/** Shows the banner and plays the sound for one delivered notification. */\nexport type LocalAlert = (title: string, message: string) => Promise<void>\n\n/** Fill gaps in a partial `notifications.local` block with the defaults. */\nexport function localSettings(cfg: Partial<LocalSettings> | undefined): LocalSettings {\n return { ...DEFAULT_LOCAL, ...(cfg ?? {}) }\n}\n\nexport function localAlert(\n settings: LocalSettings,\n deps: {\n run?: NativeIo[\"run\"]; capture?: NativeIo[\"capture\"]; platform?: NodeJS.Platform; helper?: string | null; native?: NativeConfig[\"native\"]\n /** For tests: the poll between two looks at who is speaking. */\n pollMs?: number\n } = {},\n): LocalAlert {\n const native = loadNativeAdapter({ native: deps.native }, { platform: deps.platform, io: { run: deps.run, capture: deps.capture, helper: deps.helper } })\n return async (title, message) => {\n const steps: Promise<unknown>[] = []\n if (settings.banner && native.banner) steps.push(native.banner.post({ title, message }))\n if (settings.sound && native.sound) {\n const sound = native.sound\n // A chime over someone speaking is the collision #1126 is about:\n // the banner goes up at once, the sound waits for quiet.\n steps.push(quiet(native.speech, (settings.quietWaitSeconds ?? DEFAULT_LOCAL.quietWaitSeconds!) * 1000, deps.pollMs ?? 500)\n .then((ok) => (ok ? sound.play(settings.soundName, settings.volume) : undefined)))\n }\n await Promise.all(steps)\n }\n}\n\n/** True once nothing else speaks on this machine, false when something\n * still does after `waitMs`. Without a way to tell, true at once. The\n * daemon's own speech counts too (no `exceptParents` here, unlike the\n * speaking queue): a chime over a spoken reply is the same interruption,\n * so it waits, and past the wait the banner shows without the sound. */\nasync function quiet(speech: NativeSpeech | undefined, waitMs: number, pollMs: number): Promise<boolean> {\n if (!speech || waitMs <= 0) return true\n const until = Date.now() + waitMs\n for (;;) {\n if (!(await speech.othersSpeaking())) return true\n if (Date.now() >= until) return false\n await new Promise((r) => setTimeout(r, pollMs))\n }\n}\n\n/**\n * Apply a change to a stored `notifications.local` block, the one rule\n * both the CLI and the dashboard write through. Returns the new block;\n * throws on a value that would not load. Only a machine with a native\n * adapter has sounds to check a name against; elsewhere the setting is\n * inert, so it need only be well-formed.\n */\nexport function patchLocal(\n current: Partial<LocalSettings> | undefined,\n patch: Record<string, unknown>,\n platform: NodeJS.Platform = process.platform,\n): Partial<LocalSettings> {\n const next = { ...(current ?? {}) }\n const native = loadNativeAdapter({}, { platform })\n if (\"banner\" in patch) next.banner = Boolean(patch.banner)\n if (\"sound\" in patch) next.sound = Boolean(patch.sound)\n if (\"soundName\" in patch) {\n const name = String(patch.soundName).trim()\n const ok = native.sound ? native.sound.has(name) : /^[\\w -]+$/.test(name)\n if (!ok) throw new Error(`no system sound named \"${name}\" on this machine`)\n next.soundName = name\n }\n if (\"icon\" in patch) {\n const icon = String(patch.icon ?? \"\").trim().replace(/^~(?=\\/)/, homedir())\n if (!icon) delete next.icon\n else {\n if (!isAbsolute(icon) || !/\\.(png|jpe?g|icns)$/i.test(icon)) throw new Error(\"icon must be the full path to a .png, .jpg or .icns file\")\n if (native.banner && !existsSync(icon)) throw new Error(`no icon file at ${icon}`)\n next.icon = icon\n }\n }\n if (\"volume\" in patch) {\n const v = Number(patch.volume)\n if (!Number.isFinite(v) || v < 0 || v > 1) throw new Error(\"volume must be between 0 and 1\")\n next.volume = v\n }\n return next\n}\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport type { NativePriority, NativeTasks } from \"@/native\"\nimport { cardWords, summarize } from \"@/requests/card-view\"\nimport type { RequestRecord } from \"@/requests/store\"\nimport { CARD_LIMITS, type DecisionCard } from \"./cards\"\n\n// --- The Reminders mirror (#1062 step 5) ---\n//\n// Each pending decision card, and each request waiting on the owner,\n// becomes one task in the OS task app (Apple Reminders on a Mac) with a due\n// time. Calendar shows it, and the system alert comes back when it falls\n// due. Answering stays on the Desk, the Approvals page or the CLI: a task\n// cannot carry choices or a draft.\n//\n// Runs once a minute beside the approvals sweep, on the node that holds the\n// cards (forwarded cards live on the owner's node, so that is where they\n// are mirrored). Off by default.\n//\n// Rules:\n// - one task per card or request, created once;\n// - the card is answered, expires or is closed, or the request stops\n// waiting on the owner: the task is completed;\n// - the owner ticks the task off or deletes it while the item still\n// waits: the item stays on the Desk and is never mirrored again.\n// Ticking a task is not an answer;\n// - three failed adds for one item: the owner is told once and that\n// item is not tried again;\n// - every task ends with `agentx: card=<id>` or `agentx: request=<id>`,\n// which check-ins and the reminders hand-back skip, so a mirrored\n// task never turns back into a card or an agent's job.\n//\n// State lives in its own file, written only by the daemon, not in the card\n// files that the CLI and the dashboard also write.\n\nexport interface MirrorSettings {\n enabled: boolean\n list: string\n dueAfterMinutes: number\n include: (\"card\" | \"request\")[]\n /** Where the owner answers. Unset: the local dashboard's Approvals page. */\n answerUrl?: string\n}\n\nexport type MirrorState = \"open\" | \"completed\" | \"dismissed\" | \"failed\"\n\nexport interface MirrorEntry {\n /** The task's id in the OS task app, once added. */\n id?: string\n list: string\n state: MirrorState\n /** ISO time of the last change. */\n at: string\n /** ISO time its task was added. Unset on entries from before #1062's\n * trial, and on items whose task was never added. */\n createdAt?: string\n failures: number\n lastError?: string\n}\n\nexport interface MirrorFile {\n /** Keyed `card:<id>` or `request:<id>`, the inbox's keys. */\n items: Record<string, MirrorEntry>\n /** ISO time of the last pass that read every list it needed. Stale\n * (the mirror was turned off, or the list can't be read) means the\n * mirror no longer covers anything, and the Mac popup is back. */\n checkedAt?: string\n /** That pass mirrored cards (include has \"card\"). */\n cards?: boolean\n /** ISO time the owner was last told adds are failing: once a day. */\n failureToldAt?: string\n /** The latest pass's last error, for doctor. */\n lastError?: { at: string; message: string }\n}\n\nexport const MAX_ADD_FAILURES = 3\n/** Closed entries are kept this long, then forgotten. */\nconst KEEP_CLOSED_MS = 30 * 24 * 3_600_000\n\nexport function mirrorPath(root: string): string {\n return resolve(root, \".agentx\", \"native-mirror.json\")\n}\n\nexport function readMirror(root: string): MirrorFile {\n try {\n const parsed = JSON.parse(readFileSync(mirrorPath(root), \"utf-8\"))\n return { ...parsed, items: parsed?.items && typeof parsed.items === \"object\" ? parsed.items : {} }\n } catch {\n return { items: {} }\n }\n}\n\nfunction writeMirror(root: string, file: MirrorFile): void {\n const path = mirrorPath(root)\n if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true })\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(file, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\n/** A pass older than this means the mirror is not running. */\nexport const MIRROR_FRESH_MS = 5 * 60_000\n\n/** True when the mirror is running and covers this card: it has a task,\n * or gets one on the next pass, or the owner ticked its task off. The Mac\n * popup then leaves it alone, so the owner is not alerted twice. A card\n * whose task could not be added is not covered. */\nexport function mirrorCovers(root: string, cardId: string, now = Date.now()): boolean {\n const file = readMirror(root)\n const checked = file.checkedAt ? Date.parse(file.checkedAt) : NaN\n if (!file.cards || !(now - checked <= MIRROR_FRESH_MS)) return false\n return file.items[`card:${cardId}`]?.state !== \"failed\"\n}\n\n/** What one task says. */\nexport interface MirrorItem {\n key: string\n title: string\n notes: string\n due: Date\n priority: NativePriority\n}\n\nconst DAY_MS = 24 * 3_600_000\n\nfunction dueFor(now: number, settings: MirrorSettings, limit?: number): Date {\n const due = now + settings.dueAfterMinutes * 60_000\n return new Date(limit !== undefined && Number.isFinite(limit) ? Math.max(now, Math.min(due, limit)) : due)\n}\n\nexport function cardItem(card: DecisionCard, settings: MirrorSettings, answerUrl: string, now: number): MirrorItem {\n const expires = Date.parse(card.expires)\n const lines = [summarize(card.ask, CARD_LIMITS.ask)]\n if (card.choices?.length) lines.push(...card.choices.map((c, i) => `${i + 1}. ${c}`))\n if (card.recommend) lines.push(`Recommended: ${summarize(card.recommend, CARD_LIMITS.recommend)}`)\n lines.push(`Answer: ${answerUrl}`, `agentx: card=${card.id}`)\n return {\n key: `card:${card.id}`,\n title: summarize(card.title, CARD_LIMITS.title),\n notes: lines.join(\"\\n\"),\n due: dueFor(now, settings, expires),\n priority: Number.isFinite(expires) && expires - now <= DAY_MS ? \"high\" : \"none\",\n }\n}\n\nexport function requestItem(r: RequestRecord, settings: MirrorSettings, answerUrl: string, now: number): MirrorItem {\n const lines = [summarize(r.question || r.text, CARD_LIMITS.ask), `Asked of ${r.agentId}.`, `Answer: ${answerUrl}`, `agentx: request=${r.id}`]\n const dueAt = r.dueAt ?? undefined\n return {\n key: `request:${r.id}`,\n title: cardWords(r, CARD_LIMITS.title).headline,\n notes: lines.join(\"\\n\"),\n due: dueFor(now, settings, dueAt),\n priority: dueAt !== undefined && dueAt - now <= DAY_MS ? \"high\" : \"none\",\n }\n}\n\nexport interface MirrorDeps {\n root: string\n settings: MirrorSettings\n tasks: NativeTasks\n /** Pending cards on this node. */\n cards: () => DecisionCard[]\n /** Requests in waiting_owner. */\n requests: () => RequestRecord[]\n answerUrl: string\n /** Tell the owner, through the usual notification. */\n notify: (title: string, message: string) => Promise<void>\n log: (msg: string) => void\n now?: number\n}\n\nexport interface MirrorResult {\n created: number\n completed: number\n dismissed: number\n failed: number\n}\n\n/** One pass of the mirror. Never throws. */\nexport async function runMirror(deps: MirrorDeps): Promise<MirrorResult> {\n const { root, settings, tasks, log } = deps\n const now = deps.now ?? Date.now()\n const at = new Date(now).toISOString()\n const result: MirrorResult = { created: 0, completed: 0, dismissed: 0, failed: 0 }\n const file = readMirror(root)\n // lastError says how the latest pass went: a clean pass clears it.\n delete file.lastError\n const fail = (message: string) => { file.lastError = { at, message } }\n\n const waiting = new Map<string, MirrorItem>()\n try {\n if (settings.include.includes(\"card\")) {\n for (const c of deps.cards()) if (c.status === \"pending\" && Date.parse(c.expires) > now) waiting.set(`card:${c.id}`, cardItem(c, settings, deps.answerUrl, now))\n }\n if (settings.include.includes(\"request\")) {\n for (const r of deps.requests()) if (r.state === \"waiting_owner\") waiting.set(`request:${r.id}`, requestItem(r, settings, deps.answerUrl, now))\n }\n } catch (e: any) {\n log(`[mirror] could not read what is waiting: ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n writeMirror(root, file)\n return result\n }\n\n // Close or notice dismissal for what is already mirrored. The open list\n // is read once per list; when it can't be read, nothing is closed or\n // dismissed this pass, so a hiccup never loses a task.\n let allRead = true\n const openIds = new Map<string, Set<string> | null>()\n const openIn = async (list: string): Promise<Set<string> | null> => {\n if (!openIds.has(list)) {\n try {\n openIds.set(list, new Set((await tasks.listOpen(list)).map((t) => t.id)))\n } catch (e: any) {\n log(`[mirror] could not read list \"${list}\": ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n openIds.set(list, null)\n allRead = false\n }\n }\n return openIds.get(list)!\n }\n\n for (const [key, entry] of Object.entries(file.items)) {\n if (entry.state !== \"open\" || !entry.id) continue\n const open = await openIn(entry.list)\n if (!open) continue\n if (!waiting.has(key)) {\n if (open.has(entry.id)) {\n try {\n await tasks.complete(entry.id)\n } catch (e: any) {\n log(`[mirror] ${key}: could not complete its task: ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n continue\n }\n }\n file.items[key] = { ...entry, state: \"completed\", at }\n result.completed++\n } else if (!open.has(entry.id)) {\n file.items[key] = { ...entry, state: \"dismissed\", at }\n result.dismissed++\n log(`[mirror] ${key}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`)\n }\n }\n\n let listReady: boolean | null = null\n let listError = \"\"\n let cardsMissed = 0\n const gaveUp: { title: string; message: string }[] = []\n for (const [key, item] of waiting) {\n const entry = file.items[key]\n if (entry && (entry.state === \"open\" || entry.state === \"dismissed\")) continue\n if (entry?.state === \"failed\" && entry.failures >= MAX_ADD_FAILURES) continue\n // The list is made on the first add of a pass, when it is missing.\n if (listReady === null) {\n try {\n await tasks.ensureList(settings.list)\n listReady = true\n } catch (e: any) {\n log(`[mirror] could not make list \"${settings.list}\": ${e?.message ?? e}`)\n listError = String(e?.message ?? e)\n fail(listError)\n listReady = false\n }\n }\n const failures = entry?.state === \"failed\" ? entry.failures : 0\n try {\n // No list (access denied, or a permission prompt nobody answers under\n // launchd, which runs into the timeout): every add would fail the\n // same way, one timeout each. Count it as this item's failed add\n // without trying.\n if (listReady === false) throw new Error(listError)\n const { id } = await tasks.add({ list: settings.list, title: item.title, notes: item.notes, due: item.due, priority: item.priority })\n file.items[key] = { id, list: settings.list, state: \"open\", at, createdAt: at, failures: 0 }\n result.created++\n } catch (e: any) {\n const message = String(e?.message ?? e)\n if (key.startsWith(\"card:\")) cardsMissed++\n const n = failures + 1\n file.items[key] = { list: settings.list, state: \"failed\", at, failures: n, lastError: message }\n fail(message)\n result.failed++\n log(`[mirror] ${key}: could not add to Reminders (${n}/${MAX_ADD_FAILURES}): ${message}`)\n if (n === MAX_ADD_FAILURES) gaveUp.push({ title: item.title, message })\n }\n }\n\n // A card without a task is not covered (mirrorCovers): the Mac popup\n // shows it. Said once a pass, so the fallback is in the log.\n if (cardsMissed) log(`[mirror] ${cardsMissed} card(s) could not be added to Reminders; the Mac popup shows them instead`)\n\n // One notification a day at most, however many items gave up: a missing\n // permission fails every card the same way.\n const told = file.failureToldAt ? Date.parse(file.failureToldAt) : NaN\n if (gaveUp.length && !(now - told < DAY_MS)) {\n const first = gaveUp[0]\n const more = gaveUp.length > 1 ? ` (and ${gaveUp.length - 1} more)` : \"\"\n try {\n await deps.notify(\"Could not add to Reminders\", `${first.title}${more}: ${summarize(first.message, 200)}. Still on the Desk.`)\n file.failureToldAt = at\n } catch (err: any) {\n log(`[mirror] could not tell the owner: ${err?.message ?? err}`)\n }\n }\n\n if (allRead) {\n file.checkedAt = at\n file.cards = settings.include.includes(\"card\")\n }\n\n for (const [key, entry] of Object.entries(file.items)) {\n if (entry.state !== \"open\" && !waiting.has(key) && now - Date.parse(entry.at) > KEEP_CLOSED_MS) delete file.items[key]\n }\n writeMirror(root, file)\n return result\n}\n\n// --- The trial count (#1062 step 5) ---\n//\n// One line a day while the mirror is on trial: cards raised, Reminders\n// created, cards missed. A card closed before a pass could reach it (within\n// the grace below of being raised) is counted apart, not as a miss; so is\n// one still that new. Read from the card files and the mirror file, both\n// on this node.\n\n/** A card closed or still pending this soon after it was raised may never\n * have met a pass: it is not a miss. */\nexport const MIRROR_GRACE_MS = 5 * 60_000\n\nexport interface MirrorTally {\n from: string\n to: string\n /** Cards raised in [from, to). */\n raised: number\n /** Tasks added in [from, to), by kind. */\n created: { cards: number; requests: number }\n /** Cards raised in the window that never got a task, with why. */\n missed: { id: string; title: string; reason: string }[]\n /** Raised in the window and closed within the grace, with no task. */\n closedFast: number\n /** Raised within the grace of now, with no task yet. */\n tooNew: number\n}\n\nexport function mirrorTally(root: string, cards: DecisionCard[], from: number, to: number, now = Date.now()): MirrorTally {\n const file = readMirror(root)\n const inWindow = (iso?: string) => {\n const t = iso ? Date.parse(iso) : NaN\n return t >= from && t < to\n }\n const tally: MirrorTally = {\n from: new Date(from).toISOString(), to: new Date(to).toISOString(),\n raised: 0, created: { cards: 0, requests: 0 }, missed: [], closedFast: 0, tooNew: 0,\n }\n for (const [key, entry] of Object.entries(file.items)) {\n if (!entry.id || !inWindow(entry.createdAt)) continue\n if (key.startsWith(\"card:\")) tally.created.cards++\n else tally.created.requests++\n }\n for (const card of cards) {\n if (!inWindow(card.created_at)) continue\n tally.raised++\n const entry = file.items[`card:${card.id}`]\n if (entry?.id) continue\n const raisedAt = Date.parse(card.created_at)\n const closedAt = card.status === \"pending\" ? NaN : Date.parse(card.decided_at ?? \"\")\n if (closedAt - raisedAt <= MIRROR_GRACE_MS) { tally.closedFast++; continue }\n if (card.status === \"pending\" && now - raisedAt <= MIRROR_GRACE_MS) { tally.tooNew++; continue }\n const reason = entry?.state === \"failed\" ? `could not be added (${entry.failures}x): ${entry.lastError ?? \"unknown error\"}` : \"no pass reached it\"\n tally.missed.push({ id: card.id, title: card.title, reason })\n }\n return tally\n}\n\n/** The day's line for the trial issue. */\nexport function tallyLine(t: MirrorTally): string {\n const extra = [t.closedFast ? `closed within 5 min: ${t.closedFast}` : \"\", t.tooNew ? `raised in the last 5 min: ${t.tooNew}` : \"\"].filter(Boolean)\n return `cards raised ${t.raised} / Reminders created ${t.created.cards + t.created.requests} (${t.created.cards} cards, ${t.created.requests} requests) / missed ${t.missed.length}${extra.length ? ` · ${extra.join(\" · \")}` : \"\"}`\n}\n","import { markdownToHtml } from \"@/utils/markdown-html\"\nimport type { RequestRecord, RequestStore } from \"./store\"\nimport type { PlanState, PlanStore, StepState } from \"./plan-store\"\nimport { describeCloseWhen } from \"./checkers\"\nimport { activeStepAgentOf, stalledWhy, waitsOn, type StallGroup } from \"./loops\"\nimport { awaitingQa } from \"./qa\"\n\n// --- One open request as a card the owner can read in seconds (#459) ---\n//\n// The Approvals page shows each open request as a card: a short plain\n// summary, where it stands and why it is not finished, then the words the\n// owner used and the agent's last answer, both rendered. markdownToHtml\n// escapes before it marks up, so nothing an agent or a channel wrote\n// reaches the page as HTML. The summary is the request's headline (#1126);\n// a request without one yet falls back to the start of its own words,\n// without the markdown marks.\n\nexport const SUMMARY_MAX = 200\n/** An answer of pages is cut: the card is for reading quickly. */\nexport const ANSWER_MAX = 4000\n\n/** What a request needs from the owner when nothing does. */\nexport const NOTHING_NEEDED = \"Nothing, just so you know.\"\n\n/** A request as every surface titles it (#1126): what it is, the one\n * thing needed from the owner, and the owner's own words. The need\n * follows where it stands: a request that needs attention or waits on\n * the owner's answer says so, whatever the agent wrote earlier. */\nexport function cardWords(\n r: Pick<RequestRecord, \"text\" | \"headline\" | \"need\" | \"state\" | \"question\" | \"agentId\">,\n max = SUMMARY_MAX,\n): { headline: string; need: string; said: string } {\n const headline = r.headline ? (r.headline.length > max ? `${r.headline.slice(0, max - 1)}…` : r.headline) : summarize(r.text, max)\n const need = r.state === \"needs_attention\" ? `Hand it back to ${r.agentId}, or drop it.`\n : r.state === \"waiting_owner\" ? (r.need ?? (r.question ? `Answer: ${summarize(r.question, 150)}` : \"Your answer.\"))\n : r.state === \"candidate\" || r.state === \"in_progress\" || r.state === \"waiting_other\" ? (r.need ?? NOTHING_NEEDED)\n : NOTHING_NEEDED\n return { headline, need, said: plain(r.text) }\n}\n\nexport interface RequestCard extends RequestRecord {\n summary: string\n /** The one thing needed from the owner, in words: the agent's `need`\n * or what follows from where the request stands (cardWords). */\n needed: string\n /** The request in the owner's words (the transcript, when spoken). */\n textHtml: string\n /** Why it is not finished, or what is being asked. Null: work is under way. */\n why: string | null\n ownerNoteHtml: string | null\n lastAnswer: { agentId: string; at: number; html: string } | null\n /** The open loop (#1039): who it is owed to, when it is due, what\n * closes it. Null on a request with none of it. */\n loop: {\n owedTo: string | null\n promise: boolean\n dueAt: number | null\n /** What its check waits for, in words. */\n check: string | null\n verifyState: string | null\n verifyDetail: string | null\n } | null\n /** Marked as needing QA, with no verdict since (#1188). The verdict\n * itself is `qa`, from the record. */\n awaitingQa: boolean\n /** Stalled, and what it waits on. Null: not stalled, or not asked. */\n stall: { group: StallGroup; who: string; why: string } | null\n /** Its tracked plan (#788), step by step. Null: no plan. */\n plan: {\n state: PlanState\n steps: Array<{ idx: number; name: string; kind: string; agentId: string; state: StepState; approval: string | null; evidence: string | null; note: string | null; nudges: number; waitUntil: number | null }>\n } | null\n}\n\n/** Markdown to the words alone, on one line. */\nexport function plain(md: string): string {\n return md\n .replace(/```[\\s\\S]*?```/g, \" \")\n .replace(/!?\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n .replace(/^\\s{0,3}(#{1,6}|>|[-*+]|\\d+[.)])\\s+/gm, \"\")\n .replace(/[*_~`]+/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n}\n\n/** The start of the request, cut at a sentence when one ends in reach. */\nexport function summarize(md: string, max = SUMMARY_MAX): string {\n const text = plain(md)\n if (text.length <= max) return text\n const cut = text.slice(0, max)\n const end = Math.max(cut.lastIndexOf(\". \"), cut.lastIndexOf(\"? \"), cut.lastIndexOf(\"! \"))\n return end > max / 2 ? cut.slice(0, end + 1) : `${cut.slice(0, max - 1).trimEnd()}…`\n}\n\n/** What the stall view needs: the quiet time, the clock, and which ids are agents. */\nexport interface StallLookup { staleAfterHours: number; now: number; isAgent: (id: string) => boolean }\n\n/** A request's open loop (#1039): who it is owed to, when it is due, what\n * check closes it and what that check last said. Null: none of it. The\n * card and the Hub's post (#1440) both show it. */\nexport function loopOf(r: RequestRecord): RequestCard[\"loop\"] {\n return r.promise || r.dueAt !== null || r.closeWhen ? {\n owedTo: r.owedTo, promise: r.promise, dueAt: r.dueAt, check: r.closeWhen ? describeCloseWhen(r.closeWhen) : null,\n verifyState: r.verifyState, verifyDetail: r.verifyDetail,\n } : null\n}\n\nexport function requestCard(\n r: RequestRecord,\n store: Pick<RequestStore, \"lastAnswer\">,\n plans?: Pick<PlanStore, \"get\" | \"steps\"> | null,\n stall?: StallLookup,\n): RequestCard {\n const plan = plans?.get(r.id)\n const why = stall ? stalledWhy(r, stall.staleAfterHours, stall.now) : null\n const answer = store.lastAnswer(r.id)\n const cutAnswer = answer && answer.text.length > ANSWER_MAX ? `${answer.text.slice(0, ANSWER_MAX)}\\n\\n…` : answer?.text\n const words = cardWords(r)\n return {\n ...r,\n summary: words.headline,\n needed: words.need,\n textHtml: markdownToHtml(r.text),\n why: r.state === \"waiting_owner\" ? r.question : r.state === \"needs_attention\" ? r.attentionReason : null,\n ownerNoteHtml: r.ownerNote ? markdownToHtml(r.ownerNote) : null,\n lastAnswer: answer ? { agentId: answer.agentId, at: answer.at, html: markdownToHtml(cutAnswer!) } : null,\n loop: loopOf(r),\n awaitingQa: awaitingQa(r),\n stall: stall && why ? { ...waitsOn(r, { isAgent: stall.isAgent, activeStepAgent: activeStepAgentOf(plans) }), why } : null,\n plan: plan ? {\n state: plan.state,\n steps: plans!.steps(r.id).map((s) => ({\n idx: s.idx, name: s.name, kind: s.kind, agentId: s.agentId, state: s.state,\n approval: s.needsApproval ? s.approval : null, evidence: s.evidence, note: s.note, nudges: s.nudges,\n waitUntil: s.state === \"active\" ? s.waitUntil : null,\n })),\n } : null,\n }\n}\n","import { OPEN_STATES, OWED_TO_OWNER, type RequestRecord, type RequestStore } from \"./store\"\nimport { runCheck, type CheckContext, type CheckResult, type CloseWhen } from \"./checkers\"\nimport { closeByCheck, PROOF_OFF, type CloseProofCtx } from \"./close-proof\"\n\n// --- Open loops: who each one waits on, and when it is stalled (#1039) ---\n//\n// A loop is an open request: one the owner asked for, or one an agent\n// promised (action promise). It is stalled when it is past its due time,\n// or, without one, when nothing has happened for staleAfterHours. A loop\n// that needs attention is stalled too: nothing is retrying it.\n//\n// Stalled loops are grouped by what they wait on:\n// owner the owner's answer (waiting_owner), or the owner's decision\n// on one that needs attention\n// agent an agent: the one that has it, a plan step's agent, or the\n// agent it is owed to\n// person an outside person: a promise owed to a known person\n// The requests panel, `agentx requests --stalled` and the sweep's notice\n// all use this one grouping.\n\nexport const STALL_GROUPS = [\"owner\", \"agent\", \"person\"] as const\nexport type StallGroup = (typeof STALL_GROUPS)[number]\n\nexport interface StalledLoop {\n request: RequestRecord\n group: StallGroup\n /** Who it waits on: \"owner\", an agent id or a person id. */\n who: string\n /** Why it counts as stalled, in words. */\n why: string\n}\n\nexport interface LoopLookups {\n isAgent: (id: string) => boolean\n /** The agent of the active step of the request's plan, if it has one. */\n activeStepAgent?: (requestId: string) => string | null\n}\n\nconst HOUR = 3_600_000\nconst isOpen = (r: RequestRecord) => (OPEN_STATES as readonly string[]).includes(r.state)\n\n/** The agent of each request's active plan step, from the plan store. */\nexport function activeStepAgentOf(plans: { get(id: string): { state: string } | null; steps(id: string): Array<{ state: string; agentId: string }> } | null | undefined) {\n return (requestId: string): string | null => {\n if (!plans || plans.get(requestId)?.state !== \"active\") return null\n return plans.steps(requestId).find((s) => s.state === \"active\")?.agentId ?? null\n }\n}\n\n/** What an open loop waits on. */\nexport function waitsOn(r: RequestRecord, look: LoopLookups): { group: StallGroup; who: string } {\n if (r.state === \"waiting_owner\") return { group: \"owner\", who: OWED_TO_OWNER }\n if (r.promise && r.owedTo && r.owedTo !== OWED_TO_OWNER && !look.isAgent(r.owedTo)) return { group: \"person\", who: r.owedTo }\n if (r.state === \"needs_attention\") return { group: \"owner\", who: OWED_TO_OWNER }\n const step = look.activeStepAgent?.(r.id)\n return { group: \"agent\", who: step ?? r.agentId }\n}\n\n/** Why an open loop is stalled, or null when it is not. */\nexport function stalledWhy(r: RequestRecord, staleAfterHours: number, now: number): string | null {\n if (!isOpen(r)) return null\n if (r.state === \"needs_attention\") return r.attentionReason ?? \"needs attention\"\n if (r.dueAt !== null) return now > r.dueAt ? `past its due time (${when(r.dueAt)})` : null\n return now - r.updatedAt > staleAfterHours * HOUR ? `no activity for ${staleAfterHours} h or more` : null\n}\n\n/** Stalled loops among `items`, oldest first, grouped. */\nexport function stalledLoops(items: RequestRecord[], staleAfterHours: number, now: number, look: LoopLookups): Record<StallGroup, StalledLoop[]> {\n const out: Record<StallGroup, StalledLoop[]> = { owner: [], agent: [], person: [] }\n for (const r of items) {\n const why = stalledWhy(r, staleAfterHours, now)\n if (!why) continue\n const { group, who } = waitsOn(r, look)\n out[group].push({ request: r, group, who, why })\n }\n return out\n}\n\n/** The group, in words, for people. */\nexport function waitsOnWords(group: StallGroup, who: string): string {\n return group === \"owner\" ? \"you\" : group === \"agent\" ? `agent ${who}` : `${who} (outside person)`\n}\n\nexport const when = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace(\"T\", \" \") + \" UTC\"\n\n/** A due time an agent or the owner gave: epoch ms, or an ISO date.\n * Undefined when absent, a string when it is not a time. */\nexport function parseDue(v: unknown): number | undefined | string {\n if (v === undefined || v === null || v === \"\") return undefined\n const at = typeof v === \"number\" ? v : typeof v === \"string\" ? Date.parse(v.trim()) : NaN\n if (!Number.isFinite(at) || at <= 0) return \"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds\"\n return at\n}\n\n// ── Running the checkers from the requests check ─────────────────────────\n\n/** Runs a loop's checker. The daemon's own; tests give their own. */\nexport type LoopChecker = (spec: CloseWhen, request: RequestRecord) => Promise<CheckResult>\n\nexport function loopChecker(ctx: () => CheckContext): LoopChecker {\n return (spec) => runCheck(spec, ctx())\n}\n\n/** How many checkers run at once, and how many loops one check takes on. */\nconst CHECK_BATCH = 10\n\n/** Run the checker of every open loop whose last check is older than\n * `everyMinutes`. Met closes it as done with the checker's evidence;\n * unverifiable marks it unverified; not met leaves it as it is. */\nexport async function checkLoops(\n store: RequestStore,\n check: LoopChecker,\n opts: { everyMinutes: number; now: number; log: (msg: string) => void; proof?: CloseProofCtx },\n): Promise<{ checked: number; closed: number }> {\n const proof = opts.proof ?? PROOF_OFF\n const due = store.dueForCheck(opts.now - opts.everyMinutes * 60_000, CHECK_BATCH)\n let closed = 0\n await Promise.all(due.map(async (r) => {\n // Marked before the call: a check that hangs is not started again\n // at the next minute.\n store.markChecked(r.id, r.verifyState, r.verifyDetail ?? \"\", opts.now)\n const res = await check(r.closeWhen!, r).catch((e: any): CheckResult => ({ verdict: \"unverifiable\", detail: String(e?.message ?? e) }))\n if (res.verdict === \"met\") {\n // Proof per deliverable and reopen once (close-proof.ts, #692).\n if ((await closeByCheck(store, r, res.detail, res.detail, opts.now, proof)).outcome === \"closed\") {\n closed++\n opts.log(`[requests] ${r.id} closed by its check: ${res.detail}`)\n }\n return\n }\n // A refused done stays \"failed\" until the check says otherwise.\n store.markChecked(r.id, res.verdict === \"unverifiable\" ? \"unverified\" : r.verifyState === \"failed\" ? \"failed\" : null, res.detail, opts.now)\n }))\n return { checked: due.length, closed }\n}\n","import type { DeliverableProof, RequestRecord, RequestStore } from \"./store\"\nimport type { PlanStep } from \"./plan-store\"\nimport { parseRef } from \"./checkers/issue\"\n\n// --- Proof per deliverable before a close by check, and reopen once ---\n//\n// A checker (closeWhen) or an issue home can close a request as done on\n// its own. A check on issue state alone says nothing about what the owner\n// asked for. When the owner named several things (\"confirm each stage:\n// build, MR, merge, staging, test, production\"), the request closed with\n// no proof for any of them.\n//\n// Part A, `requests.closeProof.mode` (off | warn | block):\n// - The owner's words (text, plus the latest owner note) are read once\n// by the model into a short list of deliverables (DeliverablesReader).\n// A request with a tracked plan needs no read: its steps are the list,\n// and each step's own evidence link is its proof.\n// - The agent gives one link per deliverable with agentx_request\n// `proofs: [{deliverable, link}]` on step or done, in every mode.\n// - A close by check counts only when each deliverable has a link. One\n// deliverable, or an unreadable list, closes as before.\n// - warn: the close goes through, with one log line and one\n// close_proof_missing signal per request. block: it is refused,\n// verify_state = proof_missing, and the agent is told once.\n//\n// Part B (every mode, acts only after an owner-words mismatch, so only\n// with `requests.ownerCheck` on): the same checker detail that was judged\n// a mismatch does not close the request again. It closes again only on a\n// proof added after the reopen and after the owner's last send-back, a\n// changed checker detail, or the owner's own close. An owner note alone\n// gives the work back to the agent; it does not let the check close.\n//\n// closeByCheck is the only caller of store.closeVerified().\n\nexport type CloseProofMode = \"off\" | \"warn\" | \"block\"\n\nexport interface CloseProofSettings {\n mode: CloseProofMode\n /** Requests whose words are read per requests check (once a minute). */\n perCheck: number\n /** Agents told per requests check which deliverables need a link. */\n askPerCheck: number\n}\n\nexport const DEFAULT_CLOSE_PROOF: CloseProofSettings = { mode: \"off\", perCheck: 2, askPerCheck: 3 }\n\n/** Same cut as store.closeVerified: kept evidence is compared with it. */\nconst DETAIL_MAX = 500\nconst cut = (t: string) => t.trim().slice(0, DETAIL_MAX) || \"the check was met\"\n\n/** What the callers add after the checker's own words (daemon-api: the\n * agent's words on done; home-check: the plan's steps left). */\nconst SUFFIXES = [\" (agent: \", \"; its plan stopped with steps left: \"]\n\n/** The kept evidence holds this checker detail, and nothing else of the\n * checker's (#692 B1). The agent's words on done are never new. */\nexport function sameCheckDetail(evidence: string | null, detail: string): boolean {\n if (evidence == null) return false\n const d = cut(detail)\n if (evidence === d) return true\n if (!evidence.startsWith(d)) return false\n const rest = evidence.slice(d.length)\n // A suffix cut short at the 500 characters still counts.\n return SUFFIXES.some((s) => rest.startsWith(s) || (evidence.length >= DETAIL_MAX && s.startsWith(rest)))\n}\n\n/** The list a close is held to, and the proofs given for it. */\nexport interface Deliverables {\n names: string[]\n proofs: DeliverableProof[]\n /** From a tracked plan's steps (#692 B6). */\n fromPlan: boolean\n}\n\n/** A tracked plan's steps as deliverables: each step's own link. Skipped\n * steps were decided away and are left out. */\nexport function planDeliverables(steps: PlanStep[], linkOf: (text: string) => string | null): Deliverables | null {\n const kept = steps.filter((s) => s.state !== \"skipped\")\n if (!kept.length) return null\n const proofs: DeliverableProof[] = []\n for (const s of kept) {\n const link = s.state === \"done\" && s.evidence ? linkOf(s.evidence) : null\n if (link) proofs.push({ deliverable: s.name, link, at: s.updatedAt })\n }\n return { names: kept.map((s) => s.name), proofs, fromPlan: true }\n}\n\n/** What a request is held to. Null: its words are not read yet. */\nexport function deliverablesOf(r: RequestRecord, plan: Deliverables | null): Deliverables | null {\n if (plan) return plan\n if (r.deliverables === \"unreadable\") return { names: [\"what was asked\"], proofs: r.deliverableProofs ?? [], fromPlan: false }\n if (!r.deliverables) return null\n return { names: r.deliverables, proofs: r.deliverableProofs ?? [], fromPlan: false }\n}\n\nconst normLink = (l: string) => l.trim().replace(/\\/+$/, \"\").toLowerCase()\n\n/** Links that are no proof of a deliverable (#692 S6): the checker's own\n * ref and the home. Issue state alone proves nothing asked. */\nexport function refusedLinks(r: Pick<RequestRecord, \"home\" | \"closeWhen\">): string[] {\n const out: string[] = []\n if (r.home?.link) out.push(normLink(r.home.link))\n const ref = (r.closeWhen as { ref?: unknown } | null)?.ref\n if (typeof ref === \"string\" && ref) out.push(normLink(ref))\n return out\n}\n\n/** The link names the checker's own issue or merge request itself, not a\n * note or comment inside it (no anchor). */\nfunction isCheckedItem(r: Pick<RequestRecord, \"closeWhen\">, link: string): boolean {\n const cw = r.closeWhen as { kind?: string; provider?: unknown; ref?: unknown } | null\n if (cw?.kind !== \"issue\" || (cw.provider !== \"github\" && cw.provider !== \"gitlab\") || typeof cw.ref !== \"string\") return false\n try { if (new URL(link).hash) return false } catch { return false }\n const a = parseRef(cw.provider, cw.ref)\n const b = parseRef(cw.provider, link)\n return !!a && !!b && a.project.toLowerCase() === b.project.toLowerCase() && a.number === b.number && a.mr === b.mr\n}\n\nexport function isRefusedLink(r: Pick<RequestRecord, \"home\" | \"closeWhen\">, link: string): boolean {\n return refusedLinks(r).includes(normLink(link)) || isCheckedItem(r, link)\n}\n\n/** Whether proof `p` is for deliverable `i` (0-based) named `name`. */\nfunction proves(p: DeliverableProof, i: number, name: string): boolean {\n const d = p.deliverable.trim().toLowerCase()\n return d === name.trim().toLowerCase() || d === String(i + 1)\n}\n\n/** The deliverables with no proof link, numbered as in the list. One\n * deliverable needs none: it closes as before. */\nexport function missingProofs(r: RequestRecord, d: Deliverables): string[] {\n if (d.names.length <= 1) return []\n const refused = refusedLinks(r)\n return d.names\n .map((name, i) => ({ name, i }))\n .filter(({ name, i }) => !d.proofs.some((p) => proves(p, i, name) && !refused.includes(normLink(p.link)) && !isCheckedItem(r, p.link)))\n .map(({ name, i }) => `${i + 1}. ${name}`)\n}\n\nexport const HELD_TEXT = \"held: the owner-words check found this same result a mismatch; it closes again on a new proof link, a changed check result, or the owner's own close\"\n\n/** Part B (#692 B1–B3): why this met check must not close the request\n * again, or null when it may. */\nexport function holdReason(r: RequestRecord, detail: string, d: Deliverables | null, ownerCheckOn: boolean): string | null {\n if (!ownerCheckOn || r.ownerCheck !== \"mismatch\") return null\n if (!sameCheckDetail(r.evidence, detail)) return null\n const since = Math.max(r.ownerCheckAt ?? 0, r.sentBackAt ?? 0)\n const proofs = d?.proofs ?? r.deliverableProofs ?? []\n return proofs.some((p) => p.at > since) ? null : HELD_TEXT\n}\n\nexport interface CloseProofCtx {\n mode: CloseProofMode\n ownerCheckOn: boolean\n /** The request's tracked plan as deliverables, or null without one. */\n plan?: (requestId: string) => Deliverables | null\n /** Reads the request's words now (#692 B5). Unset: no provider; an\n * unread list counts as one deliverable. */\n read?: (r: RequestRecord) => Promise<void>\n /** Tells the agent which deliverables need a link (a new turn). */\n tell?: (agentId: string, text: string, r: RequestRecord) => Promise<void>\n hasAgent?: (agentId: string) => boolean\n /** Agents still to be told in this check (#692 S5). */\n askBudget?: { left: number }\n log?: (msg: string) => void\n}\n\nexport const PROOF_OFF: CloseProofCtx = { mode: \"off\", ownerCheckOn: false }\n\nexport type CloseOutcome =\n | { outcome: \"closed\" }\n | { outcome: \"held\"; detail: string }\n | { outcome: \"blocked\"; detail: string; missing: string[] }\n | { outcome: \"reading\"; detail: string }\n /** Already closed, or gone. */\n | { outcome: \"lost\" }\n\nconst READING_TEXT = \"reading what the owner's words ask for; the check runs again shortly\"\n\nexport function missingText(missing: string[]): string {\n return `no proof link yet for: ${missing.join(\"; \")}`\n}\n\n/** The gate, then the close: one transaction (#692 S1). `detail` is the\n * checker's own words; `evidence` what the close keeps (with any suffix\n * the caller adds). */\nexport function closeByCheckNow(store: RequestStore, id: string, detail: string, evidence: string, now: number, ctx: CloseProofCtx): CloseOutcome {\n return store.tx((): CloseOutcome => {\n const r = store.get(id)\n if (!r || [\"done\", \"declined\", \"dropped\"].includes(r.state)) return { outcome: \"lost\" }\n const plan = ctx.plan?.(r.id) ?? null\n const d = deliverablesOf(r, plan)\n const held = holdReason(r, detail, d, ctx.ownerCheckOn)\n if (held) {\n store.markChecked(r.id, \"held\", held, now)\n return { outcome: \"held\", detail: held }\n }\n if (ctx.mode !== \"off\") {\n if (!d) {\n // No provider: nothing will read it, so it counts as one.\n if (ctx.mode === \"block\" && ctx.read) {\n store.markChecked(r.id, \"proof_missing\", READING_TEXT, now)\n return { outcome: \"reading\", detail: READING_TEXT }\n }\n if (ctx.read) ctx.log?.(`[requests] ${r.id} closes by its check before its deliverables were read`)\n } else {\n const missing = missingProofs(r, d)\n if (missing.length) {\n const text = missingText(missing)\n if (ctx.mode === \"block\") {\n store.markChecked(r.id, \"proof_missing\", text, now)\n return { outcome: \"blocked\", detail: text, missing }\n }\n if (store.signalProofMissing(r.id, text, now)) ctx.log?.(`[requests] ${r.id} closed by its check with ${text}`)\n }\n }\n }\n return store.closeVerified(r.id, evidence, now) ? { outcome: \"closed\" } : { outcome: \"lost\" }\n })\n}\n\n/** closeByCheckNow, after reading an unread list first (#692 B5), and\n * telling the agent once when it is refused for proof. */\nexport async function closeByCheck(store: RequestStore, r: RequestRecord, detail: string, evidence: string, now: number, ctx: CloseProofCtx): Promise<CloseOutcome> {\n if (ctx.mode !== \"off\" && ctx.read && r.deliverables == null && !ctx.plan?.(r.id)) {\n await ctx.read(r).catch((e: any) => ctx.log?.(`[requests] ${r.id}: reading its deliverables failed: ${e?.message ?? e}`))\n }\n const out = closeByCheckNow(store, r.id, detail, evidence, now, ctx)\n if (out.outcome === \"blocked\") askForProof(store, r.id, out.missing, now, ctx)\n return out\n}\n\nexport function proofAskText(r: RequestRecord, missing: string[], fromPlan: boolean): string {\n return [\n `[agentx:request-proof id=${r.id}]`,\n `The check of this request is met, but the owner asked for several things and it does not close until each has its own proof link.`,\n `No link yet for:`,\n ...missing.map((m) => `- ${m}`),\n \"\",\n fromPlan\n ? \"Report each of these plan steps done with agentx_request {action: \\\"step\\\", step: <n>, status: \\\"done\\\", evidence: \\\"<link>\\\"}.\"\n : `Give one link per item with agentx_request {action: \"step\", id: \"${r.id}\", proofs: [{deliverable: <number or name>, link: \"<url>\"}]}. A note or comment link that shows the item done is a proof; the issue itself is not.`,\n ].join(\"\\n\")\n}\n\n/** Tell the agent once which deliverables need a link (#692 S5). Marked\n * before the call, unmarked when it fails. An agent not on this node:\n * the owner is told instead. */\nexport function askForProof(store: RequestStore, id: string, missing: string[], now: number, ctx: CloseProofCtx): void {\n const r = store.get(id)\n if (!r || r.proofAskedAt != null || !ctx.tell) return\n if (ctx.askBudget && ctx.askBudget.left <= 0) return\n if (ctx.hasAgent && !ctx.hasAgent(r.agentId)) {\n store.markProofAsked(id, now)\n store.needsAttention(id, `Its check is met, but it has ${missingText(missing)}, and ${r.agentId} is not on this node to give them`, now)\n return\n }\n if (ctx.askBudget) ctx.askBudget.left--\n store.markProofAsked(id, now)\n const fromPlan = !!ctx.plan?.(id)\n ctx.tell(r.agentId, proofAskText(r, missing, fromPlan), r).catch((e: any) => {\n store.markProofAsked(id, null)\n ctx.log?.(`[requests] ${id}: could not ask ${r.agentId} for proof links: ${e?.message ?? e}`)\n })\n}\n\n/** The \"proof per deliverable\" block of the owner-words prompt (#692 B4):\n * every kept link, where the 500-character evidence cannot hold them. */\nexport function proofBlock(d: Deliverables | null): string[] {\n if (!d || (d.names.length <= 1 && !d.proofs.length)) return []\n const lines = d.names.map((name, i) => {\n const links = d.proofs.filter((p) => proves(p, i, name)).map((p) => p.link)\n return `${i + 1}. ${name}: ${links.length ? links.join(\" \") : \"(no link)\"}`\n })\n return [\"\", \"Proof per deliverable (one link or more each, given by the assistant):\", ...lines]\n}\n"],"mappings":"uQAAA,OAAS,cAAAA,GAAY,aAAAC,GAAW,aAAAC,GAAW,cAAAC,GAAY,YAAAC,GAAU,gBAAAC,GAAc,YAAAC,GAAU,YAAAC,OAAgB,UACzG,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAS,iBAAAC,OAAqB,WAC9B,OAAS,WAAAC,OAAe,UCHxB,OAAS,QAAAC,GAAM,SAAAC,MAAa,OAarB,SAASC,EAASC,EAA4C,CACnE,OAAIA,IAAa,SAAiB,QAC9BA,IAAa,QAAgB,UAC1B,IACT,CAGO,IAAMC,EAAqB,oBAC3B,SAASC,GAAuBC,EAA8B,CACnE,OAAOL,EAAM,KAAKK,EAAc,WAAY,SAAUF,CAAkB,CAC1E,CAEO,IAAMG,GAAiB,oBACvB,SAASC,EAAmBC,EAAsB,CACvD,OAAOT,GAAKS,EAAM,eAAgBF,GAAgB,kCAAkC,CACtF,CAKO,SAASG,GAAeP,EAA2BQ,EAA4C,CACpG,IAAMC,EAAMD,EAAI,uBAAuB,KAAK,EAC5C,GAAIC,EAAK,OAAOA,EAChB,IAAMC,EAAMF,EAAI,mBAAmB,KAAK,EACxC,OAAOE,GAAOX,EAASC,CAAQ,IAAM,QAAUU,EAAM,MACvD,CAcO,SAASC,GAAqBC,EAAgC,CACnE,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A,EAAE,QAAQ,+BAA+BA,EAAE,OAAO,SAAS2B,EAAM,OAAS,SAAMA,EAAM,KAAK,QAAK,IAAM,IAClO","names":["accessSync","closeSync","constants","existsSync","openSync","readFileSync","readSync","statSync","dirname","join","fileURLToPath","homedir","join","win32","helperOs","platform","WINDOWS_HELPER_EXE","installedWindowsHelper","localAppData","MAC_HELPER_APP","installedMacHelper","home","helperOverride","env","any","mac","resolveDesktopHelper","l","override","os","installed","helperInstallHint","helperMissingMessage","hint","DESKTOP_LABEL","DESKTOP_APP","HELPER_APP","desktopPlatformError","platform","arch","release","selectDesktopAgent","agents","requested","id","shellQuote","value","LAUNCHD_PATH","desktopPath","ffmpeg","override","dirname","unxml","s","ents","_","e","plistPathEnv","plist","m","isVoiceLoginItemFile","name","adoptLoginItem","dir","items","keep","remove","file","a","b","label","program","join","findOnPath","bin","path","isExecutable","isNativeExecutable","accessSync","constants","statSync","fd","openSync","head","readSync","closeSync","desktopPlist","opts","xml","env","k","v","helperBuildArgs","icon","installedHelper","installedMacHelper","packageRoot","from","fileURLToPath","readFileSync","findHelper","path","resolveDesktopHelper","packageRoot","homedir","existsSync","accessSync","constants","execFile","STEP_TIMEOUT_MS","run","file","args","done","err","capture","stdout","output","resolve","reject","stderr","helperOf","io","findHelper","helperBannerStatus","path","capture","out","status","macosBanner","exec","run","title","message","helper","idleSecondsIn","ioreg","m","macosIdle","io","capture","out","NOTES_SCRIPT","macosNotes","exec","output","folder","title","body","id","existsSync","readdirSync","SOUNDS","soundPath","name","path","existsSync","macosSound","io","exec","run","volume","readdirSync","f","SPEAKERS","speakersIn","ps","exceptParents","self","line","m","pid","ppid","comm","name","macosSpeech","io","capture","opts","ZWSP","argValue","v","unArg","listName","list","isoDue","d","macosTasks","command","exec","output","raw","lists","l","items","r","title","notes","due","priority","args","id","patch","executable","file","accessSync","constants","focus","s","readSystemFocus","macosAdapter","cfg","io","command","macosTasks","macosNotes","macosBanner","macosSound","macosSpeech","macosIdle","problems","isExec","findOnPath","noneAdapter","reason","existsSync","readdirSync","win32","POWERSHELL","psString","value","q","psArgs","script","POWERSHELL_APP_ID","toastScript","title","message","psString","windowsBanner","io","exec","run","helper","POWERSHELL","psArgs","helperBannerStatus","capture","IDLE_SCRIPT","idleSecondsFromMs","out","ms","windowsIdle","io","capture","POWERSHELL","psArgs","win32","windowsSoundPath","name","io","path","win32","windowsSound","exec","run","volume","POWERSHELL","psArgs","psString","f","windowsAdapter","_cfg","io","helper","findHelper","media","win32","exists","existsSync","list","dir","readdirSync","windowsBanner","windowsSound","windowsIdle","problems","FACTORIES","macosAdapter","windowsAdapter","loadNativeAdapter","cfg","opts","noneAdapter","platform","make","existsSync","homedir","isAbsolute","DEFAULT_LOCAL","localSettings","cfg","localAlert","settings","deps","native","loadNativeAdapter","title","message","steps","sound","quiet","ok","speech","waitMs","pollMs","until","r","patchLocal","current","patch","platform","next","name","icon","homedir","isAbsolute","existsSync","v","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","resolve","init_checkers","init_store","init_checkers","init_issue","DEFAULT_CLOSE_PROOF","DETAIL_MAX","cut","t","SUFFIXES","sameCheckDetail","evidence","detail","d","rest","s","planDeliverables","steps","linkOf","kept","proofs","link","deliverablesOf","r","plan","normLink","l","refusedLinks","out","ref","isCheckedItem","cw","a","parseRef","b","isRefusedLink","proves","p","i","name","missingProofs","refused","HELD_TEXT","holdReason","ownerCheckOn","since","PROOF_OFF","READING_TEXT","missingText","missing","closeByCheckNow","store","id","now","ctx","held","text","closeByCheck","e","askForProof","proofAskText","fromPlan","m","proofBlock","links","STALL_GROUPS","HOUR","isOpen","r","OPEN_STATES","activeStepAgentOf","plans","requestId","s","waitsOn","look","OWED_TO_OWNER","stalledWhy","staleAfterHours","now","when","stalledLoops","items","out","why","group","who","waitsOnWords","ms","parseDue","v","at","loopChecker","ctx","spec","runCheck","CHECK_BATCH","checkLoops","store","check","opts","proof","PROOF_OFF","due","closed","res","e","closeByCheck","SUMMARY_MAX","ANSWER_MAX","NOTHING_NEEDED","cardWords","r","max","headline","summarize","need","plain","md","text","cut","end","loopOf","describeCloseWhen","requestCard","store","plans","stall","plan","why","stalledWhy","answer","cutAnswer","words","markdownToHtml","awaitingQa","waitsOn","activeStepAgentOf","s","MAX_ADD_FAILURES","KEEP_CLOSED_MS","mirrorPath","root","resolve","readMirror","parsed","readFileSync","writeMirror","file","path","existsSync","dirname","mkdirSync","tmp","writeFileSync","renameSync","MIRROR_FRESH_MS","mirrorCovers","cardId","now","checked","DAY_MS","dueFor","settings","limit","due","cardItem","card","answerUrl","expires","lines","summarize","CARD_LIMITS","c","i","requestItem","r","dueAt","cardWords","runMirror","deps","tasks","log","at","result","fail","message","waiting","e","allRead","openIds","openIn","list","t","key","entry","open","listReady","listError","cardsMissed","gaveUp","item","failures","id","n","told","first","more","err","MIRROR_GRACE_MS","mirrorTally","cards","from","to","inWindow","iso","tally","raisedAt","reason","tallyLine","extra"]}