agentix-cli 0.106.0 → 0.107.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 (119) hide show
  1. package/dist/{App-PVMJEC3G.js → App-GRPPB7IF.js} +2 -2
  2. package/dist/{ChatApp-GWIOURQL.js → ChatApp-ZEIEXPOB.js} +2 -2
  3. package/dist/{agent-IOHJGUZT.js → agent-J22ODKSX.js} +2 -2
  4. package/dist/{board-dashboard-OA4WFL3D.js → board-dashboard-DUT3XBS7.js} +4 -4
  5. package/dist/chunk-36AXN6ZB.js +11 -0
  6. package/dist/chunk-36AXN6ZB.js.map +1 -0
  7. package/dist/{chunk-QCKUXJJ3.js → chunk-3RLYCNGP.js} +2 -2
  8. package/dist/{chunk-4MESMUND.js → chunk-4YBFKN3B.js} +2 -2
  9. package/dist/{chunk-GGB5JMII.js → chunk-55MUAKXA.js} +2 -2
  10. package/dist/{chunk-CHQ5Q4QO.js → chunk-CXCXMOTB.js} +2 -2
  11. package/dist/chunk-FQGEDMG6.js +2 -0
  12. package/dist/chunk-FQGEDMG6.js.map +1 -0
  13. package/dist/{chunk-SGOXLRY4.js → chunk-GFON223J.js} +2 -2
  14. package/dist/{chunk-ZROS7GX2.js → chunk-H5ZNKPXN.js} +2 -2
  15. package/dist/{chunk-UW6RUGNV.js → chunk-IRH2O2QB.js} +2 -2
  16. package/dist/{chunk-MTP2RH3P.js → chunk-JUJPQWLG.js} +2 -2
  17. package/dist/{chunk-5D5NKZSD.js → chunk-JYFE6SQU.js} +2 -2
  18. package/dist/{chunk-H5LQXHQQ.js → chunk-M6NIPFRY.js} +11 -11
  19. package/dist/chunk-M6NIPFRY.js.map +1 -0
  20. package/dist/{chunk-UZ5Q6Q2X.js → chunk-N72AJ2LS.js} +187 -187
  21. package/dist/chunk-N72AJ2LS.js.map +1 -0
  22. package/dist/{chunk-W3LSDADF.js → chunk-NL6JSS4E.js} +2 -2
  23. package/dist/{chunk-HRX7FIOO.js → chunk-O5BBV4ZV.js} +2 -2
  24. package/dist/{chunk-VYSFOONA.js → chunk-OTCF46CF.js} +2 -2
  25. package/dist/{chunk-CZFGADZ2.js → chunk-PEDNM2FA.js} +2 -2
  26. package/dist/{chunk-YZJCOWHU.js → chunk-S4RQ6Q2B.js} +2 -2
  27. package/dist/chunk-UDJAODAB.js +100 -0
  28. package/dist/chunk-UDJAODAB.js.map +1 -0
  29. package/dist/{chunk-ZD5ECP5D.js → chunk-UEOG3H25.js} +2 -2
  30. package/dist/chunk-UIDHTIPG.js +153 -0
  31. package/dist/chunk-UIDHTIPG.js.map +1 -0
  32. package/dist/{chunk-3IEFHOPH.js → chunk-UOOFNFEO.js} +2 -2
  33. package/dist/{chunk-DJMK22SB.js → chunk-XQMLRZHY.js} +2 -2
  34. package/dist/cli.js +1 -1
  35. package/dist/{client-DLRQIQZU.js → client-WTC7P6PE.js} +2 -2
  36. package/dist/{config-32FKG36S.js → config-WG62KB23.js} +2 -2
  37. package/dist/config-mutator-7REOEXW4.js +2 -0
  38. package/dist/{doctor-ALOXJM5G.js → doctor-XDR22CFD.js} +2 -2
  39. package/dist/index.d.ts +197 -0
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/{program-DSUZFBJZ.js → program-PZO6XJYZ.js} +109 -109
  43. package/dist/program-PZO6XJYZ.js.map +1 -0
  44. package/dist/{promote-SXH7DKMC.js → promote-YEODWQX2.js} +2 -2
  45. package/dist/{query-WKBSHVWZ.js → query-DC3O3QBJ.js} +2 -2
  46. package/dist/registry-PT5SRRZA.js +2 -0
  47. package/dist/{request-planner-GV5NAXQ5.js → request-planner-EP2XYPKZ.js} +2 -2
  48. package/dist/{review-candidates-AWIUSB3O.js → review-candidates-VKH372WW.js} +2 -2
  49. package/dist/routing-OOIZ6433.js +2 -0
  50. package/dist/schedule-tool-W45LNZGX.js +2 -0
  51. package/dist/scheduler-YXU4G5NH.js +2 -0
  52. package/dist/{seat-EQKPGMJE.js → seat-AGGELF3C.js} +2 -2
  53. package/dist/{select-RJCBMM3O.js → select-6SXEU2NV.js} +2 -2
  54. package/dist/{set-enabled-ADQH7VKE.js → set-enabled-GLWP7YDW.js} +2 -2
  55. package/dist/token-tracker-W7DFDEFN.js +2 -0
  56. package/dist/{tool-K4MU42KH.js → tool-23P66PKZ.js} +2 -2
  57. package/dist/{tool-JPHWWTZI.js → tool-UF6LOS6K.js} +2 -2
  58. package/dist/usage-channels-KBLEC4NE.js +2 -0
  59. package/dist/usage-channels-KBLEC4NE.js.map +1 -0
  60. package/dist/wiki-6SCKSY4I.js +2 -0
  61. package/dist/workspace-setup-EA3G42NY.js +2 -0
  62. package/dist/workspace-setup-EA3G42NY.js.map +1 -0
  63. package/package.json +1 -1
  64. package/dist/chunk-DWADWDMU.js +0 -96
  65. package/dist/chunk-DWADWDMU.js.map +0 -1
  66. package/dist/chunk-H5LQXHQQ.js.map +0 -1
  67. package/dist/chunk-PWTSY77F.js +0 -2
  68. package/dist/chunk-PWTSY77F.js.map +0 -1
  69. package/dist/chunk-UZ5Q6Q2X.js.map +0 -1
  70. package/dist/chunk-YSMPXFQR.js +0 -154
  71. package/dist/chunk-YSMPXFQR.js.map +0 -1
  72. package/dist/config-mutator-2VM2FWRF.js +0 -2
  73. package/dist/program-DSUZFBJZ.js.map +0 -1
  74. package/dist/registry-DAWQT4D4.js +0 -2
  75. package/dist/routing-35ETOM24.js +0 -2
  76. package/dist/schedule-tool-BXRRN3IE.js +0 -2
  77. package/dist/scheduler-PIZG2JA4.js +0 -2
  78. package/dist/wiki-RHHHYUTK.js +0 -2
  79. package/dist/workspace-setup-42ARC42I.js +0 -2
  80. /package/dist/{App-PVMJEC3G.js.map → App-GRPPB7IF.js.map} +0 -0
  81. /package/dist/{ChatApp-GWIOURQL.js.map → ChatApp-ZEIEXPOB.js.map} +0 -0
  82. /package/dist/{agent-IOHJGUZT.js.map → agent-J22ODKSX.js.map} +0 -0
  83. /package/dist/{board-dashboard-OA4WFL3D.js.map → board-dashboard-DUT3XBS7.js.map} +0 -0
  84. /package/dist/{chunk-QCKUXJJ3.js.map → chunk-3RLYCNGP.js.map} +0 -0
  85. /package/dist/{chunk-4MESMUND.js.map → chunk-4YBFKN3B.js.map} +0 -0
  86. /package/dist/{chunk-GGB5JMII.js.map → chunk-55MUAKXA.js.map} +0 -0
  87. /package/dist/{chunk-CHQ5Q4QO.js.map → chunk-CXCXMOTB.js.map} +0 -0
  88. /package/dist/{chunk-SGOXLRY4.js.map → chunk-GFON223J.js.map} +0 -0
  89. /package/dist/{chunk-ZROS7GX2.js.map → chunk-H5ZNKPXN.js.map} +0 -0
  90. /package/dist/{chunk-UW6RUGNV.js.map → chunk-IRH2O2QB.js.map} +0 -0
  91. /package/dist/{chunk-MTP2RH3P.js.map → chunk-JUJPQWLG.js.map} +0 -0
  92. /package/dist/{chunk-5D5NKZSD.js.map → chunk-JYFE6SQU.js.map} +0 -0
  93. /package/dist/{chunk-W3LSDADF.js.map → chunk-NL6JSS4E.js.map} +0 -0
  94. /package/dist/{chunk-HRX7FIOO.js.map → chunk-O5BBV4ZV.js.map} +0 -0
  95. /package/dist/{chunk-VYSFOONA.js.map → chunk-OTCF46CF.js.map} +0 -0
  96. /package/dist/{chunk-CZFGADZ2.js.map → chunk-PEDNM2FA.js.map} +0 -0
  97. /package/dist/{chunk-YZJCOWHU.js.map → chunk-S4RQ6Q2B.js.map} +0 -0
  98. /package/dist/{chunk-ZD5ECP5D.js.map → chunk-UEOG3H25.js.map} +0 -0
  99. /package/dist/{chunk-3IEFHOPH.js.map → chunk-UOOFNFEO.js.map} +0 -0
  100. /package/dist/{chunk-DJMK22SB.js.map → chunk-XQMLRZHY.js.map} +0 -0
  101. /package/dist/{client-DLRQIQZU.js.map → client-WTC7P6PE.js.map} +0 -0
  102. /package/dist/{config-32FKG36S.js.map → config-WG62KB23.js.map} +0 -0
  103. /package/dist/{config-mutator-2VM2FWRF.js.map → config-mutator-7REOEXW4.js.map} +0 -0
  104. /package/dist/{doctor-ALOXJM5G.js.map → doctor-XDR22CFD.js.map} +0 -0
  105. /package/dist/{promote-SXH7DKMC.js.map → promote-YEODWQX2.js.map} +0 -0
  106. /package/dist/{query-WKBSHVWZ.js.map → query-DC3O3QBJ.js.map} +0 -0
  107. /package/dist/{registry-DAWQT4D4.js.map → registry-PT5SRRZA.js.map} +0 -0
  108. /package/dist/{request-planner-GV5NAXQ5.js.map → request-planner-EP2XYPKZ.js.map} +0 -0
  109. /package/dist/{review-candidates-AWIUSB3O.js.map → review-candidates-VKH372WW.js.map} +0 -0
  110. /package/dist/{routing-35ETOM24.js.map → routing-OOIZ6433.js.map} +0 -0
  111. /package/dist/{schedule-tool-BXRRN3IE.js.map → schedule-tool-W45LNZGX.js.map} +0 -0
  112. /package/dist/{scheduler-PIZG2JA4.js.map → scheduler-YXU4G5NH.js.map} +0 -0
  113. /package/dist/{seat-EQKPGMJE.js.map → seat-AGGELF3C.js.map} +0 -0
  114. /package/dist/{select-RJCBMM3O.js.map → select-6SXEU2NV.js.map} +0 -0
  115. /package/dist/{set-enabled-ADQH7VKE.js.map → set-enabled-GLWP7YDW.js.map} +0 -0
  116. /package/dist/{wiki-RHHHYUTK.js.map → token-tracker-W7DFDEFN.js.map} +0 -0
  117. /package/dist/{tool-K4MU42KH.js.map → tool-23P66PKZ.js.map} +0 -0
  118. /package/dist/{tool-JPHWWTZI.js.map → tool-UF6LOS6K.js.map} +0 -0
  119. /package/dist/{workspace-setup-42ARC42I.js.map → wiki-6SCKSY4I.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/daemon/token-tracker.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Token usage tracker ---\n// Tracks token usage per agent per day with cache-aware, tier-aware cost\n// calculation. Persisted to .agentx/usage/{YYYY-MM-DD}.json.\n//\n// Design notes:\n// - Pricing is per-model-FAMILY (opus/sonnet/haiku). Exact model name\n// variants map via getModelFamily(). Override the table by dropping\n// .agentx/pricing/custom.json (same shape) — merged over defaults at\n// construction, lets operators adjust without a rebuild.\n// - Anthropic bills 1.5× input/output when a single request's total input\n// (input + cacheCreate + cacheRead) exceeds 200K tokens. We split each\n// recorded task into tier1/tier2 buckets and bill them separately so\n// long-context sessions are not undercounted.\n// - Per-channel breakdowns let operators see \"GitLab drove 70% of today's\n// spend\" — the lever for channel-specific session + context tuning.\n// - Session tracking (unique chatId:channel pairs seen today per agent)\n// gives an avg-tasks-per-session proxy — when it spikes, it's usually\n// retry/clarification chains, a signal the context budget or model\n// capability is under-sized for that traffic.\n\n// Anthropic pricing per million tokens (as of April 2026, 5-min ephemeral).\n// Keys here must match getModelFamily() output.\n//\n// IMPORTANT: Opus 4.6 is 3× cheaper than Opus 4.1. Haiku 4.5 is more expensive\n// than Haiku 3.5. Our getModelFamily() resolves the exact version so the cost\n// report matches what Anthropic actually bills. Source: LiteLLM pricing cache\n// at ~/.cache/codeburn/litellm-pricing.json + codeburn/src/models.ts.\n//\n// Cache multipliers (consistent across all models):\n// cache write (5-min ephemeral) = 1.25 × input\n// cache read = 0.10 × input\nexport const CACHE_AWARE_PRICING: Record<string, { input: number; output: number; cacheRead: number; cacheCreate: number }> = {\n // Fable 5.1 / 5 — $10/$50 per MTok\n \"claude-fable\": { input: 10, output: 50, cacheRead: 1, cacheCreate: 12.5 },\n // Opus 5 / 4.8 / 4.7 / 4.6 / 4.5 — $5/$25 per MTok\n \"claude-opus-5\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-8\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-7\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-6\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n \"claude-opus-4-5\": { input: 5, output: 25, cacheRead: 0.5, cacheCreate: 6.25 },\n // Opus 4.1 and earlier — $15/$75 per MTok (legacy, keep for historical runs)\n \"claude-opus\": { input: 15, output: 75, cacheRead: 1.5, cacheCreate: 18.75 },\n // Sonnet 5 — $2/$10 per MTok\n \"claude-sonnet-5\": { input: 2, output: 10, cacheRead: 0.2, cacheCreate: 2.5 },\n // Sonnet 4.6 / 4.5 — $3/$15 per MTok\n \"claude-sonnet\": { input: 3, output: 15, cacheRead: 0.3, cacheCreate: 3.75 },\n // Haiku 4.5 — $1/$5 per MTok (more expensive than Haiku 3.5)\n \"claude-haiku\": { input: 1, output: 5, cacheRead: 0.1, cacheCreate: 1.25 },\n}\n\n/** Per-request input size (input + cacheCreate + cacheRead) above this\n * threshold triggers Anthropic's extended-context tier: all four rates\n * get multiplied. Applies to Opus 4.x and Sonnet 4.x 1M variants. */\nexport const CONTEXT_TIER_THRESHOLD = 200_000\nexport const TIER2_MULTIPLIER = 1.5\n\n/** Map a model id onto a pricing family.\n *\n * Version matching is explicit and most-specific-first. Getting this wrong\n * is not a rounding error: an Opus id that falls through to the legacy\n * 4.1 family is priced at $15/$75 instead of $5/$25 and every cost figure\n * derived from it is inflated 3×. That is exactly what happened to the\n * whole fleet once it moved to claude-opus-5 — \"opus\" matched, no version\n * branch did, and the legacy fallback caught it silently.\n *\n * So an UNRECOGNISED Opus version now resolves to the current $5/$25 tier\n * rather than the legacy one. Every Opus from 4.5 onward has been $5/$25;\n * treating tomorrow's release as 4.1-era is the more likely and more\n * expensive mistake, and the genuinely old ids still match explicitly. */\nexport function getModelFamily(model: string): string {\n const lower = model.toLowerCase()\n const has = (...needles: string[]) => needles.some((n) => lower.includes(n))\n\n if (has(\"fable\", \"mythos\")) return \"claude-fable\"\n\n if (lower.includes(\"opus\")) {\n if (has(\"opus-5\", \"opus5\", \"opus-5-\")) return \"claude-opus-5\"\n if (has(\"4-8\", \"4.8\")) return \"claude-opus-4-8\"\n if (has(\"4-7\", \"4.7\")) return \"claude-opus-4-7\"\n if (has(\"4-6\", \"4.6\")) return \"claude-opus-4-6\"\n if (has(\"4-5\", \"4.5\")) return \"claude-opus-4-5\"\n // Named legacy generations, which really are $15/$75.\n if (has(\"4-1\", \"4.1\", \"opus-3\", \"opus3\", \"-3-\")) return \"claude-opus\"\n // Unknown/new Opus — assume the current tier, not the legacy one.\n return \"claude-opus-5\"\n }\n\n if (lower.includes(\"haiku\")) return \"claude-haiku\"\n if (has(\"sonnet-5\", \"sonnet5\")) return \"claude-sonnet-5\"\n return \"claude-sonnet\"\n}\n\nexport interface ChannelUsage {\n tasks: number\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheCreateTokens: number\n tier2InputTokens: number\n tier2OutputTokens: number\n tier2CacheReadTokens: number\n tier2CacheCreateTokens: number\n totalDuration: number\n errors: number\n}\n\nexport interface AgentUsage {\n tasks: number\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheCreateTokens: number\n /** Tokens from requests whose input crossed CONTEXT_TIER_THRESHOLD (billed at\n * TIER2_MULTIPLIER × normal rate). Kept separate from the tier1 buckets so\n * cost math stays honest when a session accumulates past 200K. */\n tier2InputTokens?: number\n tier2OutputTokens?: number\n tier2CacheReadTokens?: number\n tier2CacheCreateTokens?: number\n totalDuration: number\n errors: number\n model?: string\n /** Per-channel breakdown so we can attribute cost to Telegram vs GitLab vs WhatsApp. */\n byChannel?: Record<string, ChannelUsage>\n /** Unique session identifiers (channel:chatId) this agent participated in\n * today. Used to derive avg tasks/session. Capped at 500 entries to keep\n * the daily JSON small. */\n sessionKeys?: string[]\n}\n\nexport interface DailyUsage {\n date: string\n agents: Record<string, AgentUsage>\n}\n\nexport interface DailyReport {\n date: string\n totalTasks: number\n totalInput: number\n totalOutput: number\n totalCacheRead: number\n totalCacheCreate: number\n totalCost: number\n topAgent: string\n topCost: number\n agentCosts: Record<string, number>\n /** Per-agent avg tasks/session — high values suggest retry chains. */\n agentSessionStats: Record<string, { sessions: number; avgTasksPerSession: number }>\n /** Aggregate cost by channel across all agents. */\n byChannel: Record<string, number>\n}\n\n/** Shape of a per-request usage report coming from the runtime. Keeps the\n * record() signature tidy and lets callers opt into tier2 accounting. */\nexport interface TaskUsage {\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheCreateTokens: number\n}\n\n/** Split a TaskUsage into tier1 and tier2 buckets using the same\n * CONTEXT_TIER_THRESHOLD that record() applies. Output inherits the\n * tier of its request. Returned as a flat object so callers can spread\n * it directly into bus payloads or DB writes. */\nexport function splitTaskUsageByTier(u: TaskUsage): {\n inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheCreateTokens: number\n tier2InputTokens: number; tier2OutputTokens: number; tier2CacheReadTokens: number; tier2CacheCreateTokens: number\n} {\n const totalInput = u.inputTokens + u.cacheReadTokens + u.cacheCreateTokens\n if (totalInput > CONTEXT_TIER_THRESHOLD) {\n return {\n inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0,\n tier2InputTokens: u.inputTokens, tier2OutputTokens: u.outputTokens,\n tier2CacheReadTokens: u.cacheReadTokens, tier2CacheCreateTokens: u.cacheCreateTokens,\n }\n }\n return {\n inputTokens: u.inputTokens, outputTokens: u.outputTokens,\n cacheReadTokens: u.cacheReadTokens, cacheCreateTokens: u.cacheCreateTokens,\n tier2InputTokens: 0, tier2OutputTokens: 0, tier2CacheReadTokens: 0, tier2CacheCreateTokens: 0,\n }\n}\n\nconst SESSION_KEYS_MAX = 500\nconst PRICING_OVERRIDE_PATH = \".agentx/pricing/custom.json\"\n\nexport class TokenTracker {\n private dir: string\n private cache: DailyUsage | null = null\n private pricing: typeof CACHE_AWARE_PRICING\n\n constructor(baseDir: string = resolve(process.cwd(), \".agentx/usage\")) {\n this.dir = baseDir\n mkdirSync(this.dir, { recursive: true })\n this.pricing = loadPricingWithOverrides()\n }\n\n /** Returns the active pricing table (hardcoded defaults with any per-model\n * overrides merged in). Useful for UI / debugging. */\n getPricing(): typeof CACHE_AWARE_PRICING {\n return this.pricing\n }\n\n /**\n * Calculate cost for a slice of usage. Accepts either a full AgentUsage or\n * a narrowed ChannelUsage — both expose the same token buckets we price on.\n * Tier2 tokens are billed at TIER2_MULTIPLIER × the normal rate.\n */\n static calculateCost(usage: AgentUsage | ChannelUsage, model?: string, pricingTable: typeof CACHE_AWARE_PRICING = CACHE_AWARE_PRICING): number {\n const family = getModelFamily(model || (usage as AgentUsage).model || \"claude-sonnet\")\n const p = pricingTable[family] || pricingTable[\"claude-sonnet\"]\n const tier2In = (usage as any).tier2InputTokens || 0\n const tier2Out = (usage as any).tier2OutputTokens || 0\n const tier2CR = (usage as any).tier2CacheReadTokens || 0\n const tier2CW = (usage as any).tier2CacheCreateTokens || 0\n\n const tier1 =\n ((usage.inputTokens || 0) / 1_000_000) * p.input +\n ((usage.outputTokens || 0) / 1_000_000) * p.output +\n ((usage.cacheReadTokens || 0) / 1_000_000) * p.cacheRead +\n ((usage.cacheCreateTokens || 0) / 1_000_000) * p.cacheCreate\n\n const tier2 =\n (tier2In / 1_000_000) * p.input +\n (tier2Out / 1_000_000) * p.output +\n (tier2CR / 1_000_000) * p.cacheRead +\n (tier2CW / 1_000_000) * p.cacheCreate\n\n return tier1 + tier2 * TIER2_MULTIPLIER\n }\n\n /**\n * Instance-level cost calculation — uses the tracker's resolved pricing\n * table so any custom override file is honored. Prefer this over the\n * static variant when available.\n */\n cost(usage: AgentUsage | ChannelUsage, model?: string): number {\n return TokenTracker.calculateCost(usage, model, this.pricing)\n }\n\n /**\n * Record a task execution with real or estimated token counts.\n *\n * `channel` attributes the cost to a surface (telegram/gitlab/whatsapp/cron).\n * `sessionKey` is an opaque \"this chat on this day\" identifier — we use it\n * to count unique sessions so an avg-tasks-per-session metric falls out.\n */\n record(\n agentId: string,\n duration: number,\n realUsage?: TaskUsage,\n messageLength?: number,\n responseLength?: number,\n error?: boolean,\n model?: string,\n channel?: string,\n sessionKey?: string,\n ): void {\n const daily = this.today()\n const agent = daily.agents[agentId] || {\n tasks: 0, inputTokens: 0, outputTokens: 0,\n cacheReadTokens: 0, cacheCreateTokens: 0,\n tier2InputTokens: 0, tier2OutputTokens: 0,\n tier2CacheReadTokens: 0, tier2CacheCreateTokens: 0,\n totalDuration: 0, errors: 0, byChannel: {}, sessionKeys: [],\n }\n\n agent.tasks++\n agent.totalDuration += duration\n if (model) agent.model = model\n\n // Split this request into tier1/tier2 based on its TOTAL input size\n // (input + cacheCreate + cacheRead). Output inherits the tier of its\n // request. Estimated paths (no realUsage) are always tier1 — they're\n // too small to reach the threshold.\n let i1 = 0, o1 = 0, cr1 = 0, cw1 = 0, i2 = 0, o2 = 0, cr2 = 0, cw2 = 0\n if (realUsage) {\n const totalInput = realUsage.inputTokens + realUsage.cacheReadTokens + realUsage.cacheCreateTokens\n if (totalInput > CONTEXT_TIER_THRESHOLD) {\n i2 = realUsage.inputTokens\n o2 = realUsage.outputTokens\n cr2 = realUsage.cacheReadTokens\n cw2 = realUsage.cacheCreateTokens\n } else {\n i1 = realUsage.inputTokens\n o1 = realUsage.outputTokens\n cr1 = realUsage.cacheReadTokens\n cw1 = realUsage.cacheCreateTokens\n }\n } else if (messageLength !== undefined && responseLength !== undefined) {\n i1 = Math.ceil(messageLength / 4)\n o1 = Math.ceil(responseLength / 4)\n }\n\n agent.inputTokens += i1\n agent.outputTokens += o1\n agent.cacheReadTokens += cr1\n agent.cacheCreateTokens += cw1\n agent.tier2InputTokens = (agent.tier2InputTokens || 0) + i2\n agent.tier2OutputTokens = (agent.tier2OutputTokens || 0) + o2\n agent.tier2CacheReadTokens = (agent.tier2CacheReadTokens || 0) + cr2\n agent.tier2CacheCreateTokens = (agent.tier2CacheCreateTokens || 0) + cw2\n\n if (error) agent.errors++\n\n // Per-channel attribution. Unknown channel falls into \"other\".\n if (!agent.byChannel) agent.byChannel = {}\n const chKey = (channel || \"other\").toLowerCase()\n const ch = agent.byChannel[chKey] || {\n tasks: 0, inputTokens: 0, outputTokens: 0,\n cacheReadTokens: 0, cacheCreateTokens: 0,\n tier2InputTokens: 0, tier2OutputTokens: 0,\n tier2CacheReadTokens: 0, tier2CacheCreateTokens: 0,\n totalDuration: 0, errors: 0,\n }\n ch.tasks++\n ch.totalDuration += duration\n ch.inputTokens += i1; ch.outputTokens += o1\n ch.cacheReadTokens += cr1; ch.cacheCreateTokens += cw1\n ch.tier2InputTokens += i2; ch.tier2OutputTokens += o2\n ch.tier2CacheReadTokens += cr2; ch.tier2CacheCreateTokens += cw2\n if (error) ch.errors++\n agent.byChannel[chKey] = ch\n\n // Session tracking — dedup sessions by opaque key (normally channel:chatId).\n if (sessionKey) {\n if (!agent.sessionKeys) agent.sessionKeys = []\n if (!agent.sessionKeys.includes(sessionKey)) {\n agent.sessionKeys.push(sessionKey)\n if (agent.sessionKeys.length > SESSION_KEYS_MAX) {\n agent.sessionKeys.splice(0, agent.sessionKeys.length - SESSION_KEYS_MAX)\n }\n }\n }\n\n daily.agents[agentId] = agent\n this.save(daily)\n }\n\n /**\n * Get today's usage summary.\n */\n today(): DailyUsage {\n const date = new Date().toISOString().slice(0, 10)\n\n if (this.cache?.date === date) return this.cache\n\n const path = this.filePath(date)\n if (existsSync(path)) {\n try {\n this.cache = JSON.parse(readFileSync(path, \"utf-8\"))\n return this.cache!\n } catch {}\n }\n\n this.cache = { date, agents: {} }\n return this.cache\n }\n\n /**\n * Get usage for a specific date.\n */\n getDate(date: string): DailyUsage | null {\n const path = this.filePath(date)\n if (!existsSync(path)) return null\n try {\n return JSON.parse(readFileSync(path, \"utf-8\"))\n } catch {\n return null\n }\n }\n\n /**\n * Generate a daily cost report for a given date. Includes per-agent,\n * per-channel costs and session statistics.\n */\n generateDailyReport(date?: string): DailyReport | null {\n const targetDate = date || new Date().toISOString().slice(0, 10)\n const usage = this.getDate(targetDate)\n if (!usage) return null\n\n let totalTasks = 0, totalInput = 0, totalOutput = 0\n let totalCacheRead = 0, totalCacheCreate = 0, totalCost = 0\n let topAgent = \"\", topCost = 0\n const agentCosts: Record<string, number> = {}\n const agentSessionStats: Record<string, { sessions: number; avgTasksPerSession: number }> = {}\n const byChannel: Record<string, number> = {}\n\n for (const [id, agent] of Object.entries(usage.agents)) {\n const cost = this.cost(agent)\n agentCosts[id] = cost\n totalTasks += agent.tasks\n totalInput += (agent.inputTokens || 0) + (agent.tier2InputTokens || 0)\n totalOutput += (agent.outputTokens || 0) + (agent.tier2OutputTokens || 0)\n totalCacheRead += (agent.cacheReadTokens || 0) + (agent.tier2CacheReadTokens || 0)\n totalCacheCreate += (agent.cacheCreateTokens || 0) + (agent.tier2CacheCreateTokens || 0)\n totalCost += cost\n if (cost > topCost) { topCost = cost; topAgent = id }\n\n const sessions = agent.sessionKeys?.length || 0\n agentSessionStats[id] = {\n sessions,\n avgTasksPerSession: sessions > 0 ? agent.tasks / sessions : agent.tasks,\n }\n\n for (const [chKey, ch] of Object.entries(agent.byChannel || {})) {\n const chCost = this.cost(ch, agent.model)\n byChannel[chKey] = (byChannel[chKey] || 0) + chCost\n }\n }\n\n return {\n date: targetDate, totalTasks, totalInput, totalOutput,\n totalCacheRead, totalCacheCreate, totalCost, topAgent, topCost, agentCosts,\n agentSessionStats, byChannel,\n }\n }\n\n /**\n * Append a daily report row to TOKEN_COSTS.md. Adds channel + session\n * breakdown inline for at-a-glance spend attribution.\n */\n appendToTokenCosts(report: DailyReport, filePath?: string): void {\n const file = filePath || resolve(process.cwd(), \".agentx/TOKEN_COSTS.md\")\n const fmt = (n: number) => n < 0.01 ? n.toFixed(4) : n.toFixed(2)\n const fmtTok = (n: number) =>\n n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` :\n n >= 1_000 ? `${(n / 1_000).toFixed(0)}K` :\n String(n)\n\n const agentBreakdown = Object.entries(report.agentCosts)\n .sort(([, a], [, b]) => b - a)\n .map(([id, cost]) => {\n const stats = report.agentSessionStats[id]\n const sessTag = stats && stats.sessions > 0 ? ` (${stats.sessions}s, ${stats.avgTasksPerSession.toFixed(1)}t/s)` : \"\"\n return `${id}: $${fmt(cost)}${sessTag}`\n })\n .join(\", \")\n\n const channelBreakdown = Object.entries(report.byChannel)\n .sort(([, a], [, b]) => b - a)\n .map(([ch, cost]) => `${ch}: $${fmt(cost)}`)\n .join(\", \")\n\n const row = `| ${report.date} | ${report.totalTasks} | ${fmtTok(report.totalInput)} | ${fmtTok(report.totalOutput)} | ${fmtTok(report.totalCacheRead)} | ${fmtTok(report.totalCacheCreate)} | $${fmt(report.totalCost)} | ${agentBreakdown} | ${channelBreakdown} |`\n\n if (!existsSync(file)) {\n const header =\n \"# Token Costs\\n\\n\" +\n \"Daily token cost tracking. Auto-appended at midnight, host time.\\n\" +\n \"Agent breakdown: `agent: $cost (Ns, T.Tt/s)` — sessions, tasks/session.\\n\\n\" +\n \"| Date | Tasks | Input | Output | Cache R | Cache W | Cost | Per Agent | Per Channel |\\n\" +\n \"|------|-------|-------|--------|---------|---------|------|-----------|-------------|\\n\"\n writeFileSync(file, header + row + \"\\n\")\n } else {\n appendFileSync(file, row + \"\\n\")\n }\n }\n\n /**\n * Return true if TOKEN_COSTS.md already has a row for `date`. Lets callers\n * skip duplicate appends after daemon restarts or timer-edge double fires.\n */\n hasTokenCostsEntry(date: string, filePath?: string): boolean {\n const file = filePath || resolve(process.cwd(), \".agentx/TOKEN_COSTS.md\")\n if (!existsSync(file)) return false\n try {\n const content = readFileSync(file, \"utf-8\")\n // Rows look like: `| 2026-04-18 | ...`\n return new RegExp(`^\\\\|\\\\s*${date}\\\\s*\\\\|`, \"m\").test(content)\n } catch {\n return false\n }\n }\n\n /**\n * Find the most recent date already logged to TOKEN_COSTS.md (YYYY-MM-DD).\n * Returns null when the file doesn't exist or has no rows.\n */\n lastTokenCostsDate(filePath?: string): string | null {\n const file = filePath || resolve(process.cwd(), \".agentx/TOKEN_COSTS.md\")\n if (!existsSync(file)) return null\n try {\n const content = readFileSync(file, \"utf-8\")\n const dates = content.match(/^\\|\\s*(\\d{4}-\\d{2}-\\d{2})\\s*\\|/gm) ?? []\n if (dates.length === 0) return null\n // Extract the date portion and pick the max — rows can be out of order\n // after a catch-up, so don't rely on file order.\n const parsed = dates\n .map((m) => m.match(/(\\d{4}-\\d{2}-\\d{2})/)?.[1])\n .filter((d): d is string => !!d)\n parsed.sort()\n return parsed[parsed.length - 1] ?? null\n } catch {\n return null\n }\n }\n\n /**\n * Append reports for any days between (lastLogged + 1) and `throughDate`\n * that have usage on disk but no row in TOKEN_COSTS.md. Idempotent —\n * safe to call on every daemon startup. Bounded to `maxDays` to avoid\n * a stalled daemon backfilling a year's worth on first start.\n *\n * Returns the list of dates actually appended, for logging.\n */\n catchUpTokenCosts(\n throughDate: string,\n opts: { maxDays?: number; filePath?: string } = {},\n ): string[] {\n const maxDays = opts.maxDays ?? 30\n const appended: string[] = []\n\n const last = this.lastTokenCostsDate(opts.filePath)\n // Walk backward from throughDate, collecting dates to fill. Stop at the\n // last-logged date (exclusive) or after maxDays, whichever comes first.\n const candidates: string[] = []\n const cursor = new Date(`${throughDate}T00:00:00Z`)\n for (let i = 0; i < maxDays; i++) {\n const date = cursor.toISOString().slice(0, 10)\n if (last && date <= last) break\n candidates.push(date)\n cursor.setUTCDate(cursor.getUTCDate() - 1)\n }\n // Oldest-first so the file stays chronological.\n candidates.reverse()\n\n for (const date of candidates) {\n if (this.hasTokenCostsEntry(date, opts.filePath)) continue\n const report = this.generateDailyReport(date)\n if (!report || report.totalTasks === 0) continue\n this.appendToTokenCosts(report, opts.filePath)\n appended.push(date)\n }\n return appended\n }\n\n /**\n * Get summary across last N days.\n */\n summary(days: number = 7): {\n totalTasks: number\n totalTokens: number\n totalInput: number\n totalOutput: number\n totalCacheRead: number\n totalCacheCreate: number\n cacheHitRatio: number\n totalErrors: number\n totalCost: number\n byAgent: Record<string, { tasks: number; input: number; output: number; cacheRead: number; cacheCreate: number; total: number; avgDuration: number; cost: number }>\n byChannel: Record<string, { tasks: number; cost: number }>\n sessionStats: Record<string, { sessions: number; avgTasksPerSession: number }>\n } {\n let totalTasks = 0\n let totalInput = 0\n let totalOutput = 0\n let totalCacheRead = 0\n let totalCacheCreate = 0\n let totalErrors = 0\n let totalCost = 0\n const byAgent: Record<string, { tasks: number; input: number; output: number; cacheRead: number; cacheCreate: number; total: number; avgDuration: number; totalDuration: number; cost: number; model?: string; sessions: number }> = {}\n const byChannel: Record<string, { tasks: number; cost: number }> = {}\n\n for (let i = 0; i < days; i++) {\n const date = new Date(Date.now() - i * 86400_000).toISOString().slice(0, 10)\n const usage = this.getDate(date)\n if (!usage) continue\n\n for (const [id, agent] of Object.entries(usage.agents)) {\n const cost = this.cost(agent)\n totalTasks += agent.tasks\n const agentInput = (agent.inputTokens || 0) + (agent.tier2InputTokens || 0)\n const agentOutput = (agent.outputTokens || 0) + (agent.tier2OutputTokens || 0)\n const agentCR = (agent.cacheReadTokens || 0) + (agent.tier2CacheReadTokens || 0)\n const agentCW = (agent.cacheCreateTokens || 0) + (agent.tier2CacheCreateTokens || 0)\n totalInput += agentInput\n totalOutput += agentOutput\n totalCacheRead += agentCR\n totalCacheCreate += agentCW\n totalErrors += agent.errors\n totalCost += cost\n\n const existing = byAgent[id] || { tasks: 0, input: 0, output: 0, cacheRead: 0, cacheCreate: 0, total: 0, avgDuration: 0, totalDuration: 0, cost: 0, sessions: 0 }\n existing.tasks += agent.tasks\n existing.input += agentInput\n existing.output += agentOutput\n existing.cacheRead += agentCR\n existing.cacheCreate += agentCW\n existing.total = existing.input + existing.output + existing.cacheRead + existing.cacheCreate\n existing.totalDuration += agent.totalDuration\n existing.avgDuration = existing.totalDuration / existing.tasks\n existing.cost += cost\n existing.sessions += agent.sessionKeys?.length || 0\n if (agent.model) existing.model = agent.model\n byAgent[id] = existing\n\n for (const [chKey, ch] of Object.entries(agent.byChannel || {})) {\n const chCost = this.cost(ch, agent.model)\n const acc = byChannel[chKey] || { tasks: 0, cost: 0 }\n acc.tasks += ch.tasks\n acc.cost += chCost\n byChannel[chKey] = acc\n }\n }\n }\n\n const totalTokens = totalInput + totalOutput + totalCacheRead + totalCacheCreate\n const cacheHitRatio = (totalCacheRead + totalCacheCreate) > 0\n ? totalCacheRead / (totalCacheRead + totalCacheCreate)\n : 0\n\n const sessionStats: Record<string, { sessions: number; avgTasksPerSession: number }> = {}\n for (const [id, a] of Object.entries(byAgent)) {\n sessionStats[id] = {\n sessions: a.sessions,\n avgTasksPerSession: a.sessions > 0 ? a.tasks / a.sessions : a.tasks,\n }\n }\n\n return { totalTasks, totalTokens, totalInput, totalOutput, totalCacheRead, totalCacheCreate, cacheHitRatio, totalErrors, totalCost, byAgent, byChannel, sessionStats }\n }\n\n private filePath(date: string): string {\n return resolve(this.dir, `${date}.json`)\n }\n\n private save(usage: DailyUsage): void {\n try {\n writeFileSync(this.filePath(usage.date), JSON.stringify(usage, null, 2))\n } catch {}\n }\n}\n\n/**\n * Load CACHE_AWARE_PRICING and merge any operator-supplied override. The\n * override file is optional; operators tweak rates (e.g. when Anthropic\n * publishes a price change) without rebuilding the daemon.\n */\nexport function loadPricingWithOverrides(\n overridePath: string = PRICING_OVERRIDE_PATH,\n): typeof CACHE_AWARE_PRICING {\n const result = JSON.parse(JSON.stringify(CACHE_AWARE_PRICING))\n try {\n const p = resolve(process.cwd(), overridePath)\n if (!existsSync(p)) return result\n const raw = JSON.parse(readFileSync(p, \"utf-8\"))\n for (const [family, rates] of Object.entries(raw)) {\n if (!result[family]) result[family] = { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 }\n Object.assign(result[family], rates as object)\n }\n } catch {\n // Malformed override file — stay with defaults rather than crash at boot.\n }\n return result\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,MAAiB,KACnF,OAAS,WAAAC,MAAe,OAiCjB,IAAMC,EAAiH,CAE5H,eAAoB,CAAE,MAAO,GAAM,OAAQ,GAAM,UAAW,EAAO,YAAa,IAAK,EAErF,gBAAoB,CAAE,MAAO,EAAM,OAAQ,GAAM,UAAW,GAAO,YAAa,IAAK,EACrF,kBAAoB,CAAE,MAAO,EAAM,OAAQ,GAAM,UAAW,GAAO,YAAa,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C,EAAW,QAAAqC,EAAS,UAAAhC,EAAW,aAAAyC,CAAa,CACvK,CAEQ,SAAStD,EAAsB,CACrC,OAAO/C,EAAQ,KAAK,IAAK,GAAG+C,QAAW,CACzC,CAEQ,KAAK9B,EAAyB,CACpC,GAAI,CACFrB,EAAc,KAAK,SAASqB,EAAM,IAAI,EAAG,KAAK,UAAUA,EAAO,KAAM,CAAC,CAAC,CACzE,MAAE,CAAO,CACX,CACF,EAOO,SAASD,EACdsF,EAAuBzF,EACK,CAC5B,IAAM0F,EAAS,KAAK,MAAM,KAAK,UAAUtG,CAAmB,CAAC,EAC7D,GAAI,CACF,IAAMmB,EAAIpB,EAAQ,QAAQ,IAAI,EAAGsG,CAAY,EAC7C,GAAI,CAACxG,EAAWsB,CAAC,EAAG,OAAOmF,EAC3B,IAAMC,EAAM,KAAK,MAAM7G,EAAayB,EAAG,OAAO,CAAC,EAC/C,OAAW,CAACD,EAAQsF,CAAK,IAAK,OAAO,QAAQD,CAAG,EACzCD,EAAOpF,CAAM,IAAGoF,EAAOpF,CAAM,EAAI,CAAE,MAAO,EAAG,OAAQ,EAAG,UAAW,EAAG,YAAa,CAAE,GAC1F,OAAO,OAAOoF,EAAOpF,CAAM,EAAGsF,CAAe,CAEjD,MAAE,CAEF,CACA,OAAOF,CACT","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","resolve","CACHE_AWARE_PRICING","CONTEXT_TIER_THRESHOLD","TIER2_MULTIPLIER","getModelFamily","model","lower","has","needles","n","splitTaskUsageByTier","u","SESSION_KEYS_MAX","PRICING_OVERRIDE_PATH","TokenTracker","baseDir","loadPricingWithOverrides","usage","pricingTable","family","p","tier2In","tier2Out","tier2CR","tier2CW","tier1","tier2","agentId","duration","realUsage","messageLength","responseLength","error","channel","sessionKey","daily","agent","i1","o1","cr1","cw1","i2","o2","cr2","cw2","chKey","ch","date","path","targetDate","totalTasks","totalInput","totalOutput","totalCacheRead","totalCacheCreate","totalCost","topAgent","topCost","agentCosts","agentSessionStats","byChannel","id","cost","sessions","chCost","report","filePath","file","fmt","fmtTok","agentBreakdown","a","b","stats","sessTag","channelBreakdown","row","content","dates","parsed","m","d","throughDate","opts","maxDays","appended","last","candidates","cursor","i","days","totalErrors","byAgent","agentInput","agentOutput","agentCR","agentCW","existing","acc","totalTokens","cacheHitRatio","sessionStats","overridePath","result","raw","rates"]}
@@ -1,4 +1,4 @@
1
- import{b as C}from"./chunk-CECHWYJ2.js";import{a as L,b as _,c as R,d as j,e as M,j as I}from"./chunk-W3LSDADF.js";import{v as x,w as O}from"./chunk-CHQ5Q4QO.js";import{c as A,d as D}from"./chunk-QOYAX2FT.js";import{readFileSync as y,writeFileSync as b,appendFileSync as P,existsSync as w,mkdirSync as $,readdirSync as v,statSync as B}from"fs";import{resolve as u,join as N,relative as k,dirname as U}from"path";O();var T=class{baseDir;rawDir;log;constructor(t=u(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=u(t,"raw/entries"),this.log=e,$(this.rawDir,{recursive:!0}),$(u(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,r=u(this.rawDir,e),n=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&n.push(`context: ${t.sourceContext}`),t.meta)for(let[a,s]of Object.entries(t.meta))n.push(`${a}: ${JSON.stringify(s)}`);return n.push("---","",t.content),b(r,n.join(`
1
+ import{b as C}from"./chunk-CECHWYJ2.js";import{a as L,b as _,c as R,d as j,e as M,j as I}from"./chunk-NL6JSS4E.js";import{v as x,w as O}from"./chunk-CXCXMOTB.js";import{c as A,d as D}from"./chunk-QOYAX2FT.js";import{readFileSync as y,writeFileSync as b,appendFileSync as P,existsSync as w,mkdirSync as $,readdirSync as v,statSync as B}from"fs";import{resolve as u,join as N,relative as k,dirname as U}from"path";O();var T=class{baseDir;rawDir;log;constructor(t=u(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=u(t,"raw/entries"),this.log=e,$(this.rawDir,{recursive:!0}),$(u(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,r=u(this.rawDir,e),n=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&n.push(`context: ${t.sourceContext}`),t.meta)for(let[a,s]of Object.entries(t.meta))n.push(`${a}: ${JSON.stringify(s)}`);return n.push("---","",t.content),b(r,n.join(`
2
2
  `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}listEntries(t){if(!w(this.rawDir))return[];let e=v(this.rawDir).filter(n=>n.endsWith(".md")).sort(),r=[];for(let n of e){let a=y(u(this.rawDir,n),"utf-8"),s=this.parseEntry(a,n);s&&(t?.agentId&&s.agentId!==t.agentId||t?.after&&s.date<t.after||t?.before&&s.date>t.before||r.push(s))}return r}parseEntry(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let n=r[1],a=r[2].trim(),s=c=>n.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",o=new Set(["id","date","agent","source","context"]),i={};for(let c of n.split(`
3
3
  `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||o.has(l[1])))try{i[l[1]]=JSON.parse(l[2])}catch{i[l[1]]=l[2].trim()}}return{id:s("id")||e.replace(".md",""),date:s("date"),agentId:s("agent"),source:s("source"),sourceContext:s("context")||void 0,content:a,meta:Object.keys(i).length>0?i:void 0}}writeArticle(t,e,r,n){let a=this.readArticle(t);if(a&&!this.canWrite(a.meta,n))return this.log(`Permission denied: "${n}" cannot write "${t}" (owner: ${a.meta.owner})`),!1;e.type&&!C(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let s=u(this.baseDir,t);a&&this.saveVersion(t,s),$(U(s),{recursive:!0});let o=["---",`title: "${e.title}"`];e.type&&o.push(`type: ${e.type}`),e.related?.length&&o.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),o.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&o.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),o.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&o.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),o.push("---","",r),b(s,o.join(`
4
4
  `));let i=a?"update":"create";return this.appendLog(i,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${n} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let r=y(e,"utf-8"),n=new Date().toISOString().replace(/[:.]/g,"-"),a=u(this.baseDir,"_versions",t.replace(/\.md$/,""));$(a,{recursive:!0}),b(u(a,`${n}.md`),r)}catch{}}getVersions(t){let e=u(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return v(e).filter(r=>r.endsWith(".md")).sort().reverse().map(r=>({timestamp:r.replace(/\.md$/,"").replace(/-/g,(n,a)=>a<19?a===10?"T":a===13||a===16?":":"-":n),path:u(e,r)}))}catch{return[]}}restoreVersion(t,e){let n=this.getVersions(t).find(a=>a.timestamp.startsWith(e));if(!n)return!1;try{let a=y(n.path,"utf-8"),s=u(this.baseDir,t);return this.saveVersion(t,s),b(s,a),this.appendLog("restore",`${t} restored to ${e}`),!0}catch{return!1}}readArticle(t){let e=u(this.baseDir,t);if(!w(e))return null;let r=y(e,"utf-8");return this.parseArticle(r,t)}readArticleAs(t,e){let r=this.readArticle(t);return!r||!this.canRead(r.meta,e)?null:r}parseArticle(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let n=r[1],a=r[2].trim(),s=m=>n.match(new RegExp(`^${m}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",o=m=>{let h=n.match(new RegExp(`^${m}:\\s*\\[(.*)\\]$`,"m"));return h?h[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},i=s("type")||s("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(i)?i:void 0,p=o("tags").filter((m,h,f)=>m&&f.indexOf(m)===h),d=o("related"),g=o("graph_path");return{meta:{title:s("title"),type:l,related:d.length?d:void 0,tags:p,owner:s("owner"),access:s("access")||"public",sharedWith:o("shared_with"),created:s("created"),lastUpdated:s("last_updated"),sources:o("sources"),graphPath:g.length?g:void 0},content:a,path:e}}listCache=new Map;listArticles(t){let e=[],r=[];this.walkDir(this.baseDir,(o,i)=>{if(!o.endsWith(".md"))return;let c=k(this.baseDir,o);c.startsWith("raw/")||c.startsWith("_")||(e.push(c),r.push(`${c}:${i?.mtimeMs??"?"}:${i?.size??"?"}`))});let n=r.join("|"),a=this.listCache.get(t);if(a&&a.signature===n)return a.articles.slice();let s=[];for(let o of e){let i=this.readArticle(o);i&&this.canRead(i.meta,t)&&s.push(i)}return this.listCache.set(t,{signature:n,articles:s}),s.slice()}search(t,e,r=10){let n=t.toLowerCase(),a=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let g=k(this.baseDir,d);if(g.startsWith("raw/")||g.startsWith("_"))return;let m=this.readArticle(g);!m||!this.canRead(m.meta,e)||a.push(m)}),a.length===0)return[];let s=a.map(d=>d.content),o=u(this.baseDir,"_bm25_cache.json"),i=D(s,o),c=A(t,i),l=new Map(c.map(d=>[d.docIndex,d.score]));return a.map((d,g)=>{let m=l.get(g)??0;return d.meta.title.toLowerCase().includes(n)&&(m+=10),d.meta.tags?.some(h=>h.toLowerCase().includes(n))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,g)=>g.score-d.score).slice(0,r).map(d=>d.article)}async findRelevantReranked(t,e,r=10,n={}){let a=Math.max(r,n.shortlist??_),s=this.findRelevant(t,e,a);if(s.length<2)return s.slice(0,r);let o=s.map((l,p)=>({id:`c${p}`,title:l.meta.title||`(untitled ${p})`,tags:l.meta.tags,excerpt:l.content})),i=await x(L,R({query:t,candidates:o,excerptChars:n.excerptChars}),j(o),{incumbent:{best:o[0].id},features:{agent:e??"unknown"}});return!i||i.mode!=="active"?s.slice(0,r):M(i.answers,o).ranked.map(l=>s[Number(l.slice(1))]).filter(l=>!!l).slice(0,r)}findRelevant(t,e,r=3,n,a={graph:.6,bm25:.4}){let s=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=k(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let W=this.readArticle(f);!W||!this.canRead(W.meta,e)||s.push(W)}),s.length===0)return[];let o=s.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),i=u(this.baseDir,"_bm25_relevance_cache.json"),c=D(o,i),l=A(t,c),p=l.reduce((h,f)=>Math.max(h,f.score),0)||1,d=new Map(l.map(h=>[h.docIndex,h.score/p])),g=!!(n&&n.length>0);return s.map((h,f)=>{let W=d.get(f)??0,S=0;g&&h.meta.graphPath?.length&&(S=I(n,h.meta.graphPath));let E=g?a.graph*S+a.bm25*W:W;return{article:h,score:E}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,r).map(h=>h.article)}buildContext(t,e=4e3){if(t.length===0)return"";let r=["[Wiki Knowledge]"],n=0;for(let a of t){let s=`
@@ -102,4 +102,4 @@ We use GitLab for version control.
102
102
  There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
103
 
104
104
  ${r}`}walkDir(t,e){if(w(t))for(let r of v(t)){let n=N(t,r),a=B(n);a.isDirectory()?this.walkDir(n,e):e(n,a)}}};export{T as a};
105
- //# sourceMappingURL=chunk-QCKUXJJ3.js.map
105
+ //# sourceMappingURL=chunk-3RLYCNGP.js.map
@@ -1,4 +1,4 @@
1
- import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-DP7RTNDM.js";import{a as E}from"./chunk-QCKUXJJ3.js";import{b as L}from"./chunk-CECHWYJ2.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c=""){return Z(r,s,t,o,i,c)}function Z(n,r,s,t,o,i=""){let c=r?`
1
+ import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-DP7RTNDM.js";import{a as E}from"./chunk-3RLYCNGP.js";import{b as L}from"./chunk-CECHWYJ2.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c=""){return Z(r,s,t,o,i,c)}function Z(n,r,s,t,o,i=""){let c=r?`
2
2
  ## Worldview
3
3
 
4
4
  ${r}
@@ -240,4 +240,4 @@ ${g}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
240
240
  Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let u=[{role:"user",content:n}];s&&(u.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),u.push({role:"user",content:`Your previous response failed validation: ${s}
241
241
  Re-emit the FULL corrected JSON object.`}));let g=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:u}),signal:i.signal});if(!g.ok){let a=await g.text().catch(()=>"");throw new Error(`anthropic API ${g.status}: ${a.slice(0,500)}`)}let l=await g.json(),e=(Array.isArray(l.content)?l.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
242
242
  `).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...m)=>t(m.map(String).join(" "))),p=c.rebuildIndex(),u=z(r),g=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(g,p,u,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let l=p.articles.map(m=>({title:m.title,path:m.path,type:m.type})),d=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,l,d);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,l,d);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(m=>m.candidates),w=new Set(y.map(m=>m.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(m=>[m.stamp,m]));for(let m of f.articles){let A=c.readArticle(m.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${m.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(m.promotedFrom,T),S={id:Y(o,m.path),createdAt:v,status:"pending",article:m,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:m.path,title:m.title,type:m.type,stamps:m.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of m.promotedFrom)k.push({stamp:X,decision:"proposed",article:m.path,proposal:S.id,at:v})}for(let m of f.skipped)k.push({stamp:m.stamp,decision:"skipped",reason:m.reason,at:v}),i.skipped.push(m);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let u=s.now??Date.now(),g=new Date(u).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??g,lastUpdated:g,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let d=new Date(u).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:d}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:d};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
243
- //# sourceMappingURL=chunk-4MESMUND.js.map
243
+ //# sourceMappingURL=chunk-4YBFKN3B.js.map
@@ -1,2 +1,2 @@
1
- import{q as p}from"./chunk-CZFGADZ2.js";import{b as i,c as u,d as l,e as c}from"./chunk-5D5NKZSD.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
- //# sourceMappingURL=chunk-GGB5JMII.js.map
1
+ import{q as p}from"./chunk-PEDNM2FA.js";import{b as i,c as u,d as l,e as c}from"./chunk-JYFE6SQU.js";import d from"cronstrue";var f=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||f,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return d.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return p(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{f as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
+ //# sourceMappingURL=chunk-55MUAKXA.js.map
@@ -1,4 +1,4 @@
1
- import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{ja as Ze,ka as et}from"./chunk-H5LQXHQQ.js";import{a as ot,b as st,c as it,d as at,e as ct,f as ut,g as lt,h as dt,i as pt,j as mt,k as bt,l as ft}from"./chunk-RGDKHYY2.js";import{a as E,b as Ke,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function yt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import ht from"better-sqlite3";import{createHash as wt}from"crypto";import{mkdirSync as Tt}from"fs";import{dirname as Et,resolve as kt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function xt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function St(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&_t(e),t<2&&Rt(e),t<3&&At(e)}function At(e){e.exec(`
1
+ import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{ja as Ze,ka as et}from"./chunk-M6NIPFRY.js";import{a as ot,b as st,c as it,d as at,e as ct,f as ut,g as lt,h as dt,i as pt,j as mt,k as bt,l as ft}from"./chunk-RGDKHYY2.js";import{a as E,b as Ke,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function yt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import ht from"better-sqlite3";import{createHash as wt}from"crypto";import{mkdirSync as Tt}from"fs";import{dirname as Et,resolve as kt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function xt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function St(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&_t(e),t<2&&Rt(e),t<3&&At(e)}function At(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function Rt(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:y,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Vt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:U,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:U}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===U),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function zt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Jt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Gt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,qt,Xt,Ue,$t,be=E(()=>{"use strict";He();Fe();gt();j();Y();v();z();Bt="claude-code",qt="claude-haiku-4-5-20251001",Xt=24e3,Ue=2e3,$t=3e4});import{readFileSync as Yt}from"fs";import{homedir as Kt}from"os";import{join as Ht}from"path";function N(e={}){let t=(e.baseUrl??Wt).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??en,s=e.maxChoiceOptions??tn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),sn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=an(a.abortSignal,a.timeoutMs??e.timeoutMs??Zt);try{let b={"Content-Type":"application/json"},y=on(e.apiKeyEnv,e.apiKeyFile);y&&(b.Authorization=`Bearer ${y}`);let w=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:rn(a.questions)}),signal:g}),g);if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await qe(w.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${F(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function rn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:nn[n.type]};return t}function on(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Ht(Kt(),t.slice(2)):t;if(!Z.has(n))try{let o=Yt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function sn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function an(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Wt,Zt,en,tn,nn,Z,fe=E(()=>{"use strict";j();v();z();Y();Wt="http://127.0.0.1:8000/v1",Zt=3e4,en=6e3,tn=50;nn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};Ke(Xe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>U,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>yt,agreement:()=>ot,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>dt,askSeat:()=>mn,band:()=>Ie,bootstrapInterval:()=>mt,brier:()=>ct,buildDesign:()=>ve,calibrationReport:()=>bt,choice:()=>nt,compareCalibrators:()=>Dt,confidenceFor:()=>re,configureDecisions:()=>un,coverageCurve:()=>lt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>dn,describeIssues:()=>F,ece:()=>it,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>pt,getDecisionBackend:()=>D,getSeatMode:()=>ze,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ut,logit:()=>le,mce:()=>at,measureConsistency:()=>jt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>tt,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>pn,registerBuiltinDecisionBackends:()=>cn,registerDecisionBackend:()=>R,reliabilityBins:()=>st,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>ln,score:()=>rt,seatEnvVar:()=>Ve,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function cn(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();ft();Me();je();Je();pe();be();fe();C();pe();be();fe()});function un(e){T={...ye,...T,...e},ee=!0}function ln(){T={...ye,seats:{}},ee=!1}function bn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(et(),he(Ze)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function dn(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return fn.includes(t)?t:null}function Ve(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function ze(e,t=process.env){bn();let r=ge(t[Ve(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function pn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function mn(e,t,r,n={}){let o=ze(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=gn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return yn(e,o,t,r,i,n,s,a,u),hn(e,i,u),null}}function gn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ye(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function yn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ye(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ye(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function hn(e,t,r){let n=Date.now();n-Ge<6e4||(Ge=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,fn,Ge,Je=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;fn=["off","shadow","active"];Ge=0});export{D as a,Ee as b,C as c,I as d,V as e,Dt as f,Me as g,jt as h,je as i,me as j,Un as k,Fe as l,cn as m,$e as n,un as o,ln as p,dn as q,ge as r,Ve as s,ze as t,pn as u,mn as v,Je as w};
114
- //# sourceMappingURL=chunk-CHQ5Q4QO.js.map
114
+ //# sourceMappingURL=chunk-CXCXMOTB.js.map
@@ -0,0 +1,2 @@
1
+ import{v as l,w as f}from"./chunk-CXCXMOTB.js";import{a,f as p}from"./chunk-72SZI2UW.js";f();p();var d="task-tier";function u(e){return{task:w(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 w(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function T(e){return e==="voice"||e==="desktop"||e==="opencode"}var k=60*60*1e3;function _(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 y(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(T(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??k;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}`}}export{h as a,T as b,_ as c,y as d};
2
+ //# sourceMappingURL=chunk-FQGEDMG6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agents/routing.ts","../src/decisions/seats/task-tier.ts"],"sourcesContent":["import { askSeat } from \"@/decisions/seat\"\nimport { PRE_SPAWN_SEAT_TIMEOUT_MS } from \"@/decisions/limits\"\nimport {\n TASK_TIER_SEAT,\n taskTierQuestions,\n taskTierState,\n needsFlagship,\n type TaskTierAnswers,\n type TaskTierInput,\n} from \"@/decisions/seats/task-tier\"\n\n// Picking a cheaper model for work that does not need an expensive one.\n//\n// The policy, in one line: keep the flagship unless the seat is ACTIVE and\n// confidently says the task is mechanical.\n//\n// Every branch that is not that leads to the flagship — seat off, seat in\n// shadow, backend unreachable, answer above the threshold, no cheap model\n// configured, a follow-up turn. That is not defensiveness for its own\n// sake. Downgrading is invisible in the output: the reply still arrives,\n// still reads fluently, and is simply worse in ways nobody checks. An\n// outage that silently made the whole fleet dumber would cost far more\n// than the tokens it saved, so the failure has to land on the expensive\n// side.\n//\n// Follow-ups are where this gets interesting, and the answer is\n// arithmetic rather than caution.\n//\n// Switching models mid-session is mechanically trivial — the session is a\n// transcript and the model is a per-invocation flag, which is exactly what\n// Claude Code's /model does. The cost is that the PROMPT CACHE IS PER\n// MODEL. Resuming on a different model means that model has no cache for\n// the transcript and reads all of it at full price.\n//\n// Published rates, opus-5 against haiku-4.5:\n//\n// opus cached read $0.50/M haiku uncached read $1.00/M\n// opus output $25.00/M haiku output $5.00/M\n//\n// So the swap costs 2x more on input and saves $20/M on output, and it is\n// cheaper only when\n//\n// session_tokens < 40 x reply_tokens\n//\n// A task worth downgrading is by definition one whose answer is short —\n// an acknowledgement, a status echo. Ten tokens of reply puts the\n// break-even at a 400-token session. On any real conversation the swap\n// LOSES, and it loses precisely on the traffic this seat exists to catch.\n//\n// That reverses once the cache is COLD. After the cache TTL there is no\n// cached read to give up: opus pays $5.00/M and haiku $1.00/M, and the\n// cheap model wins outright. So a follow-up is routable exactly when the\n// session has been idle long enough that nothing is cached any more.\n\n/** Below this P(needs the strongest model), a cheaper one will do.\n *\n * Low on purpose. This is not the point at which a small model becomes\n * adequate — it is the point past which being wrong is cheap, and the\n * asymmetry between \"saved a fraction of a cent\" and \"gave a subtly wrong\n * answer nobody caught\" is not close. */\nexport const DOWNGRADE_BELOW = 0.2\n\n/** Channels where the person picked the model themselves — in the desktop\n * app, or as agentx/<agent> in OpenCode's model menu. Downgrading there is\n * overriding them, so routing never applies. Exported so an offline\n * replay (scripts/backtest-jev.ts) applies the same rule as this path. */\nexport function channelKeepsConfiguredModel(channel: string | null | undefined): boolean {\n return channel === \"voice\" || channel === \"desktop\" || channel === \"opencode\"\n}\n\n/** How long a cached prefix is assumed to live. Anthropic's default TTL is\n * five minutes with a one-hour option; an hour is assumed here because it\n * is the assumption whose error is cheap — see the note above. */\nconst CACHE_TTL_MS = 60 * 60 * 1000\n\n/** Resolve only models compatible with the agent's CLI engine. An omitted\n * model leaves the agent on its configured default. */\nexport function cheapModelForEngine(\n tier: string,\n routing?: { cheapModel?: string; cheapModels?: { \"claude-code\"?: string; \"codex-cli\"?: string } },\n): string | undefined {\n if (tier === \"claude-code\") {\n const model = routing?.cheapModels?.[tier] ?? routing?.cheapModel\n return model && /^(claude-|haiku$|sonnet$|opus$)/.test(model) ? model : undefined\n }\n if (tier === \"codex-cli\") {\n const model = routing?.cheapModels?.[tier]\n return model && /^(gpt-|o\\d)/.test(model) ? model : undefined\n }\n return undefined\n}\n\nexport interface RouteResult {\n /** The model to use, or undefined to leave the agent's own default. */\n model?: string\n /** True when this call moved the task off the flagship. */\n downgraded: boolean\n /** P(needs the strongest model), or null when nothing was asked. */\n needsFlagship: number | null\n reason: string\n}\n\nexport interface RouteOptions extends TaskTierInput {\n /** The model to drop to. Usually from config; no downgrade without it. */\n cheapModel?: string | null\n threshold?: number\n /** Idle time on the session being resumed, or null when starting fresh.\n * Only consulted for follow-ups. */\n sessionIdleMs?: number | null\n /** How long a cached prefix is assumed to survive. */\n cacheTtlMs?: number\n}\n\n/**\n * Decide whether this task can run on a cheaper model.\n *\n * Never throws and never blocks: a routing decision must not be able to\n * stop a task from running.\n */\nexport async function routeTaskModel(opts: RouteOptions): Promise<RouteResult> {\n const keep = (reason: string, p: number | null = null): RouteResult => ({\n downgraded: false, needsFlagship: p, reason,\n })\n\n if (channelKeepsConfiguredModel(opts.channel)) {\n return keep(`${opts.channel} requests retain the configured model`)\n }\n\n if (!opts.cheapModel) return keep(\"no cheaper model configured\")\n\n // A follow-up onto a WARM cache is the losing case above. Idle longer\n // than the TTL and there is nothing left to lose, so it is routable.\n //\n // One hour, not the five-minute default, because the assumption has to\n // be the one that fails safely: over-estimating how long the cache lives\n // means occasionally keeping the flagship when a swap would have been\n // free, while under-estimating means routinely paying double on input.\n if (opts.isFollowUp) {\n const idle = opts.sessionIdleMs ?? 0\n const ttl = opts.cacheTtlMs ?? CACHE_TTL_MS\n if (idle < ttl) {\n return keep(`follow-up on a warm cache (idle ${Math.round(idle / 1000)}s) — swapping would cost more than it saves`)\n }\n }\n\n let result\n try {\n result = await askSeat(\n TASK_TIER_SEAT,\n taskTierState(opts),\n taskTierQuestions,\n {\n // The incumbent is \"always flagship\", which is what this has to beat.\n incumbent: { needsFlagship: 1 },\n features: { agent: opts.agent, channel: opts.channel ?? \"unknown\" },\n // Pre-spawn: without this the backend default (30s) bounded the\n // wait, and the step was seen taking minutes under load.\n timeoutMs: PRE_SPAWN_SEAT_TIMEOUT_MS,\n },\n )\n } catch {\n return keep(\"routing seat threw — keeping the flagship\")\n }\n\n if (!result) return keep(\"routing seat unavailable — keeping the flagship\")\n\n const p = needsFlagship(result.answers as TaskTierAnswers)\n\n // Shadow records the answer and changes nothing. This is the whole\n // point of a soak: the rows accumulate against real traffic while the\n // incumbent stays authoritative, so promotion is a decision made on\n // evidence rather than on how good the idea sounded.\n if (result.mode !== \"active\") {\n return keep(`shadow — would ${p < (opts.threshold ?? DOWNGRADE_BELOW) ? \"downgrade\" : \"keep\"} (${p.toFixed(2)})`, p)\n }\n\n const threshold = opts.threshold ?? DOWNGRADE_BELOW\n if (p >= threshold) return keep(`needs the flagship (${p.toFixed(2)})`, p)\n\n return {\n model: opts.cheapModel,\n downgraded: true,\n needsFlagship: p,\n reason: `mechanical task (${p.toFixed(2)} below ${threshold}) → ${opts.cheapModel}`,\n }\n}\n","import { noul } from \"../questions\"\nimport type { AnswersFor, NoulAnswer, StateValue } from \"../types\"\n\n// Whether a task needs the flagship model.\n//\n// Every claude-code agent on both nodes runs claude-opus-5. Much of what\n// they actually do is not hard: acknowledging a message, reading a file\n// and saying what is in it, restating a status, routing a mention. Those\n// turns cost flagship rates for work a small model finishes correctly.\n//\n// A single Noul, not a Choice over model names, and that is deliberate.\n// The models available differ per node, per tier and per provider, and a\n// Choice whose options are a fleet's current model list is a decision that\n// silently changes meaning every time someone edits config. The question\n// that stays stable is about the TASK: does this need the strongest model\n// available. Mapping that answer onto a specific model is policy, and\n// policy belongs in code where it can be read.\n//\n// Direction of failure is the whole design. A seat is fail-open by\n// contract — askSeat returns null when it is off or unreachable — and here\n// \"open\" must mean KEEP THE FLAGSHIP. A missing answer that quietly\n// downgrades a model would turn an outage into silently worse work across\n// the fleet, which is far more expensive than the tokens it saved. So the\n// caller only ever downgrades on an explicit, confident \"no\".\n\nexport const TASK_TIER_SEAT = \"task-tier\"\n\nexport interface TaskTierInput {\n /** The task, in the words it arrived in. */\n message: string\n agent: string\n /** Where it came from — a cron heartbeat and a customer message are not\n * the same kind of work even when they read alike. */\n channel?: string | null\n /** True when this continues an existing session. A follow-up inherits\n * the difficulty of what it is following up on, and switching models\n * mid-conversation is its own hazard. */\n isFollowUp?: boolean\n /** Tools the agent could reach for. A task that will touch production\n * is not a cheap task however simply it is phrased. */\n toolsAvailable?: number\n}\n\nexport function taskTierState(input: TaskTierInput): StateValue {\n return {\n task: clip(input.message, 2000),\n agent: input.agent,\n channel: input.channel ?? null,\n continuesExistingSession: input.isFollowUp ?? false,\n ...(input.toolsAvailable ? { toolsAvailable: input.toolsAvailable } : {}),\n }\n}\n\nexport const taskTierQuestions = {\n needsFlagship: noul(\n \"This task needs the strongest available model to be done correctly.\",\n {\n true:\n \"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.\",\n false:\n \"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.\",\n },\n ),\n}\n\nexport type TaskTierAnswers = AnswersFor<typeof taskTierQuestions>\n\nexport function needsFlagship(answers: TaskTierAnswers): number {\n return (answers.needsFlagship as NoulAnswer).noul\n}\n\nfunction clip(s: string, max: number): string {\n return s.length > max ? `${s.slice(0, max)}…` : s\n}\n"],"mappings":"yFAAAA,ICAAC,IAyBO,IAAMC,EAAiB,YAkBvB,SAASC,EAAcC,EAAkC,CAC9D,MAAO,CACL,KAAMC,EAAKD,EAAM,QAAS,GAAI,EAC9B,MAAOA,EAAM,MACb,QAASA,EAAM,SAAW,KAC1B,yBAA0BA,EAAM,YAAc,GAC9C,GAAIA,EAAM,eAAiB,CAAE,eAAgBA,EAAM,cAAe,EAAI,CAAC,CACzE,CACF,CAEO,IAAME,EAAoB,CAC/B,cAAeC,EACb,sEACA,CACE,KACE,sYACF,MACE,sSACJ,CACF,CACF,EAIO,SAASC,EAAcC,EAAkC,CAC9D,OAAQA,EAAQ,cAA6B,IAC/C,CAEA,SAASJ,EAAKK,EAAWC,EAAqB,CAC5C,OAAOD,EAAE,OAASC,EAAM,GAAGD,EAAE,MAAM,EAAGC,CAAG,UAAOD,CAClD,CDbO,IAAME,EAAkB,GAMxB,SAASC,EAA4BC,EAA6C,CACvF,OAAOA,IAAY,SAAWA,IAAY,WAAaA,IAAY,UACrE,CAKA,IAAMC,EAAe,GAAK,GAAK,IAIxB,SAASC,EACdC,EACAC,EACoB,CACpB,GAAID,IAAS,cAAe,CAC1B,IAAME,EAAQD,GAAS,cAAcD,CAAI,GAAKC,GAAS,WACvD,OAAOC,GAAS,kCAAkC,KAAKA,CAAK,EAAIA,EAAQ,OAE1E,GAAIF,IAAS,YAAa,CACxB,IAAME,EAAQD,GAAS,cAAcD,CAAI,EACzC,OAAOE,GAAS,cAAc,KAAKA,CAAK,EAAIA,EAAQ,OAGxD,CA6BA,eAAsBC,EAAeC,EAA0C,CAC7E,IAAMC,EAAO,CAACC,EAAgBC,EAAmB,QAAuB,CACtE,WAAY,GAAO,cAAeA,EAAG,OAAAD,CACvC,GAEA,GAAIV,EAA4BQ,EAAK,OAAO,EAC1C,OAAOC,EAAK,GAAGD,EAAK,8CAA8C,EAGpE,GAAI,CAACA,EAAK,WAAY,OAAOC,EAAK,6BAA6B,EAS/D,GAAID,EAAK,WAAY,CACnB,IAAMI,EAAOJ,EAAK,eAAiB,EAC7BK,EAAML,EAAK,YAAcN,EAC/B,GAAIU,EAAOC,EACT,OAAOJ,EAAK,mCAAmC,KAAK,MAAMG,EAAO,GAAI,mDAA8C,EAIvH,IAAIE,EACJ,GAAI,CACFA,EAAS,MAAMC,EACbC,EACAC,EAAcT,CAAI,EAClBU,EACA,CAEE,UAAW,CAAE,cAAe,CAAE,EAC9B,SAAU,CAAE,MAAOV,EAAK,MAAO,QAASA,EAAK,SAAW,SAAU,EAGlE,UAAW,IACb,CACF,CACF,MAAE,CACA,OAAOC,EAAK,gDAA2C,CACzD,CAEA,GAAI,CAACK,EAAQ,OAAOL,EAAK,sDAAiD,EAE1E,IAAME,EAAIQ,EAAcL,EAAO,OAA0B,EAMzD,GAAIA,EAAO,OAAS,SAClB,OAAOL,EAAK,uBAAkBE,GAAKH,EAAK,WAAaT,GAAmB,YAAc,WAAWY,EAAE,QAAQ,CAAC,KAAMA,CAAC,EAGrH,IAAMS,EAAYZ,EAAK,WAAaT,EACpC,OAAIY,GAAKS,EAAkBX,EAAK,uBAAuBE,EAAE,QAAQ,CAAC,KAAMA,CAAC,EAElE,CACL,MAAOH,EAAK,WACZ,WAAY,GACZ,cAAeG,EACf,OAAQ,oBAAoBA,EAAE,QAAQ,CAAC,WAAWS,aAAgBZ,EAAK,YACzE,CACF","names":["init_seat","init_questions","TASK_TIER_SEAT","taskTierState","input","clip","taskTierQuestions","noul","needsFlagship","answers","s","max","DOWNGRADE_BELOW","channelKeepsConfiguredModel","channel","CACHE_TTL_MS","cheapModelForEngine","tier","routing","model","routeTaskModel","opts","keep","reason","p","idle","ttl","result","askSeat","TASK_TIER_SEAT","taskTierState","taskTierQuestions","needsFlagship","threshold"]}
@@ -1,8 +1,8 @@
1
- import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-GGB5JMII.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-5D5NKZSD.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
1
+ import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-55MUAKXA.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-JYFE6SQU.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
2
2
  `)}async function k(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
3
3
  `):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
4
4
  `),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
5
5
  `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
6
  `),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
7
  `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
8
- //# sourceMappingURL=chunk-SGOXLRY4.js.map
8
+ //# sourceMappingURL=chunk-GFON223J.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-DAWQT4D4.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-PT5SRRZA.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-ZROS7GX2.js.map
126
+ //# sourceMappingURL=chunk-H5ZNKPXN.js.map
@@ -1,4 +1,4 @@
1
- import{c as le,d as K,e as E,f as Y,g as D}from"./chunk-N7HKIMMR.js";import{a as se,b as de}from"./chunk-DG5I6PPM.js";import{e as j,g as oe,n as ie,p as J}from"./chunk-E5OV6RTG.js";import{a as ae,b as re}from"./chunk-5D5NKZSD.js";import{a as ne}from"./chunk-DJMK22SB.js";import{A as Pe,P as ee,W as _e,ea as q,ga as te,ha as U,ka as F,w as L,x as Z}from"./chunk-H5LQXHQQ.js";import{existsSync as M,readFileSync as he,writeFileSync as ve,appendFileSync as Ue,mkdirSync as We}from"fs";import{dirname as Oe,resolve as P}from"path";import{fileURLToPath as Be}from"url";import{hostname as He}from"os";import{spawn as Le}from"child_process";F();import{existsSync as pe,readFileSync as ce,writeFileSync as G,copyFileSync as ze}from"fs";import{resolve as ge}from"path";function W(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(!pe(n))throw new Error(`agentx.json not found at ${n}`);let a=JSON.parse(ce(n,"utf-8")),r=e(a),o=typeof r=="string"?{summary:r}:r,s=JSON.stringify(a,null,2)+`
1
+ import{c as le,d as K,e as E,f as Y,g as D}from"./chunk-N7HKIMMR.js";import{a as se,b as de}from"./chunk-DG5I6PPM.js";import{e as j,g as oe,n as ie,p as J}from"./chunk-E5OV6RTG.js";import{a as ae,b as re}from"./chunk-JYFE6SQU.js";import{a as ne}from"./chunk-XQMLRZHY.js";import{A as Pe,P as ee,W as _e,ea as q,ga as te,ha as U,ka as F,w as L,x as Z}from"./chunk-M6NIPFRY.js";import{existsSync as M,readFileSync as he,writeFileSync as ve,appendFileSync as Ue,mkdirSync as We}from"fs";import{dirname as Oe,resolve as P}from"path";import{fileURLToPath as Be}from"url";import{hostname as He}from"os";import{spawn as Le}from"child_process";F();import{existsSync as pe,readFileSync as ce,writeFileSync as G,copyFileSync as ze}from"fs";import{resolve as ge}from"path";function W(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(!pe(n))throw new Error(`agentx.json not found at ${n}`);let a=JSON.parse(ce(n,"utf-8")),r=e(a),o=typeof r=="string"?{summary:r}:r,s=JSON.stringify(a,null,2)+`
2
2
  `,l=n+".tmp";G(l,s,"utf-8");try{JSON.parse(ce(l,"utf-8"))}catch(p){throw new Error(`config did not round-trip cleanly: ${p.message}`)}let i;return t.skipBackup||(i=`${n}.bak.${Date.now()}`,ze(n,i)),G(n,s,"utf-8"),t.skipReload||De().catch(()=>{}),{summary:o.summary,payload:o.payload,backupPath:i}}function me(e,t={}){let n=t.configPath||ge(process.cwd(),"agentx.json");if(pe(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return G(n,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:n}}async function De(){try{let t=U().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function ue(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
4
4
  <div class="ax-topbar__left">
@@ -741,4 +741,4 @@ tr:hover td { background: var(--bg-hover); }
741
741
  ORDER BY started_at DESC, rowid DESC LIMIT ?`).all(t,Math.max(1,Math.min(n,500))).map(r=>({taskId:r.task_id,agentId:r.agent_id,channel:r.channel,chatId:r.chat_id,status:r.status,startedAt:r.started_at,finishedAt:r.finished_at??null,messagePreview:r.message_preview}))}function lt(e){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'requests'").get()?e.prepare("PRAGMA table_info(requests)").all().some(a=>a.name==="person"):!1}function $e(e,t,n,a,...r){return lt(e)?e.prepare(`SELECT id, state, channel, agent_id, text, created_at FROM requests
742
742
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
743
743
  ${a}`).all(t,...n,...r).map(s=>({id:s.id,state:s.state,channel:s.channel,agentId:s.agent_id,text:s.text,createdAt:s.created_at})):[]}function sn(e,t){return $e(e,t,L,"ORDER BY created_at")}function dn(e,t,n=50){return $e(e,t,[...L,...Z],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}_e();var Q="member:",ct=90,pt="members",gt="tailscale-user-login",mt=400,ut=60*60*1e3;function ft(e){let t=e.scopes.find(n=>n.startsWith(Q));return t?t.slice(Q.length):null}function Ae(e,t){if(!e)return null;let n=t.verify(e),a=n?ft(n):null;return n&&a?{rec:n,personId:a}:null}function un(e,t){let n=e.people().find(l=>l.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:a,record:r}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${Q}${n.id}`],expiresInDays:ct}),{code:o,expiresAt:s}=e.codes.create({token:a,tokenId:r.id,name:n.id});return e.members.log({person:n.id,device:r.id,event:"invited"}),{ok:!0,code:o,expiresAt:s,tokenId:r.id,person:n}}var ht="The private network says someone else is connecting from this machine. Ask the owner for a new code.",vt="Too many machines are waiting for the owner's answer. Try again later.",Se=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Ie(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function bt(e){if(!Ie(e))return null;let t=Se(e,gt).toLowerCase();return t?t.slice(0,80):null}function xt(e){let t=e.socket?.remoteAddress||"unknown";if(!Ie(e))return t;let n=Se(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function yt(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function kt(e){return e.identities.map(ee).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function fn(e,t){let n=Date.now(),a=t.now??Date.now,r=t.log??(m=>console.log(m)),o=xt(e),s=t.limiter.retryAfter(o);if(s>0)return r(`[member] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let l=null,i="";try{let m=await ie(e,2048);l=m.code,i=yt(m.machine)}catch{}let p=t.codes.redeem(l),g=p?Ae(p.token,t.tokens):null;if(await $t(n,t.minMs??mt),!p||!g)return t.limiter.fail(o),r(`[member] pair-code failed from ${o}`),{status:401,body:{error:J}};t.limiter.succeed(o);let{rec:f,personId:d}=g,h=t.people().find(m=>m.id===d);if(!h)return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),r(`[member] pair-code for ${d} refused from ${o}: person no longer listed`),{status:403,body:{error:J}};let u=bt(e),A=kt(h);if(A.length&&(!u||!A.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${A.join(" or ")}`}),r(`[member] ${d}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${A.join(" or ")}`),{status:403,body:{error:ht}};let x=i||"Unnamed machine",y=h.name.slice(0,40),v=oe(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${x}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:pt},{now:a()});return v.ok?(t.members.add({tokenId:f.id,personId:d,name:x,state:"pending",cardId:v.card.id,address:o,...u?{network:u}:{},createdAt:new Date(a()).toISOString()}),t.members.log({person:d,device:f.id,event:"paired",address:o,detail:x}),r(`[member] ${d} paired "${x}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:d,name:x,state:"pending"},token:p.token}):(t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:v.error}),r(`[member] ${d}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:vt}})}var H="this machine is not paired",wt="waiting for the owner to approve this machine";function Ee(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function hn(e,t){return t.state==="pending"&&t.cardId?Ee(j(e,t.cardId)):null}function vn(e,t,n){let a=t.now??Date.now,r=t.log??(g=>console.log(g)),o=Ae(e,t.tokens);if(!o)return{ok:!1,status:401,error:H};let{rec:s,personId:l}=o,i=t.members.byToken(s.id);if(!i||i.state==="removed"||i.personId!==l)return{ok:!1,status:401,error:H};if(t.people&&!t.people().some(g=>g.id===l))return Ce(t,s.id,"person no longer listed"),r(`[member] ${l}: "${i.name}" ended: person no longer listed`),{ok:!1,status:401,error:H};if(i.state==="pending"){let g=i.cardId?j(t.root,i.cardId):null,f=Ee(g);if(f==="yes")i=t.members.update(s.id,{state:"active",approvedAt:new Date(a()).toISOString()})??i,t.members.log({person:l,device:s.id,event:"approved",detail:g?.decided_by}),r(`[member] ${l}: "${i.name}" approved`);else if(f==="no"){let d=g?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(s.id),t.members.update(s.id,{state:"removed",removedAt:new Date(a()).toISOString(),removedReason:d}),t.members.log({person:l,device:s.id,event:"refused",detail:d}),r(`[member] ${l}: "${i.name}" refused: ${d}`),{ok:!1,status:401,error:H}}else return{ok:!1,status:403,error:wt,waiting:!0}}let p=i.lastSeenAt?Date.parse(i.lastSeenAt):0;return n&&(a()-p>=ut||i.lastAddress!==n)&&(i=t.members.update(s.id,{lastSeenAt:new Date(a()).toISOString(),lastAddress:n})??i,t.members.log({person:l,device:s.id,event:"signed-in",address:n})),{ok:!0,device:i,personId:l,rec:s}}function Ce(e,t,n="removed by the owner"){let a=e.members.byToken(t);if(!a)return null;e.tokens.revoke(t);let r=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:a.personId,device:t,event:"removed",detail:n}),r}function bn(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Ce(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function $t(e,t){let n=e+t-Date.now();n>0&&await new Promise(a=>setTimeout(a,n))}var Te=["gitlab","github"];function At(e,t,n){let a=String(t||"").trim().toLowerCase();if(!Te.includes(a))throw new Error(`Request status works on ${Te.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let r=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...r,a])]:r.filter(o=>o!==a),`request status on ${a} is ${n?"on":"off"}`}function kn(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function wn(e){let{summary:t}=W(n=>At(n,e?.channel,!!e?.enabled));return{summary:t}}var St="https://ntfy.sh";function An(e){return{enabled:!!e?.enabled,server:e?.server||St,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Sn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let a=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(a))throw new Error("ntfy server must be an http(s) URL");n.server=a}if("topic"in t){let a=String(t.topic).trim();if(!a)throw new Error("ntfy topic cannot be empty");n.topic=a}if("token"in t){let a=String(t.token??"").trim();a?n.token=a:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{W as a,be as b,Bt as c,Ht as d,Lt as e,Kt as f,Yt as g,Gt as h,on as i,sn as j,dn as k,ct as l,un as m,xt as n,fn as o,hn as p,vn as q,Ce as r,bn as s,Te as t,At as u,kn as v,wn as w,An as x,Sn as y,st as z,nn as A};
744
- //# sourceMappingURL=chunk-UW6RUGNV.js.map
744
+ //# sourceMappingURL=chunk-IRH2O2QB.js.map
@@ -1,5 +1,5 @@
1
- import{ha as m,ka as b}from"./chunk-H5LQXHQQ.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{ha as m,ka as b}from"./chunk-M6NIPFRY.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-MTP2RH3P.js.map
5
+ //# sourceMappingURL=chunk-JUJPQWLG.js.map
@@ -1,5 +1,5 @@
1
- import{fa as m,ga as $,ka as x}from"./chunk-H5LQXHQQ.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{fa as m,ga as $,ka as x}from"./chunk-M6NIPFRY.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-5D5NKZSD.js.map
5
+ //# sourceMappingURL=chunk-JYFE6SQU.js.map