agentix-cli 0.117.0 → 0.118.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 (136) hide show
  1. package/README.md +5 -5
  2. package/dist/{App-UQP7UQYV.js → App-XMSNIAU6.js} +2 -2
  3. package/dist/{ChatApp-VGSP5O6N.js → ChatApp-BFYTIQF3.js} +2 -2
  4. package/dist/{agent-MO27U4Y7.js → agent-E6W5VBYH.js} +2 -2
  5. package/dist/{board-dashboard-CSS7XMIZ.js → board-dashboard-D5FQZKO4.js} +215 -101
  6. package/dist/board-dashboard-D5FQZKO4.js.map +1 -0
  7. package/dist/chunk-23SQSUBI.js +3 -0
  8. package/dist/chunk-23SQSUBI.js.map +1 -0
  9. package/dist/{chunk-VRXJW6JJ.js → chunk-2G227TF3.js} +2 -2
  10. package/dist/{chunk-HVZVFCJX.js → chunk-4PQREYBU.js} +2 -2
  11. package/dist/{chunk-4FU4BFCH.js → chunk-5NTWGUSJ.js} +3 -3
  12. package/dist/chunk-5NTWGUSJ.js.map +1 -0
  13. package/dist/{chunk-2WK5A3UV.js → chunk-5PR6DZYW.js} +3 -3
  14. package/dist/chunk-5PR6DZYW.js.map +1 -0
  15. package/dist/{chunk-4ELAUGOP.js → chunk-5UFIHT66.js} +2 -2
  16. package/dist/{chunk-CUZTLQH2.js → chunk-6PC4EZ4P.js} +2 -2
  17. package/dist/chunk-AD4QZZVN.js +8 -0
  18. package/dist/{failure-candidates-PBPF45GN.js.map → chunk-AD4QZZVN.js.map} +1 -1
  19. package/dist/chunk-B6OXEIOF.js +126 -0
  20. package/dist/chunk-B6OXEIOF.js.map +1 -0
  21. package/dist/chunk-BDJWN3PL.js +4 -0
  22. package/dist/chunk-BDJWN3PL.js.map +1 -0
  23. package/dist/{chunk-OJ7KM2UO.js → chunk-FSXWNVGL.js} +2 -2
  24. package/dist/{chunk-746KHKT4.js → chunk-FTZCNID3.js} +2 -2
  25. package/dist/{chunk-PFK3QO6S.js → chunk-GJKYOEDE.js} +2 -2
  26. package/dist/{chunk-BQ2HJ7TS.js → chunk-HK7TU5NX.js} +2 -2
  27. package/dist/{chunk-FJI5GRBH.js → chunk-IMLLHT7U.js} +3 -3
  28. package/dist/chunk-IMLLHT7U.js.map +1 -0
  29. package/dist/chunk-IOYRRGK7.js +2 -0
  30. package/dist/chunk-IOYRRGK7.js.map +1 -0
  31. package/dist/{chunk-T2VDHVYW.js → chunk-IVCFXLAR.js} +2 -2
  32. package/dist/{chunk-W7WNRPNQ.js → chunk-NDPU6AX2.js} +2 -2
  33. package/dist/{chunk-45GOH6F7.js → chunk-NG677JHW.js} +8 -8
  34. package/dist/chunk-NG677JHW.js.map +1 -0
  35. package/dist/{chunk-MSP25HE5.js → chunk-PVQPXZHE.js} +5 -5
  36. package/dist/{chunk-5PPMPCHG.js → chunk-RJBRYUKU.js} +2 -2
  37. package/dist/{chunk-QLWGLRT5.js → chunk-TJ7IUHC7.js} +2 -2
  38. package/dist/{chunk-J2YLOGNN.js → chunk-U46G24CD.js} +2 -2
  39. package/dist/{chunk-IZMXAXW3.js → chunk-V4PVGEWI.js} +196 -197
  40. package/dist/chunk-V4PVGEWI.js.map +1 -0
  41. package/dist/chunk-WCXXXAHV.js +3 -0
  42. package/dist/{chunk-DMHQIACQ.js.map → chunk-WCXXXAHV.js.map} +1 -1
  43. package/dist/{chunk-45YETJY4.js → chunk-XGOBZCYC.js} +2 -2
  44. package/dist/{chunk-CKQ2YDFP.js → chunk-ZDWE47LM.js} +8 -8
  45. package/dist/chunk-ZDWE47LM.js.map +1 -0
  46. package/dist/cli.js +1 -1
  47. package/dist/{client-5UMNDY7Z.js → client-TSYZXEH7.js} +2 -2
  48. package/dist/{config-O44DOHFW.js → config-QAE3LNFQ.js} +2 -2
  49. package/dist/config-mutator-WRQ7MFQL.js +2 -0
  50. package/dist/{doctor-NKPH74F7.js → doctor-PVLVKLRA.js} +2 -2
  51. package/dist/failure-candidates-JNGUVBDG.js +2 -0
  52. package/dist/{grants-BRAVOGBP.js → grants-V2ZNLWSJ.js} +2 -2
  53. package/dist/index.d.ts +69 -2
  54. package/dist/index.js +1 -1
  55. package/dist/program-ZYG3YPH2.js +721 -0
  56. package/dist/program-ZYG3YPH2.js.map +1 -0
  57. package/dist/{promote-ZRNVPWTD.js → promote-IRBBEXGG.js} +2 -2
  58. package/dist/{push-bridge-VPTQNM43.js → push-bridge-325SXDGN.js} +2 -2
  59. package/dist/{query-HURONGKA.js → query-NAU7J34H.js} +2 -2
  60. package/dist/{registry-AYGFAKTC.js → registry-I5PXGCO6.js} +2 -2
  61. package/dist/{request-planner-ZZRSOBQZ.js → request-planner-CRG3OGGG.js} +2 -2
  62. package/dist/{review-candidates-KHH47PK7.js → review-candidates-HAP7P6SH.js} +2 -2
  63. package/dist/{routing-GUBKKWPT.js → routing-G33LLOTF.js} +2 -2
  64. package/dist/schedule-tool-IP7ZCQKI.js +2 -0
  65. package/dist/scheduler-QXLPYSNJ.js +2 -0
  66. package/dist/{seat-CVTTTE5V.js → seat-IJN7NETF.js} +2 -2
  67. package/dist/{select-OUTM6OBC.js → select-D7AZ2XZF.js} +2 -2
  68. package/dist/{set-enabled-2QKQRVUN.js → set-enabled-5YSDIQXU.js} +2 -2
  69. package/dist/{surface-usage-HCJTUS6Z.js → surface-usage-WSY4SHHL.js} +2 -2
  70. package/dist/{tool-XY7QGHLV.js → tool-GQIQWHWB.js} +2 -2
  71. package/dist/{tool-OFXHMLE5.js → tool-XADSW6NL.js} +2 -2
  72. package/dist/wiki-PPX3HYXW.js +2 -0
  73. package/dist/wiki-PPX3HYXW.js.map +1 -0
  74. package/package.json +1 -1
  75. package/dist/board-dashboard-CSS7XMIZ.js.map +0 -1
  76. package/dist/chunk-2WK5A3UV.js.map +0 -1
  77. package/dist/chunk-45GOH6F7.js.map +0 -1
  78. package/dist/chunk-4FU4BFCH.js.map +0 -1
  79. package/dist/chunk-CKQ2YDFP.js.map +0 -1
  80. package/dist/chunk-DMHQIACQ.js +0 -3
  81. package/dist/chunk-FJI5GRBH.js.map +0 -1
  82. package/dist/chunk-HYGMWCUU.js +0 -126
  83. package/dist/chunk-HYGMWCUU.js.map +0 -1
  84. package/dist/chunk-IZMXAXW3.js.map +0 -1
  85. package/dist/chunk-JIT5GPTX.js +0 -4
  86. package/dist/chunk-JIT5GPTX.js.map +0 -1
  87. package/dist/chunk-PMQ47IPT.js +0 -2
  88. package/dist/chunk-PMQ47IPT.js.map +0 -1
  89. package/dist/chunk-VEHTVYP6.js +0 -2
  90. package/dist/chunk-VEHTVYP6.js.map +0 -1
  91. package/dist/config-mutator-PRLY2TCE.js +0 -2
  92. package/dist/failure-candidates-PBPF45GN.js +0 -8
  93. package/dist/program-RHIJYCEJ.js +0 -703
  94. package/dist/program-RHIJYCEJ.js.map +0 -1
  95. package/dist/schedule-tool-VH77T3N3.js +0 -2
  96. package/dist/scheduler-SZ4YYXJE.js +0 -2
  97. package/dist/wiki-46GMWX34.js +0 -2
  98. /package/dist/{App-UQP7UQYV.js.map → App-XMSNIAU6.js.map} +0 -0
  99. /package/dist/{ChatApp-VGSP5O6N.js.map → ChatApp-BFYTIQF3.js.map} +0 -0
  100. /package/dist/{agent-MO27U4Y7.js.map → agent-E6W5VBYH.js.map} +0 -0
  101. /package/dist/{chunk-VRXJW6JJ.js.map → chunk-2G227TF3.js.map} +0 -0
  102. /package/dist/{chunk-HVZVFCJX.js.map → chunk-4PQREYBU.js.map} +0 -0
  103. /package/dist/{chunk-4ELAUGOP.js.map → chunk-5UFIHT66.js.map} +0 -0
  104. /package/dist/{chunk-CUZTLQH2.js.map → chunk-6PC4EZ4P.js.map} +0 -0
  105. /package/dist/{chunk-OJ7KM2UO.js.map → chunk-FSXWNVGL.js.map} +0 -0
  106. /package/dist/{chunk-746KHKT4.js.map → chunk-FTZCNID3.js.map} +0 -0
  107. /package/dist/{chunk-PFK3QO6S.js.map → chunk-GJKYOEDE.js.map} +0 -0
  108. /package/dist/{chunk-BQ2HJ7TS.js.map → chunk-HK7TU5NX.js.map} +0 -0
  109. /package/dist/{chunk-T2VDHVYW.js.map → chunk-IVCFXLAR.js.map} +0 -0
  110. /package/dist/{chunk-W7WNRPNQ.js.map → chunk-NDPU6AX2.js.map} +0 -0
  111. /package/dist/{chunk-MSP25HE5.js.map → chunk-PVQPXZHE.js.map} +0 -0
  112. /package/dist/{chunk-5PPMPCHG.js.map → chunk-RJBRYUKU.js.map} +0 -0
  113. /package/dist/{chunk-QLWGLRT5.js.map → chunk-TJ7IUHC7.js.map} +0 -0
  114. /package/dist/{chunk-J2YLOGNN.js.map → chunk-U46G24CD.js.map} +0 -0
  115. /package/dist/{chunk-45YETJY4.js.map → chunk-XGOBZCYC.js.map} +0 -0
  116. /package/dist/{client-5UMNDY7Z.js.map → client-TSYZXEH7.js.map} +0 -0
  117. /package/dist/{config-O44DOHFW.js.map → config-QAE3LNFQ.js.map} +0 -0
  118. /package/dist/{config-mutator-PRLY2TCE.js.map → config-mutator-WRQ7MFQL.js.map} +0 -0
  119. /package/dist/{doctor-NKPH74F7.js.map → doctor-PVLVKLRA.js.map} +0 -0
  120. /package/dist/{grants-BRAVOGBP.js.map → failure-candidates-JNGUVBDG.js.map} +0 -0
  121. /package/dist/{promote-ZRNVPWTD.js.map → grants-V2ZNLWSJ.js.map} +0 -0
  122. /package/dist/{push-bridge-VPTQNM43.js.map → promote-IRBBEXGG.js.map} +0 -0
  123. /package/dist/{query-HURONGKA.js.map → push-bridge-325SXDGN.js.map} +0 -0
  124. /package/dist/{registry-AYGFAKTC.js.map → query-NAU7J34H.js.map} +0 -0
  125. /package/dist/{routing-GUBKKWPT.js.map → registry-I5PXGCO6.js.map} +0 -0
  126. /package/dist/{request-planner-ZZRSOBQZ.js.map → request-planner-CRG3OGGG.js.map} +0 -0
  127. /package/dist/{review-candidates-KHH47PK7.js.map → review-candidates-HAP7P6SH.js.map} +0 -0
  128. /package/dist/{schedule-tool-VH77T3N3.js.map → routing-G33LLOTF.js.map} +0 -0
  129. /package/dist/{scheduler-SZ4YYXJE.js.map → schedule-tool-IP7ZCQKI.js.map} +0 -0
  130. /package/dist/{seat-CVTTTE5V.js.map → scheduler-QXLPYSNJ.js.map} +0 -0
  131. /package/dist/{surface-usage-HCJTUS6Z.js.map → seat-IJN7NETF.js.map} +0 -0
  132. /package/dist/{select-OUTM6OBC.js.map → select-D7AZ2XZF.js.map} +0 -0
  133. /package/dist/{set-enabled-2QKQRVUN.js.map → set-enabled-5YSDIQXU.js.map} +0 -0
  134. /package/dist/{wiki-46GMWX34.js.map → surface-usage-WSY4SHHL.js.map} +0 -0
  135. /package/dist/{tool-XY7QGHLV.js.map → tool-GQIQWHWB.js.map} +0 -0
  136. /package/dist/{tool-OFXHMLE5.js.map → tool-XADSW6NL.js.map} +0 -0
@@ -0,0 +1,3 @@
1
+ import{a as c}from"./chunk-HK7TU5NX.js";import{resolve as d}from"path";import{existsSync as h,readdirSync as f,mkdirSync as l,readFileSync as S,writeFileSync as m,renameSync as b}from"fs";var u=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=d(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=d(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new c(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=d(this.agentsDir,t,this.mode),s=new c(r,this.log);return this.agentStores.set(e,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(h(this.agentsDir))for(let r of f(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){return this.classifyEntries(t).pending}markProcessed(t,e,r){let s=new Set(r),o=this.readLedger(t),a=new Date().toISOString();for(let i of e)o.entries[i]={at:a,cited:s.has(i)};let n=this.ledgerPath(t);l(d(n,".."),{recursive:!0});let g=`${n}.tmp`;m(g,`${JSON.stringify(o,null,2)}
2
+ `),b(g,n)}summary(){return this.listAgents().map(e=>{let{all:r,cited:s,read:o,pending:a,articles:n}=this.classifyEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.length,cited:s.length,readNotCited:o.length,unabsorbed:a.length,articles:n}})}classifyEntries(t){let e=this.getAgentEntries(t),r=this.getAgentWiki(t).rebuildIndex().articles,s=new Set;for(let i of r)if(i.sources)for(let p of i.sources)s.add(p);let o=this.readLedger(t).entries,a=[],n=[],g=[];for(let i of e)s.has(i.id)?a.push(i):o[i.id]?n.push(i):g.push(i);return{all:e,cited:a,read:n,pending:g,articles:r}}ledgerPath(t){return d(this.agentsDir,t,"_absorbed.json")}readLedger(t){let e=this.ledgerPath(t);if(!h(e))return{entries:{}};try{return{entries:JSON.parse(S(e,"utf-8")).entries??{}}}catch(r){throw new Error(`absorb ledger ${e} is not valid JSON: ${r.message}`)}}};export{u as a};
3
+ //# sourceMappingURL=chunk-23SQSUBI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/hub.ts"],"sourcesContent":["import { WikiStore } from \"./store\"\nimport { resolve } from \"path\"\nimport { existsSync, readdirSync, mkdirSync, readFileSync, writeFileSync, renameSync } from \"fs\"\nimport type { WikiEntry } from \"./types\"\n\nexport type WikiMode = \"flat\" | \"graph\" | \"unified\"\n\n/**\n * WikiHub: manages per-agent wikis with a shared raw entry pool.\n * Supports two compilation modes:\n * - flat: Karpathy pattern — tags, LLM-chosen paths, worldview, gap detection\n * - graph: Knowledge graph — kind, parent, hierarchy, events, entities\n *\n * Both modes share the same raw entries. Articles stored separately:\n * agents/<id>/flat/ ← Karpathy compilation\n * agents/<id>/graph/ ← Knowledge graph compilation\n */\nexport class WikiHub {\n private baseDir: string\n private agentsDir: string\n private mode: WikiMode\n private sharedStore: WikiStore\n private agentStores: Map<string, WikiStore> = new Map()\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki-hub]\"),\n mode: WikiMode = \"graph\",\n ) {\n this.baseDir = baseDir\n this.agentsDir = resolve(baseDir, \"agents\")\n this.mode = mode\n this.log = log\n\n mkdirSync(this.agentsDir, { recursive: true })\n this.sharedStore = new WikiStore(baseDir, log)\n }\n\n getMode(): WikiMode { return this.mode }\n\n /**\n * Get or create the wiki store for a specific agent (mode-aware).\n * flat: agents/<id>/flat/\n * graph: agents/<id>/graph/\n */\n getAgentWiki(agentId: string): WikiStore {\n const key = `${agentId}:${this.mode}`\n if (this.agentStores.has(key)) return this.agentStores.get(key)!\n\n const agentDir = resolve(this.agentsDir, agentId, this.mode)\n const store = new WikiStore(agentDir, this.log)\n this.agentStores.set(key, store)\n return store\n }\n\n /** The wiki root: shared sidecars (_facts.json, _questions.json) live here. */\n getBaseDir(): string {\n return this.baseDir\n }\n\n getSharedStore(): WikiStore {\n return this.sharedStore\n }\n\n listAgents(): string[] {\n const agents = new Set<string>()\n\n const entries = this.sharedStore.listEntries()\n for (const e of entries) agents.add(e.agentId)\n\n if (existsSync(this.agentsDir)) {\n for (const dir of readdirSync(this.agentsDir)) {\n if (!dir.startsWith(\"_\") && !dir.startsWith(\".\")) {\n agents.add(dir)\n }\n }\n }\n\n return [...agents].sort()\n }\n\n getAgentEntries(agentId: string): WikiEntry[] {\n return this.sharedStore.listEntries({ agentId })\n }\n\n /**\n * Entries absorb has not dealt with yet: no article cites them and no\n * successful absorb run has read them. Without the second check an\n * entry absorb read and chose not to cite came back on every run, and\n * a backfill kept re-reading the head of the queue (#762).\n */\n getUnabsorbedEntries(agentId: string): WikiEntry[] {\n return this.classifyEntries(agentId).pending\n }\n\n /**\n * Record every entry handed to the model in a successful absorb run,\n * cited or not. Callers must not call this for a failed run, so those\n * entries are offered again.\n */\n markProcessed(agentId: string, entryIds: string[], citedIds: Iterable<string>): void {\n const cited = new Set(citedIds)\n const ledger = this.readLedger(agentId)\n const at = new Date().toISOString()\n for (const id of entryIds) ledger.entries[id] = { at, cited: cited.has(id) }\n\n const file = this.ledgerPath(agentId)\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(ledger, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n summary(): AgentWikiSummary[] {\n const agents = this.listAgents()\n return agents.map(agentId => {\n const { all, cited, read, pending, articles } = this.classifyEntries(agentId)\n return {\n agentId,\n totalEntries: all.length,\n totalArticles: articles.length,\n cited: cited.length,\n readNotCited: read.length,\n unabsorbed: pending.length,\n articles,\n }\n })\n }\n\n /** Split an agent's entries into cited by an article, read but not cited, and pending. */\n private classifyEntries(agentId: string) {\n const all = this.getAgentEntries(agentId)\n const articles = this.getAgentWiki(agentId).rebuildIndex().articles\n\n const citedIds = new Set<string>()\n for (const article of articles) {\n if (article.sources) {\n for (const s of article.sources) citedIds.add(s)\n }\n }\n const ledger = this.readLedger(agentId).entries\n\n const cited: WikiEntry[] = []\n const read: WikiEntry[] = []\n const pending: WikiEntry[] = []\n for (const e of all) {\n if (citedIds.has(e.id)) cited.push(e)\n else if (ledger[e.id]) read.push(e)\n else pending.push(e)\n }\n return { all, cited, read, pending, articles }\n }\n\n /** agents/<id>/_absorbed.json — shared by every mode, like the raw entries. */\n private ledgerPath(agentId: string): string {\n return resolve(this.agentsDir, agentId, \"_absorbed.json\")\n }\n\n private readLedger(agentId: string): AbsorbLedger {\n const file = this.ledgerPath(agentId)\n if (!existsSync(file)) return { entries: {} }\n try {\n const parsed = JSON.parse(readFileSync(file, \"utf-8\")) as AbsorbLedger\n return { entries: parsed.entries ?? {} }\n } catch (err) {\n // Treating a damaged ledger as empty would let the next run\n // overwrite it and re-queue everything it recorded.\n throw new Error(`absorb ledger ${file} is not valid JSON: ${(err as Error).message}`)\n }\n }\n}\n\ninterface AbsorbLedger {\n entries: Record<string, { at: string; cited: boolean }>\n}\n\nexport interface AgentWikiSummary {\n agentId: string\n totalEntries: number\n totalArticles: number\n /** Entries an article cites. */\n cited: number\n /** Entries a successful absorb run read and did not cite. */\n readNotCited: number\n /** Entries absorb has not read yet. */\n unabsorbed: number\n articles: Array<{ title: string; path: string; tags?: string[] }>\n}\n"],"mappings":"wCACA,OAAS,WAAAA,MAAe,OACxB,OAAS,cAAAC,EAAY,eAAAC,EAAa,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,EAAe,cAAAC,MAAkB,KAerF,IAAMC,EAAN,KAAc,CACX,QACA,UACA,KACA,YACA,YAAsC,IAAI,IAC1C,IAER,YACEC,EAAkBR,EAAQ,QAAQ,IAAI,EAAG,cAAc,EACvDS,EAAoC,QAAQ,MAAM,KAAK,QAAS,YAAY,EAC5EC,EAAiB,QACjB,CACA,KAAK,QAAUF,EACf,KAAK,UAAYR,EAAQQ,EAAS,QAAQ,EAC1C,KAAK,KAAOE,EACZ,KAAK,IAAMD,EAEXN,EAAU,KAAK,UAAW,CAAE,UAAW,EAAK,CAAC,EAC7C,KAAK,YAAc,IAAIQ,EAAUH,EAASC,CAAG,CAC/C,CAEA,SAAoB,CAAE,OAAO,KAAK,IAAK,CAOvC,aAAaG,EAA4B,CACvC,IAAMC,EAAM,GAAGD,KAAW,KAAK,OAC/B,GAAI,KAAK,YAAY,IAAIC,CAAG,EAAG,OAAO,KAAK,YAAY,IAAIA,CAAG,EAE9D,IAAMC,EAAWd,EAAQ,KAAK,UAAWY,EAAS,KAAK,IAAI,EACrDG,EAAQ,IAAIJ,EAAUG,EAAU,KAAK,GAAG,EAC9C,YAAK,YAAY,IAAID,EAAKE,CAAK,EACxBA,CACT,CAGA,YAAqB,CACnB,OAAO,KAAK,OACd,CAEA,gBAA4B,CAC1B,OAAO,KAAK,WACd,CAEA,YAAuB,CACrB,IAAMC,EAAS,IAAI,IAEbC,EAAU,KAAK,YAAY,YAAY,EAC7C,QAAWC,KAAKD,EAASD,EAAO,IAAIE,EAAE,OAAO,EAE7C,GAAIjB,EAAW,KAAK,SAAS,EAC3B,QAAWkB,KAAOjB,EAAY,KAAK,SAAS,EACtC,CAACiB,EAAI,WAAW,GAAG,GAAK,CAACA,EAAI,WAAW,GAAG,GAC7CH,EAAO,IAAIG,CAAG,EAKpB,MAAO,CAAC,GAAGH,CAAM,EAAE,KAAK,CAC1B,CAEA,gBAAgBJ,EAA8B,CAC5C,OAAO,KAAK,YAAY,YAAY,CAAE,QAAAA,CAAQ,CAAC,CACjD,CAQA,qBAAqBA,EAA8B,CACjD,OAAO,KAAK,gBAAgBA,CAAO,EAAE,OACvC,CAOA,cAAcA,EAAiBQ,EAAoBC,EAAkC,CACnF,IAAMC,EAAQ,IAAI,IAAID,CAAQ,EACxBE,EAAS,KAAK,WAAWX,CAAO,EAChCY,EAAK,IAAI,KAAK,EAAE,YAAY,EAClC,QAAWC,KAAML,EAAUG,EAAO,QAAQE,CAAE,EAAI,CAAE,GAAAD,EAAI,MAAOF,EAAM,IAAIG,CAAE,CAAE,EAE3E,IAAMC,EAAO,KAAK,WAAWd,CAAO,EACpCT,EAAUH,EAAQ0B,EAAM,IAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EAClD,IAAMC,EAAM,GAAGD,QACfrB,EAAcsB,EAAK,GAAG,KAAK,UAAUJ,EAAQ,KAAM,CAAC;AAAA,CAAK,EACzDjB,EAAWqB,EAAKD,CAAI,CACtB,CAEA,SAA8B,CAE5B,OADe,KAAK,WAAW,EACjB,IAAId,GAAW,CAC3B,GAAM,CAAE,IAAAgB,EAAK,MAAAN,EAAO,KAAAO,EAAM,QAAAC,EAAS,SAAAC,CAAS,EAAI,KAAK,gBAAgBnB,CAAO,EAC5E,MAAO,CACL,QAAAA,EACA,aAAcgB,EAAI,OAClB,cAAeG,EAAS,OACxB,MAAOT,EAAM,OACb,aAAcO,EAAK,OACnB,WAAYC,EAAQ,OACpB,SAAAC,CACF,CACF,CAAC,CACH,CAGQ,gBAAgBnB,EAAiB,CACvC,IAAMgB,EAAM,KAAK,gBAAgBhB,CAAO,EAClCmB,EAAW,KAAK,aAAanB,CAAO,EAAE,aAAa,EAAE,SAErDS,EAAW,IAAI,IACrB,QAAWW,KAAWD,EACpB,GAAIC,EAAQ,QACV,QAAWC,KAAKD,EAAQ,QAASX,EAAS,IAAIY,CAAC,EAGnD,IAAMV,EAAS,KAAK,WAAWX,CAAO,EAAE,QAElCU,EAAqB,CAAC,EACtBO,EAAoB,CAAC,EACrBC,EAAuB,CAAC,EAC9B,QAAWZ,KAAKU,EACVP,EAAS,IAAIH,EAAE,EAAE,EAAGI,EAAM,KAAKJ,CAAC,EAC3BK,EAAOL,EAAE,EAAE,EAAGW,EAAK,KAAKX,CAAC,EAC7BY,EAAQ,KAAKZ,CAAC,EAErB,MAAO,CAAE,IAAAU,EAAK,MAAAN,EAAO,KAAAO,EAAM,QAAAC,EAAS,SAAAC,CAAS,CAC/C,CAGQ,WAAWnB,EAAyB,CAC1C,OAAOZ,EAAQ,KAAK,UAAWY,EAAS,gBAAgB,CAC1D,CAEQ,WAAWA,EAA+B,CAChD,IAAMc,EAAO,KAAK,WAAWd,CAAO,EACpC,GAAI,CAACX,EAAWyB,CAAI,EAAG,MAAO,CAAE,QAAS,CAAC,CAAE,EAC5C,GAAI,CAEF,MAAO,CAAE,QADM,KAAK,MAAMtB,EAAasB,EAAM,OAAO,CAAC,EAC5B,SAAW,CAAC,CAAE,CACzC,OAASQ,EAAP,CAGA,MAAM,IAAI,MAAM,iBAAiBR,wBAA4BQ,EAAc,SAAS,CACtF,CACF,CACF","names":["resolve","existsSync","readdirSync","mkdirSync","readFileSync","writeFileSync","renameSync","WikiHub","baseDir","log","mode","WikiStore","agentId","key","agentDir","store","agents","entries","e","dir","entryIds","citedIds","cited","ledger","at","id","file","tmp","all","read","pending","articles","article","s","err"]}
@@ -1,2 +1,2 @@
1
- import{y as l,z as T}from"./chunk-W7WNRPNQ.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
- //# sourceMappingURL=chunk-VRXJW6JJ.js.map
1
+ import{y as l,z as T}from"./chunk-NDPU6AX2.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
2
+ //# sourceMappingURL=chunk-2G227TF3.js.map
@@ -1,5 +1,5 @@
1
- import{ha as m,ia as $,ma as x}from"./chunk-FJI5GRBH.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
1
+ import{ha as m,ia as $,ma as x}from"./chunk-IMLLHT7U.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
4
4
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
5
- //# sourceMappingURL=chunk-HVZVFCJX.js.map
5
+ //# sourceMappingURL=chunk-4PQREYBU.js.map
@@ -1,9 +1,9 @@
1
- import{f as o,n as u}from"./chunk-UIBUZ2N3.js";u();import{existsSync as s}from"fs";import{resolve as a}from"path";function c(){return!!(process.env.VITEST||process.env.NODE_ENV==="test"||process.env.AGENTX_NO_TELEMETRY)}function d(){let n=process.cwd();for(let t=0;t<5;t++){if(s(a(n,".agentx"))||s(a(n,"agentx.json")))return n;let e=a(n,"..");if(e===n)break;n=e}return null}function f(n=new Date){return n.toISOString().slice(0,10)}function g(n,t,e=new Date){try{if(!t||c()||!d())return;let r=o({quiet:!0});if(!r)return;r.prepare(`INSERT INTO surface_usage (kind, name, day, count, last_at)
1
+ import{f as o,n as u}from"./chunk-UIBUZ2N3.js";u();import{existsSync as s}from"fs";import{resolve as a}from"path";function c(){return!!(process.env.VITEST||process.env.NODE_ENV==="test"||process.env.AGENTX_NO_TELEMETRY)}function d(){let n=process.cwd();for(let t=0;t<5;t++){if(s(a(n,".agentx"))||s(a(n,"agentx.json")))return n;let e=a(n,"..");if(e===n)break;n=e}return null}function f(n=new Date){return n.toISOString().slice(0,10)}function g(n,t,e=new Date){try{if(!t||c()||d()!==process.cwd())return;let r=o({quiet:!0});if(!r)return;r.prepare(`INSERT INTO surface_usage (kind, name, day, count, last_at)
2
2
  VALUES (?, ?, ?, 1, ?)
3
3
  ON CONFLICT(kind, name, day)
4
4
  DO UPDATE SET count = count + 1, last_at = excluded.last_at`).run(n,t,f(e),e.toISOString())}catch{}}function E(n={}){try{let t=o({quiet:!0});if(!t)return[];let e=new Date(Date.now()-(n.sinceDays??30)*864e5).toISOString().slice(0,10),r=["day >= ?"],i=[e];return n.kind&&(r.push("kind = ?"),i.push(n.kind)),t.prepare(`SELECT kind, name, SUM(count) AS count, COUNT(DISTINCT day) AS days, MAX(last_at) AS last_at
5
5
  FROM surface_usage
6
6
  WHERE ${r.join(" AND ")}
7
7
  GROUP BY kind, name
8
- ORDER BY count DESC`).all(...i)}catch{return[]}}function T(n){let t=[],e=n;for(;e&&typeof e.name=="function";){let r=e.name();e.parent&&t.unshift(r),e=e.parent}return t.join(" ")}var l=new Set(["guard check","completion","serve"]);function y(n){return!!n&&!l.has(n)}export{g as a,E as b,T as c,y as d};
9
- //# sourceMappingURL=chunk-4FU4BFCH.js.map
8
+ ORDER BY count DESC`).all(...i)}catch{return[]}}function T(n){let t=[],e=n;for(;e&&typeof e.name=="function";){let r=e.name();e.parent&&t.unshift(r),e=e.parent}return t.join(" ")}var l=new Set(["guard check","completion","serve","demo"]);function y(n){return!!n&&!l.has(n)}export{g as a,E as b,T as c,y as d};
9
+ //# sourceMappingURL=chunk-5NTWGUSJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/observability/surface-usage.ts"],"sourcesContent":["import { existsSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { openDb } from \"@/storage/sqlite\"\n\n// --- Which operator surfaces actually get used ---\n//\n// `task_history` answers \"which agents ran\". It says nothing about which of\n// the ~46 CLI commands or 16 dashboard pages anyone ever opens — and those are\n// the two biggest surfaces by count, so they are exactly what the\n// surface-reduction work needs evidence for.\n//\n// See docs/architecture/surface-reduction.md for the bar a surface has to\n// clear to survive. This module is the missing measurement.\n//\n// Three rules, all of them about being unobtrusive:\n//\n// 1. Names only. `agentx guard log --limit 5` records \"guard log\". A page\n// view records \"/live\". Never arguments, never query strings, never\n// payloads. This counts which door was opened, not what went through it.\n// 2. Never create state. If there is no `.agentx` here, we are being run\n// from someone's home directory or a random repo — recording would\n// litter a stray database. Do nothing instead.\n// 3. Never throw, never block. A telemetry bug must not break the CLI or a\n// dashboard request. Every failure is swallowed.\n\n/**\n * True while a test runner is driving us.\n *\n * Three suites (trace-cli, process-cli, intent-ledger-cli) shell out to the\n * real CLI, so a full `pnpm test` recorded dozens of invocations of exactly\n * the commands that happen to have CLI tests — `trace list` showed 72 uses\n * against a human total of zero. That is worse than no data: it inverts the\n * ranking, making well-tested commands look popular and untested ones look\n * dead, which is precisely backwards for deciding what to remove.\n */\nfunction underTest(): boolean {\n return Boolean(process.env.VITEST || process.env.NODE_ENV === \"test\" || process.env.AGENTX_NO_TELEMETRY)\n}\n\n/** Where the install lives, or null when we're not inside one. Never creates\n * anything — the check IS the guard against writing stray databases. */\nfunction installRoot(): string | null {\n let dir = process.cwd()\n for (let i = 0; i < 5; i++) {\n if (existsSync(resolve(dir, \".agentx\")) || existsSync(resolve(dir, \"agentx.json\"))) return dir\n const parent = resolve(dir, \"..\")\n if (parent === dir) break\n dir = parent\n }\n return null\n}\n\nfunction today(now = new Date()): string {\n return now.toISOString().slice(0, 10)\n}\n\nexport type SurfaceKind = \"cli\" | \"page\"\n\n/**\n * Record one use of a surface. Silent no-op when we're outside an install,\n * when SQLite is unavailable, or on any error.\n */\nexport function recordSurfaceUse(kind: SurfaceKind, name: string, now = new Date()): void {\n try {\n if (!name) return\n if (underTest()) return\n // openDb() writes under the cwd and caches one handle per process, so only\n // record when the cwd *is* the install. Recording from a subfolder would\n // leave a stray .agentx/db.sqlite there.\n if (installRoot() !== process.cwd()) return\n const db = openDb({ quiet: true })\n if (!db) return\n db.prepare(\n `INSERT INTO surface_usage (kind, name, day, count, last_at)\n VALUES (?, ?, ?, 1, ?)\n ON CONFLICT(kind, name, day)\n DO UPDATE SET count = count + 1, last_at = excluded.last_at`,\n ).run(kind, name, today(now), now.toISOString())\n } catch {\n /* telemetry must never break the thing it measures */\n }\n}\n\nexport interface SurfaceRow {\n kind: string\n name: string\n count: number\n days: number\n last_at: string | null\n}\n\n/** Usage totals over a window, busiest first. Powers `agentx usage surfaces`. */\nexport function listSurfaceUse(opts: { kind?: SurfaceKind; sinceDays?: number } = {}): SurfaceRow[] {\n try {\n const db = openDb({ quiet: true })\n if (!db) return []\n const since = new Date(Date.now() - (opts.sinceDays ?? 30) * 86_400_000)\n .toISOString()\n .slice(0, 10)\n const where = [\"day >= ?\"]\n const params: unknown[] = [since]\n if (opts.kind) {\n where.push(\"kind = ?\")\n params.push(opts.kind)\n }\n return db\n .prepare(\n `SELECT kind, name, SUM(count) AS count, COUNT(DISTINCT day) AS days, MAX(last_at) AS last_at\n FROM surface_usage\n WHERE ${where.join(\" AND \")}\n GROUP BY kind, name\n ORDER BY count DESC`,\n )\n .all(...params) as SurfaceRow[]\n } catch {\n return []\n }\n}\n\n/**\n * The command path a commander invocation resolved to — \"guard log\", not\n * \"guard log --limit 5\". Walks up from the deepest matched subcommand so\n * nesting is preserved without ever touching argv.\n */\nexport function commandPath(cmd: { name(): string; parent?: unknown } | null | undefined): string {\n const parts: string[] = []\n let node: any = cmd\n while (node && typeof node.name === \"function\") {\n const n = node.name()\n // The root program is \"agentx\" itself — not a surface worth counting.\n if (node.parent) parts.unshift(n)\n node = node.parent\n }\n return parts.join(\" \")\n}\n\n/** Hook entrypoints fire per tool call, not per human decision. Counting them\n * would swamp the table and tell us nothing about operator behaviour. */\nconst NOT_A_SURFACE = new Set([\"guard check\", \"completion\", \"serve\", \"demo\"])\n\nexport function shouldRecordCommand(path: string): boolean {\n return Boolean(path) && !NOT_A_SURFACE.has(path)\n}\n"],"mappings":"+CAEAA,IAFA,OAAS,cAAAC,MAAkB,KAC3B,OAAS,WAAAC,MAAe,OAkCxB,SAASC,GAAqB,CAC5B,MAAO,GAAQ,QAAQ,IAAI,QAAU,QAAQ,IAAI,WAAa,QAAU,QAAQ,IAAI,oBACtF,CAIA,SAASC,GAA6B,CACpC,IAAIC,EAAM,QAAQ,IAAI,EACtB,QAASC,EAAI,EAAGA,EAAI,EAAGA,IAAK,CAC1B,GAAIL,EAAWC,EAAQG,EAAK,SAAS,CAAC,GAAKJ,EAAWC,EAAQG,EAAK,aAAa,CAAC,EAAG,OAAOA,EAC3F,IAAME,EAASL,EAAQG,EAAK,IAAI,EAChC,GAAIE,IAAWF,EAAK,MACpBA,EAAME,EAER,OAAO,IACT,CAEA,SAASC,EAAMC,EAAM,IAAI,KAAgB,CACvC,OAAOA,EAAI,YAAY,EAAE,MAAM,EAAG,EAAE,CACtC,CAQO,SAASC,EAAiBC,EAAmBC,EAAcH,EAAM,IAAI,KAAc,CACxF,GAAI,CAMF,GALI,CAACG,GACDT,EAAU,GAIVC,EAAY,IAAM,QAAQ,IAAI,EAAG,OACrC,IAAMS,EAAKC,EAAO,CAAE,MAAO,EAAK,CAAC,EACjC,GAAI,CAACD,EAAI,OACTA,EAAG,QACD;AAAA;AAAA;AAAA,mEAIF,EAAE,IAAIF,EAAMC,EAAMJ,EAAMC,CAAG,EAAGA,EAAI,YAAY,CAAC,CACjD,MAAE,CAEF,CACF,CAWO,SAASM,EAAeC,EAAmD,CAAC,EAAiB,CAClG,GAAI,CACF,IAAMH,EAAKC,EAAO,CAAE,MAAO,EAAK,CAAC,EACjC,GAAI,CAACD,EAAI,MAAO,CAAC,EACjB,IAAMI,EAAQ,IAAI,KAAK,KAAK,IAAI,GAAKD,EAAK,WAAa,IAAM,KAAU,EACpE,YAAY,EACZ,MAAM,EAAG,EAAE,EACRE,EAAQ,CAAC,UAAU,EACnBC,EAAoB,CAACF,CAAK,EAChC,OAAID,EAAK,OACPE,EAAM,KAAK,UAAU,EACrBC,EAAO,KAAKH,EAAK,IAAI,GAEhBH,EACJ,QACC;AAAA;AAAA,iBAESK,EAAM,KAAK,OAAO;AAAA;AAAA,6BAG7B,EACC,IAAI,GAAGC,CAAM,CAClB,MAAE,CACA,MAAO,CAAC,CACV,CACF,CAOO,SAASC,EAAYC,EAAsE,CAChG,IAAMC,EAAkB,CAAC,EACrBC,EAAYF,EAChB,KAAOE,GAAQ,OAAOA,EAAK,MAAS,YAAY,CAC9C,IAAMC,EAAID,EAAK,KAAK,EAEhBA,EAAK,QAAQD,EAAM,QAAQE,CAAC,EAChCD,EAAOA,EAAK,OAEd,OAAOD,EAAM,KAAK,GAAG,CACvB,CAIA,IAAMG,EAAgB,IAAI,IAAI,CAAC,cAAe,aAAc,QAAS,MAAM,CAAC,EAErE,SAASC,EAAoBC,EAAuB,CACzD,MAAO,EAAQA,GAAS,CAACF,EAAc,IAAIE,CAAI,CACjD","names":["init_sqlite","existsSync","resolve","underTest","installRoot","dir","i","parent","today","now","recordSurfaceUse","kind","name","db","openDb","listSurfaceUse","opts","since","where","params","commandPath","cmd","parts","node","n","NOT_A_SURFACE","shouldRecordCommand","path"]}
@@ -1,8 +1,8 @@
1
- import{a as $e}from"./chunk-GTJIKXDB.js";import{q as zt}from"./chunk-S2GAEH2F.js";import{a as te,b as w}from"./chunk-BGG3ZSMW.js";import{b as qt}from"./chunk-DMHQIACQ.js";import{b as Kt,c as ve,e as U,f as B,h as Gt}from"./chunk-JIT5GPTX.js";import{t as Bt,u as Ht}from"./chunk-OJ7KM2UO.js";import{d as Ft,e as Ut}from"./chunk-AQASR6KR.js";import{A as Se,b as ke,v as Dt,x as ee,y as xe}from"./chunk-5PPMPCHG.js";import{a as jt,b as Vt,d as Wt}from"./chunk-Y4CYQV7G.js";import{a as Et,b as Tt}from"./chunk-SHEUCITK.js";import{g as Pt,h as Lt,i as Mt,k as Ot,l as Nt}from"./chunk-VEHTVYP6.js";import{q as Ct}from"./chunk-HYGMWCUU.js";import{a as Rt,b as _t}from"./chunk-HVZVFCJX.js";import{A as qr,ba as we,ia as $t,ja as At,ma as It,n as Q,o as wt,p as kt,q as Br,y as St,z as vt}from"./chunk-FJI5GRBH.js";import{a as be,h as Hr}from"./chunk-BRK6M6LA.js";import{f as xt,n as zr}from"./chunk-UIBUZ2N3.js";import{existsSync as Kr,readdirSync as Gr,readFileSync as Xr,statSync as Jr}from"fs";import{resolve as Yr}from"path";function Xt(t,e,n=Date.now(),i=7){let r=i*864e5,o=new Map;for(let s of e){let a=o.get(s.workflowId);a?a.push(s):o.set(s.workflowId,[s])}return t.map(s=>{let a=o.get(s.id)??[],c=a.filter(g=>n-g.at<=r),l=a.filter(g=>n-g.at>r&&n-g.at<=r*2),u=c.filter(g=>g.status==="failed").length,d=a.filter(g=>g.status==="paused").length,p=a.length?Math.max(...a.map(g=>g.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:s.id,name:s.name||s.id,state:f,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((s,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[s.state]-c[a.state]||(a.lastRunAt??0)-(s.lastRunAt??0)})}var ne=new Map;function ka(t,e=1e3){if(!Kr(t))return[];let n=Gr(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let s=Yr(t,o);return{path:s,mtime:Jr(s).mtimeMs}}).sort((o,s)=>s.mtime-o.mtime).slice(0,e),i=new Set(n.map(o=>o.path));for(let o of ne.keys())i.has(o)||ne.delete(o);let r=[];for(let{path:o,mtime:s}of n){let a=ne.get(o);if(a&&a.mtime===s){a.summary&&r.push(a.summary);continue}let c=Zr(o,s);ne.set(o,{mtime:s,summary:c}),c&&r.push(c)}return r}function Zr(t,e){try{let n=Xr(t,"utf-8").split(`
1
+ import{a as $e}from"./chunk-GTJIKXDB.js";import{q as zt}from"./chunk-S2GAEH2F.js";import{a as te,b as w}from"./chunk-BGG3ZSMW.js";import{b as qt}from"./chunk-WCXXXAHV.js";import{c as Kt,d as ve,f as U,g as B,i as Gt}from"./chunk-BDJWN3PL.js";import{t as Bt,u as Ht}from"./chunk-FSXWNVGL.js";import{d as Ft,e as Ut}from"./chunk-AQASR6KR.js";import{A as Se,b as ke,v as Dt,x as ee,y as xe}from"./chunk-RJBRYUKU.js";import{a as jt,b as Vt,d as Wt}from"./chunk-Y4CYQV7G.js";import{a as Et,b as Tt}from"./chunk-SHEUCITK.js";import{g as Pt,h as Lt,i as Mt,k as Ot,l as Nt}from"./chunk-IOYRRGK7.js";import{q as Ct}from"./chunk-B6OXEIOF.js";import{a as Rt,b as _t}from"./chunk-4PQREYBU.js";import{A as qr,ba as we,ia as $t,ja as At,ma as It,n as Q,o as wt,p as kt,q as Br,y as St,z as vt}from"./chunk-IMLLHT7U.js";import{a as be,h as Hr}from"./chunk-BRK6M6LA.js";import{f as xt,n as zr}from"./chunk-UIBUZ2N3.js";import{existsSync as Kr,readdirSync as Gr,readFileSync as Xr,statSync as Jr}from"fs";import{resolve as Yr}from"path";function Xt(t,e,n=Date.now(),i=7){let r=i*864e5,o=new Map;for(let s of e){let a=o.get(s.workflowId);a?a.push(s):o.set(s.workflowId,[s])}return t.map(s=>{let a=o.get(s.id)??[],c=a.filter(g=>n-g.at<=r),l=a.filter(g=>n-g.at>r&&n-g.at<=r*2),u=c.filter(g=>g.status==="failed").length,d=a.filter(g=>g.status==="paused").length,p=a.length?Math.max(...a.map(g=>g.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:s.id,name:s.name||s.id,state:f,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((s,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[s.state]-c[a.state]||(a.lastRunAt??0)-(s.lastRunAt??0)})}var ne=new Map;function ka(t,e=1e3){if(!Kr(t))return[];let n=Gr(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let s=Yr(t,o);return{path:s,mtime:Jr(s).mtimeMs}}).sort((o,s)=>s.mtime-o.mtime).slice(0,e),i=new Set(n.map(o=>o.path));for(let o of ne.keys())i.has(o)||ne.delete(o);let r=[];for(let{path:o,mtime:s}of n){let a=ne.get(o);if(a&&a.mtime===s){a.summary&&r.push(a.summary);continue}let c=Zr(o,s);ne.set(o,{mtime:s,summary:c}),c&&r.push(c)}return r}function Zr(t,e){try{let n=Xr(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let o=i.run?.status??"unknown";for(let s=n.length-1;s>=0;s--){let a=JSON.parse(n[s]),c=a.status??a.run?.status;if(c){o=c;break}}return{workflowId:r,status:o,at:e}}catch{return null}}var Qr={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},ei=(t,e,n)=>{try{return Ct(t,e,n)}catch{return null}},Jt=864e5;function $a(t){let e=t.now??Date.now(),n={...Qr,...t.thresholds},i=t.nextFire??ei,r=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Ae(a.nextRun)??Ae(i(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:si(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:c.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:Yt(u),sampledRuns:c.length,flags:[],attention:null};p.flags=Zt(p,u,a.schedule,l,null,e,n,i),r.push(Qt(p))}let o=new Map(Xt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),s=new Map;for(let a of t.workflowRuns){let c=s.get(a.workflowId);c?c.push(a):s.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(R=>R.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",p=(s.get(a.id)??[]).slice().sort((R,ye)=>ye.at-R.at),f=p.map(R=>({at:R.at,status:ri(R.status)})),g=f[0],h=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",D=typeof l.timezone=="string"?l.timezone:"UTC",N={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(y,k.text),timezone:D}:{event:$(typeof l.event=="string"?l.event:"",k.text),filters:oi(l.filter,a)},agent:ii(a),enabled:d,state:u,nextRunAt:h&&d&&y?Ae(i(y,new Date(e),D)):null,lastRun:g?{at:new Date(g.at).toISOString(),status:g.status}:null,lastSuccessAt:(()=>{let R=f.find(ye=>ye.status==="success");return R?new Date(R.at).toISOString():null})(),consecutiveFailures:Yt(f),sampledRuns:p.length,flags:[],attention:null},Z=Date.parse(a.updated||a.created||"");N.flags=h?Zt(N,f,y,D,Number.isFinite(Z)?Z:null,e,n,i):ti(N,o.get(a.id)?.state==="dormant",Number.isFinite(Z)?Z:null,e,n),r.push(Qt(N))}return r.sort(ni).slice(0,k.routines)}function Yt(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function Zt(t,e,n,i,r,o,s,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=tn(l,r,o,s);return p&&c.push(p),c}if(t.consecutiveFailures>=s.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let p=0;p<s.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&o>d.getTime()+s.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${s.missedFires} scheduled fires missed`}),c}function ti(t,e,n,i,r){let o=[],s=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=tn(s,n,i,r);return a&&o.push(a),o}return t.consecutiveFailures>=r.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),s===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function tn(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*Jt?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/Jt)} days`:"Disabled and never ran"}}function Qt(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var en={critical:0,warning:1,info:2};function ni(t,e){let n=t.attention?en[t.attention]:3,i=e.attention?en[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ri(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function ii(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function oi(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,o]of Object.entries(t)){let s=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];s.length&&n.push($(`${r}=${s.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Ae(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function si(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as oe,readdirSync as $i,readFileSync as Ai}from"fs";import{resolve as E}from"path";import{randomBytes as on}from"crypto";import{existsSync as ci,mkdirSync as li,readdirSync as ui,readFileSync as di,renameSync as sn,unlinkSync as pi,writeFileSync as fi}from"fs";import{resolve as an}from"path";function nn(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ai=t=>t.trim().split(`
3
3
  `).pop()?.slice(0,300)||"no output";async function rn(t,e,n,i=$e){let r=await i(t.bin,[...nn(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ai(r.stderr||r.stdout)}`}}async function Ra(t,e,n,i,r=$e){return(await r(t.bin,[...nn(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var gi=2e3,mi=t=>rn(t.wacli,t.to,t.text);function Ie(t){return an(t,".agentx","whatsapp-triage","drafts")}var hi=t=>/^[a-z0-9-]{8,64}$/.test(t),re=(t,e)=>an(Ie(t),`${e}.json`);function cn(t,e){li(Ie(t),{recursive:!0});let n=re(t,e.id),i=`${n}.${process.pid}.tmp`;fi(i,JSON.stringify(e,null,2)+`
4
4
  `,{mode:384}),sn(i,n)}function Pa(t,e,n=Date.now()){let i=e.text.trim().slice(0,gi);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${on(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return cn(t,r),r}function ie(t,e){if(!hi(e))return null;try{return JSON.parse(di(re(t,e),"utf-8"))}catch{return null}}function ln(t,e){let n=Ie(t);return ci(n)?ui(n).filter(i=>i.endsWith(".json")).map(i=>ie(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function un(t,e,n,i={}){let r=ie(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let o=`${re(t,e)}.${process.pid}.${on(3).toString("hex")}.claim`;try{sn(re(t,e),o)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let s={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")s.status="rejected";else{let a=await(i.send??mi)(r).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?s.status="sent":(s.status="failed",s.error=a.error)}cn(t,s);try{pi(o)}catch{}return s.status==="failed"?{ok:!1,error:s.error??"send failed"}:{ok:!0,draft:s}}import{mkdirSync as yi,readFileSync as bi,renameSync as wi,writeFileSync as ki}from"fs";import{resolve as xi}from"path";function dn(t){return xi(ve(t),"_state.json")}function A(t){try{let e=JSON.parse(bi(dn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function H(t,e){yi(ve(t),{recursive:!0});let n=dn(t),i=`${n}.${process.pid}.tmp`;ki(i,JSON.stringify(e,null,2)+`
5
- `),wi(i,n)}function pn(t,e,n,i=Date.now()){let r=A(t),o={};for(let[s,a]of Object.entries(r.snoozed))Date.parse(a)>i&&(o[s]=a);o[e]=n.toISOString(),H(t,{...r,snoozed:o})}function ja(t,e){H(t,{...A(t),lastDigest:e})}function fn(t,e,n,i=Date.now()){let r=A(t),o=new Set(n),s={};for(let[c,l]of Object.entries(r.popped??{}))o.has(c)&&(s[c]=l);s[e]=new Date(i).toISOString();let a=(r.wanted??[]).filter(c=>c!==e&&o.has(c));H(t,{...r,popped:s,wanted:a})}function gn(t,e){let n=A(t);H(t,{...n,wanted:[...(n.wanted??[]).filter(i=>i!==e),e]})}function Va(t,e=Date.now()){H(t,{...A(t),popped:{},passAt:new Date(e).toISOString()})}zr();qr();import{existsSync as Si,readFileSync as vi}from"fs";It();Hr();function mn(t){let e=Rt(t),n={};if(Si(e))try{n=$t(JSON.parse(vi(e,"utf-8")))}catch{n={}}let i=we.safeParse(n?.requests);return i.success?i.data:we.parse(void 0)}async function za(t,e={}){let n=(t.channels??[]).filter(i=>!be.has(i.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(i=>`"${i}"`).join(", ")}: use ${[...be].join(", ")}`}:_t(i=>{let r=i.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays"])t[o]!==void 0&&(r[o]=t[o])},{configPath:e.configPath,reload:e.reload})}var yn=["card","schedule","memory","wiki","whatsapp","request"],Ii=280;function L(t,e=Ii){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Re(t){if(t.configPath)return E(t.configPath);let e=[E(t.root,"agentx.json"),E(t.root,".agentx","config.json")];return e.find(n=>oe(n))??e[0]}function _e(t){return t.wikiDir?E(t.wikiDir):E(t.root,".agentx","wiki")}function Ri(t){return B(t.root,"pending").map(_i)}function _i(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.context||t.draft?{detail:L([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function Ci(t){let e=Re(t);if(!oe(e))return[];let n;try{n=JSON.parse(Ai(e,"utf-8"))}catch{return[]}let i=new Date(t.now??Date.now()),r=[];for(let[o,s]of Object.entries(n?.crons??{})){let a=s?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=s.timezone||"UTC",l=s.schedule?Pt(s.schedule):"",u=s.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${s.schedule})`:"no schedule",d=String(s.prompt??s.command??""),p=a.action==="create";r.push({key:`schedule:${o}`,kind:"schedule",title:p?`New schedule "${o}" for ${s.agent??"an agent"}`:`Delete schedule "${o}"`,ask:p?`Let ${s.agent??"the agent"} run this ${u}?`:`Remove the schedule "${o}" (${u})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:L(`${d}${p&&s.schedule?` \xB7 first run ${Mt(Lt(s.schedule,c,i),c)}`:""}`),more:"agentx schedule list"})}return r}function bn(t){let e=E(t,".agentx","memory");return oe(e)?$i(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Di(t){let e=bn(t.root);if(e.length===0)return[];let n=new ke(t.root),i=[];for(let r of e)for(let o of n.held(r))i.push({key:`memory:${r}/${o.id}`,kind:"memory",title:`Fact ${r} learned from ${o.source.channel}`,ask:`Let ${r} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:r,created_at:o.createdAt,detail:L(o.content),more:`agentx memory facts held --agent ${r}`});return i}function Ei(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function Ti(t){return Ut(_e(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:L(`${Ei(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function Pi(t){return ln(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:L(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function z(t){if(t.requests)return t.requests;if(E(t.root)!==process.cwd()||!oe(E(t.root,".agentx","db.sqlite")))return null;let e=xt({quiet:!0});if(!e)return null;let n=hn.get(e);return!n&&!St(e)?null:(n||hn.set(e,n=new vt(e)),n)}var hn=new WeakMap;function Li(t){let e=z(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:`Request not finished: ${L(n.text,80)}`,ask:`Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:L(`${n.attentionReason??"It needs attention"}. Asked on ${n.channel}: ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var wn={card:Ri,schedule:Ci,memory:Di,wiki:Ti,whatsapp:Pi,request:Li};function Mi(t,e){let n=t.expires?Date.parse(t.expires):1/0,i=e.expires?Date.parse(e.expires):1/0;return n!==i?n-i:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function oc(t,e={}){let n=t.now??Date.now(),{snoozed:i}=A(t.root),r=[],o=[],s=0;for(let a of e.kinds??yn){let c;try{c=wn[a](t)}catch(l){o.push({kind:a,error:String(l?.message??l).slice(0,200)});continue}for(let l of c){let u=i[l.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){s++;continue}l.snoozed_until=u}r.push(l)}}return r.sort(Mi),{items:r,snoozed:s,errors:o}}function Oi(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),i=t.slice(e+1);return!yn.includes(n)||!i?null:{kind:n,ref:i}}function Ni(t,e,n){switch(e){case"card":return U(t.root,n)?.status==="pending";case"wiki":return Ft(_e(t),n)?.status==="pending";case"whatsapp":return ie(t.root,n)?.status==="pending";default:return wn[e](t).some(i=>i.key===`${e}:${n}`)}}async function kn(t,e,n,i={}){let r=Oi(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:o,ref:s}=r,a=t.now??Date.now(),c=i.by??"operator";if(n==="later"){if(!Ni(t,o,s))return{ok:!1,error:`nothing waiting for "${e}"`};let u=i.laterHours&&i.laterHours>0?i.laterHours:24,d=new Date(a+u*36e5);return pn(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let l=n==="yes";switch(o){case"card":{let u=Gt(t.root,s,l?"yes":"no",{by:c,note:i.note,now:a,choice:i.choice,text:i.text});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${l?"yes":"no"}${u.card.choice?` (${u.card.choice})`:""}`}:u}case"schedule":{let u=await(l?Ot:Nt)(s,{configPath:Re(t),reload:t.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=s.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let d=s.slice(0,u),p=s.slice(u+1);if(!bn(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let f=new ke(t.root);return f.held(d).some(g=>g.id===p)?(f.review(d,p,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let u=_e(t),d=l?Bt(u,s,{by:c,force:i.force,now:a}):Ht(u,s,{by:c,reason:i.note,now:a});return d.ok?{ok:!0,message:l?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}case"whatsapp":{let u=await un(t.root,s,l?"yes":"no",{by:c,now:a,send:t.sendWhatsApp});return u.ok?{ok:!0,message:l?`${e}: sent to ${u.draft.chat_name||u.draft.to}`:`${e}: dropped, nothing sent`}:u}case"request":{let u=z(t),d=u?.get(s);return!u||!d||d.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?mn(Re(t)).enabled?(u.requestPickup(s,a),{ok:!0,message:`${e}: ${d.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(u.close(s,"dropped",i.note?.trim()||`dropped by ${c}`,a),{ok:!0,message:`${e}: dropped`})}}}var xn=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function ac(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/requests"||t.startsWith("/requests/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")}function cc(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)}function lc(t){return xn.has(t)}function uc(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(xn.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function dc(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let i of t.mesh?.peers||[])i.token&&n.add(i.token);return n}function pc(t,e,n=process.env){let i=o=>o.replace(/\/+$/,"");return(e===i(t.daemonUrl)?t.token:t.daemons.find(o=>i(o.url)===e)?.token)||n.MESH_TOKEN||void 0}function se(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function ji(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Vi(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function gc(t,e=Vi()){let n=se(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=ji(n),o=[se(t.host),se(t["x-forwarded-host"])].filter(Boolean).map(s=>s.toLowerCase());return r&&o.includes(r)?"same-origin":"foreign"}let i=se(t["sec-fetch-site"]).toLowerCase();return i==="cross-site"||i==="same-site"?"foreign":"none"}function mc(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as qn,mkdirSync as mo,readFileSync as ho,renameSync as yo,writeFileSync as bo}from"fs";import{homedir as wo}from"os";import{dirname as ko,join as xo}from"path";import{execFile as Ji,execFileSync as Yi}from"child_process";import{execFileSync as Wi}from"child_process";import{existsSync as vn,mkdirSync as Fi,readdirSync as Ui,readFileSync as $n,renameSync as Bi,writeFileSync as Hi}from"fs";import{homedir as An}from"os";import{join as De}from"path";var S="siri:",In="com.apple.ttsbundle.gryphon-neural_",Rn=t=>!!t&&t.startsWith(In),zi=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],qi=()=>{try{return Wi("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},Ce;function Ee(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&Ce!==void 0)return Ce;let{platform:n=process.platform,exists:i=vn,prefDomain:r=qi}=t,o=n==="darwin"&&zi.every(s=>i(s))&&r();return e||(Ce=o),o}var _n=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Cn={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},Te=t=>Cn[t.toLowerCase()]??null;function ae(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var Ki=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Gi(t){let e=new Map;for(let n of t)for(let[,i,r,o]of n.matchAll(Ki)){let s=`${i}-${r}`,a=`${In}${o}_${s}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:s,quality:"premium",gender:Cn[o]??null,siri:!0})}return[...e.values()]}function ce(t=_n,e={}){if(!Ee(e))return[];let n=[];for(let i of t){let r;try{r=Ui(i)}catch{continue}for(let o of r)try{n.push($n(De(i,o,"Info.plist"),"latin1"))}catch{}}return Gi(n)}var Sn=`#!/bin/sh
5
+ `),wi(i,n)}function pn(t,e,n,i=Date.now()){let r=A(t),o={};for(let[s,a]of Object.entries(r.snoozed))Date.parse(a)>i&&(o[s]=a);o[e]=n.toISOString(),H(t,{...r,snoozed:o})}function ja(t,e){H(t,{...A(t),lastDigest:e})}function fn(t,e,n,i=Date.now()){let r=A(t),o=new Set(n),s={};for(let[c,l]of Object.entries(r.popped??{}))o.has(c)&&(s[c]=l);s[e]=new Date(i).toISOString();let a=(r.wanted??[]).filter(c=>c!==e&&o.has(c));H(t,{...r,popped:s,wanted:a})}function gn(t,e){let n=A(t);H(t,{...n,wanted:[...(n.wanted??[]).filter(i=>i!==e),e]})}function Va(t,e=Date.now()){H(t,{...A(t),popped:{},passAt:new Date(e).toISOString()})}zr();qr();import{existsSync as Si,readFileSync as vi}from"fs";It();Hr();function mn(t){let e=Rt(t),n={};if(Si(e))try{n=$t(JSON.parse(vi(e,"utf-8")))}catch{n={}}let i=we.safeParse(n?.requests);return i.success?i.data:we.parse(void 0)}async function za(t,e={}){let n=(t.channels??[]).filter(i=>!be.has(i.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(i=>`"${i}"`).join(", ")}: use ${[...be].join(", ")}`}:_t(i=>{let r=i.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays"])t[o]!==void 0&&(r[o]=t[o])},{configPath:e.configPath,reload:e.reload})}var yn=["card","schedule","memory","wiki","whatsapp","request"],Ii=280;function L(t,e=Ii){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Re(t){if(t.configPath)return E(t.configPath);let e=[E(t.root,"agentx.json"),E(t.root,".agentx","config.json")];return e.find(n=>oe(n))??e[0]}function _e(t){return t.wikiDir?E(t.wikiDir):E(t.root,".agentx","wiki")}function Ri(t){return B(t.root,"pending").map(_i)}function _i(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:L([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function Ci(t){let e=Re(t);if(!oe(e))return[];let n;try{n=JSON.parse(Ai(e,"utf-8"))}catch{return[]}let i=new Date(t.now??Date.now()),r=[];for(let[o,s]of Object.entries(n?.crons??{})){let a=s?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=s.timezone||"UTC",l=s.schedule?Pt(s.schedule):"",u=s.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${s.schedule})`:"no schedule",d=String(s.prompt??s.command??""),p=a.action==="create";r.push({key:`schedule:${o}`,kind:"schedule",title:p?`New schedule "${o}" for ${s.agent??"an agent"}`:`Delete schedule "${o}"`,ask:p?`Let ${s.agent??"the agent"} run this ${u}?`:`Remove the schedule "${o}" (${u})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:L(`${d}${p&&s.schedule?` \xB7 first run ${Mt(Lt(s.schedule,c,i),c)}`:""}`),more:"agentx schedule list"})}return r}function bn(t){let e=E(t,".agentx","memory");return oe(e)?$i(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Di(t){let e=bn(t.root);if(e.length===0)return[];let n=new ke(t.root),i=[];for(let r of e)for(let o of n.held(r))i.push({key:`memory:${r}/${o.id}`,kind:"memory",title:`Fact ${r} learned from ${o.source.channel}`,ask:`Let ${r} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:r,created_at:o.createdAt,detail:L(o.content),more:`agentx memory facts held --agent ${r}`});return i}function Ei(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function Ti(t){return Ut(_e(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:L(`${Ei(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function Pi(t){return ln(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:L(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function z(t){if(t.requests)return t.requests;if(E(t.root)!==process.cwd()||!oe(E(t.root,".agentx","db.sqlite")))return null;let e=xt({quiet:!0});if(!e)return null;let n=hn.get(e);return!n&&!St(e)?null:(n||hn.set(e,n=new vt(e)),n)}var hn=new WeakMap;function Li(t){let e=z(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:`Request not finished: ${L(n.text,80)}`,ask:`Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:L(`${n.attentionReason??"It needs attention"}. Asked on ${n.channel}: ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var wn={card:Ri,schedule:Ci,memory:Di,wiki:Ti,whatsapp:Pi,request:Li};function Mi(t,e){let n=t.expires?Date.parse(t.expires):1/0,i=e.expires?Date.parse(e.expires):1/0;return n!==i?n-i:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function oc(t,e={}){let n=t.now??Date.now(),{snoozed:i}=A(t.root),r=[],o=[],s=0;for(let a of e.kinds??yn){let c;try{c=wn[a](t)}catch(l){o.push({kind:a,error:String(l?.message??l).slice(0,200)});continue}for(let l of c){let u=i[l.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){s++;continue}l.snoozed_until=u}r.push(l)}}return r.sort(Mi),{items:r,snoozed:s,errors:o}}function Oi(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),i=t.slice(e+1);return!yn.includes(n)||!i?null:{kind:n,ref:i}}function Ni(t,e,n){switch(e){case"card":return U(t.root,n)?.status==="pending";case"wiki":return Ft(_e(t),n)?.status==="pending";case"whatsapp":return ie(t.root,n)?.status==="pending";default:return wn[e](t).some(i=>i.key===`${e}:${n}`)}}async function kn(t,e,n,i={}){let r=Oi(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:o,ref:s}=r,a=t.now??Date.now(),c=i.by??"operator";if(n==="later"){if(!Ni(t,o,s))return{ok:!1,error:`nothing waiting for "${e}"`};let u=i.laterHours&&i.laterHours>0?i.laterHours:24,d=new Date(a+u*36e5);return pn(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let l=n==="yes";switch(o){case"card":{let u=Gt(t.root,s,l?"yes":"no",{by:c,note:i.note,now:a,choice:i.choice,text:i.text});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${l?"yes":"no"}${u.card.choice?` (${u.card.choice})`:""}`}:u}case"schedule":{let u=await(l?Ot:Nt)(s,{configPath:Re(t),reload:t.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=s.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let d=s.slice(0,u),p=s.slice(u+1);if(!bn(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let f=new ke(t.root);return f.held(d).some(g=>g.id===p)?(f.review(d,p,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let u=_e(t),d=l?Bt(u,s,{by:c,force:i.force,now:a}):Ht(u,s,{by:c,reason:i.note,now:a});return d.ok?{ok:!0,message:l?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}case"whatsapp":{let u=await un(t.root,s,l?"yes":"no",{by:c,now:a,send:t.sendWhatsApp});return u.ok?{ok:!0,message:l?`${e}: sent to ${u.draft.chat_name||u.draft.to}`:`${e}: dropped, nothing sent`}:u}case"request":{let u=z(t),d=u?.get(s);return!u||!d||d.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?mn(Re(t)).enabled?(u.requestPickup(s,a),{ok:!0,message:`${e}: ${d.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(u.close(s,"dropped",i.note?.trim()||`dropped by ${c}`,a),{ok:!0,message:`${e}: dropped`})}}}var xn=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function ac(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/requests"||t.startsWith("/requests/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")}function cc(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)}function lc(t){return xn.has(t)}function uc(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(xn.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function dc(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let i of t.mesh?.peers||[])i.token&&n.add(i.token);return n}function pc(t,e,n=process.env){let i=o=>o.replace(/\/+$/,"");return(e===i(t.daemonUrl)?t.token:t.daemons.find(o=>i(o.url)===e)?.token)||n.MESH_TOKEN||void 0}function se(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function ji(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Vi(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function gc(t,e=Vi()){let n=se(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=ji(n),o=[se(t.host),se(t["x-forwarded-host"])].filter(Boolean).map(s=>s.toLowerCase());return r&&o.includes(r)?"same-origin":"foreign"}let i=se(t["sec-fetch-site"]).toLowerCase();return i==="cross-site"||i==="same-site"?"foreign":"none"}function mc(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{existsSync as qn,mkdirSync as mo,readFileSync as ho,renameSync as yo,writeFileSync as bo}from"fs";import{homedir as wo}from"os";import{dirname as ko,join as xo}from"path";import{execFile as Ji,execFileSync as Yi}from"child_process";import{execFileSync as Wi}from"child_process";import{existsSync as vn,mkdirSync as Fi,readdirSync as Ui,readFileSync as $n,renameSync as Bi,writeFileSync as Hi}from"fs";import{homedir as An}from"os";import{join as De}from"path";var S="siri:",In="com.apple.ttsbundle.gryphon-neural_",Rn=t=>!!t&&t.startsWith(In),zi=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],qi=()=>{try{return Wi("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},Ce;function Ee(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&Ce!==void 0)return Ce;let{platform:n=process.platform,exists:i=vn,prefDomain:r=qi}=t,o=n==="darwin"&&zi.every(s=>i(s))&&r();return e||(Ce=o),o}var _n=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Cn={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},Te=t=>Cn[t.toLowerCase()]??null;function ae(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var Ki=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Gi(t){let e=new Map;for(let n of t)for(let[,i,r,o]of n.matchAll(Ki)){let s=`${i}-${r}`,a=`${In}${o}_${s}_premium`;e.has(a)||e.set(a,{id:a,name:o[0].toUpperCase()+o.slice(1),locale:s,quality:"premium",gender:Cn[o]??null,siri:!0})}return[...e.values()]}function ce(t=_n,e={}){if(!Ee(e))return[];let n=[];for(let i of t){let r;try{r=Ui(i)}catch{continue}for(let o of r)try{n.push($n(De(i,o,"Info.plist"),"latin1"))}catch{}}return Gi(n)}var Sn=`#!/bin/sh
6
6
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
7
7
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
8
8
  # the OS default for it; any other id is
@@ -479,4 +479,4 @@ Document the arguments, commands, or files the skill expects. Example:
479
479
  claude-code ${bt(t)} --arg value
480
480
  \`\`\`
481
481
  `}It();var Vr={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Wr(t){return{...Vr,...t??{},regions:{...t?.regions??{}},buffer:{...Vr.buffer,...t?.buffer??{}}}}function Wu(t){try{return Wr(At(t).screen)}catch{return Wr(void 0)}}var ya=/^[a-z][\w-]*$/,Fr=["window","screen","menubar","notifications"];function Y(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var he=(t,e)=>Y(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Ur(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Fu(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=he(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=he(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=he(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Y(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Y(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[o,s]of Object.entries(e.regions)){if(!ya.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);s===null?delete r[o]:r[o]=Ur(s)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,o={...n.buffer??{}};"enabled"in r&&(o.enabled=!!r.enabled),"seconds"in r&&(o.seconds=Y(r.seconds,"buffer.seconds",s=>s>0&&s<=120,"above 0 and at most 120")),"fps"in r&&(o.fps=Y(r.fps,"buffer.fps",s=>s>0&&s<=10,"above 0 and at most 10")),"maxPixels"in r&&(o.maxPixels=he(r.maxPixels,"buffer.maxPixels")),"region"in r&&(o.region=String(r.region).trim()),n.buffer=o}let i=n.buffer?.region;if(i!==void 0&&!Fr.includes(i)&&!n.regions?.[i])try{Ur(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Fr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Xt as a,ka as b,Ze as c,Fo as d,Uo as e,el as f,tl as g,nl as h,er as i,il as j,sl as k,T as l,tr as m,k as n,$a as o,Ra as p,mi as q,Pa as r,un as s,A as t,ja as u,Va as v,mn as w,za as x,z as y,oc as z,kn as A,nr as B,ll as C,pl as D,hr as E,Vl as F,Wl as G,ql as H,Ls as I,Kl as J,ac as K,cc as L,lc as M,uc as N,dc as O,pc as P,gc as Q,mc as R,$c as S,Le as T,Ac as U,Ic as V,q as W,K as X,Ws as Y,nu as Z,ru as _,iu as $,ou as aa,st as ba,su as ca,Ne as da,je as ea,de as fa,so as ga,co as ha,Ec as ia,We as ja,Fe as ka,lo as la,uo as ma,Wn as na,Hn as oa,Tc as pa,go as qa,Pc as ra,So as sa,Ao as ta,Ue as ua,Ro as va,zn as wa,P as xa,_r as ya,Cr as za,Dr as Aa,pu as Ba,Xs as Ca,Tr as Da,Pr as Ea,vu as Fa,$u as Ga,da as Ha,Au as Ia,Mr as Ja,pe as Ka,zc as La,Yn as Ma,Be as Na,Je as Oa,Zc as Pa,Cu as Qa,Du as Ra,Eu as Sa,Tu as Ta,Pu as Ua,Lu as Va,Mu as Wa,Ou as Xa,Nu as Ya,Vr as Za,Wr as _a,Wu as $a,Fr as ab,Fu as bb};
482
- //# sourceMappingURL=chunk-2WK5A3UV.js.map
482
+ //# sourceMappingURL=chunk-5PR6DZYW.js.map