@cortex-agent/server 2026.8.3 → 2026.8.6

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 (224) hide show
  1. package/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
  2. package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
  3. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
  4. package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
  6. package/defaults/prompts/directives/benchmark-coder.md +1 -0
  7. package/defaults/prompts/directives/benchmark-fixer.md +1 -0
  8. package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
  9. package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
  10. package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
  11. package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
  12. package/dist/agent-adapter/capabilities.d.ts +32 -1
  13. package/dist/agent-adapter/capabilities.js +39 -1
  14. package/dist/agent-adapter/claude/adapter.d.ts +15 -0
  15. package/dist/agent-adapter/claude/adapter.js +29 -7
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
  17. package/dist/agent-adapter/claude/spawn-args.js +29 -6
  18. package/dist/agent-adapter/index.js +11 -1
  19. package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
  20. package/dist/agent-adapter/normalize/tool-names.js +10 -0
  21. package/dist/agent-adapter/pi/adapter.d.ts +20 -8
  22. package/dist/agent-adapter/pi/adapter.js +130 -35
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
  24. package/dist/agent-adapter/pi/agent-dir.js +48 -89
  25. package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
  26. package/dist/agent-adapter/pi/custom-catalog.js +42 -0
  27. package/dist/agent-adapter/pi/defaults.d.ts +9 -0
  28. package/dist/agent-adapter/pi/defaults.js +14 -4
  29. package/dist/agent-adapter/pi/discovery.d.ts +1 -3
  30. package/dist/agent-adapter/pi/discovery.js +3 -15
  31. package/dist/agent-adapter/pi/event-parser.js +8 -0
  32. package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
  33. package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
  34. package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
  35. package/dist/agent-adapter/pi/mcp-duration.js +48 -0
  36. package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
  37. package/dist/agent-adapter/pi/policy-guard.js +111 -0
  38. package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
  39. package/dist/agent-adapter/pi/providers-config.js +101 -0
  40. package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
  41. package/dist/agent-adapter/pi/quota-probe.js +36 -0
  42. package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
  43. package/dist/agent-adapter/pi/quota-sink.js +31 -0
  44. package/dist/agent-adapter/pi/session-files.d.ts +2 -0
  45. package/dist/agent-adapter/pi/session-files.js +19 -0
  46. package/dist/agent-adapter/pi/session-support.d.ts +14 -3
  47. package/dist/agent-adapter/pi/session-support.js +8 -0
  48. package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
  49. package/dist/agent-adapter/pi/spawn-args.js +13 -0
  50. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
  51. package/dist/agent-adapter/pi/tool-shims.js +32 -21
  52. package/dist/agent-adapter/pi/web-search.js +36 -8
  53. package/dist/agent-adapter/types.d.ts +14 -0
  54. package/dist/core/locales/en.d.ts +54 -1
  55. package/dist/core/locales/en.js +2 -0
  56. package/dist/core/locales/slices/commands.d.ts +12 -1
  57. package/dist/core/locales/slices/commands.js +24 -2
  58. package/dist/core/locales/slices/providers.d.ts +45 -0
  59. package/dist/core/locales/slices/providers.js +95 -0
  60. package/dist/core/locales/zh.js +2 -0
  61. package/dist/core/resilient-watch.d.ts +28 -0
  62. package/dist/core/resilient-watch.js +110 -0
  63. package/dist/core/settings.js +15 -20
  64. package/dist/core/types/agent-types.d.ts +6 -0
  65. package/dist/core/types/thread-types.d.ts +21 -3
  66. package/dist/core/utils.d.ts +21 -1
  67. package/dist/core/utils.js +37 -1
  68. package/dist/domain/agent-run/agent-run-cli.js +3 -1
  69. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
  70. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
  71. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
  72. package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
  73. package/dist/domain/agent-run/identity.d.ts +5 -0
  74. package/dist/domain/agent-run/identity.js +4 -1
  75. package/dist/domain/agent-run/journal.d.ts +3 -2
  76. package/dist/domain/agent-run/manifest.js +11 -4
  77. package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
  78. package/dist/domain/agent-run/pinned-node-process.js +9 -0
  79. package/dist/domain/agent-run/role-surface.d.ts +2 -2
  80. package/dist/domain/agent-run/role-surface.js +7 -3
  81. package/dist/domain/agent-run/run-config.d.ts +10 -1
  82. package/dist/domain/agent-run/run-config.js +57 -6
  83. package/dist/domain/agent-run/runner.js +149 -31
  84. package/dist/domain/agents/facade.d.ts +37 -122
  85. package/dist/domain/agents/facade.js +47 -115
  86. package/dist/domain/agents/spawn-config.d.ts +135 -0
  87. package/dist/domain/agents/spawn-config.js +121 -0
  88. package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
  89. package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
  90. package/dist/domain/benchmark/arm-schema.d.ts +43 -0
  91. package/dist/domain/benchmark/arm-schema.js +243 -0
  92. package/dist/domain/benchmark/capabilities.d.ts +4 -0
  93. package/dist/domain/benchmark/capabilities.js +54 -0
  94. package/dist/domain/benchmark/decimal-text.d.ts +27 -0
  95. package/dist/domain/benchmark/decimal-text.js +67 -0
  96. package/dist/domain/benchmark/lease-echo.d.ts +43 -0
  97. package/dist/domain/benchmark/lease-echo.js +56 -0
  98. package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
  99. package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
  100. package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
  101. package/dist/domain/benchmark/policy-compiler.js +680 -0
  102. package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
  103. package/dist/domain/benchmark/resolved-policy.js +195 -0
  104. package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
  105. package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
  106. package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
  107. package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
  108. package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
  109. package/dist/domain/benchmark/variant-proposal.js +42 -0
  110. package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
  111. package/dist/domain/benchmark/workspace-lease.js +272 -0
  112. package/dist/domain/costs/codex-quota.d.ts +29 -0
  113. package/dist/domain/costs/codex-quota.js +102 -0
  114. package/dist/domain/costs/cost-tracker.d.ts +48 -9
  115. package/dist/domain/costs/cost-tracker.js +74 -18
  116. package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
  117. package/dist/domain/costs/rate-limit-throttle.js +61 -6
  118. package/dist/domain/costs/resume-registry.d.ts +3 -1
  119. package/dist/domain/costs/resume-registry.js +10 -1
  120. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
  121. package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
  122. package/dist/domain/mcp/tools/cost.js +15 -6
  123. package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
  124. package/dist/domain/pi-providers/custom-provider-model.js +122 -0
  125. package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
  126. package/dist/domain/pi-providers/custom-provider-service.js +143 -0
  127. package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
  128. package/dist/domain/pi-providers/gateway-route-store.js +78 -0
  129. package/dist/domain/pi-providers/index.d.ts +4 -0
  130. package/dist/domain/pi-providers/index.js +8 -0
  131. package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
  132. package/dist/domain/pi-providers/models-json-store.js +77 -0
  133. package/dist/domain/remote/client-hot-reload.d.ts +9 -1
  134. package/dist/domain/remote/client-hot-reload.js +60 -12
  135. package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
  136. package/dist/domain/scheduling/jobs/_shared.js +11 -2
  137. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
  138. package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
  139. package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
  140. package/dist/domain/sessions/session-lifecycle.js +20 -1
  141. package/dist/domain/system/install-cli.js +8 -3
  142. package/dist/domain/system/system-notice.d.ts +4 -1
  143. package/dist/domain/system/system-notice.js +6 -2
  144. package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
  145. package/dist/domain/tasks/dispatch-utils.js +24 -37
  146. package/dist/domain/threads/runner.d.ts +16 -1
  147. package/dist/domain/threads/runner.js +62 -8
  148. package/dist/domain/threads/template-loader.d.ts +5 -0
  149. package/dist/domain/threads/template-loader.js +120 -36
  150. package/dist/domain/threads/template-validate.d.ts +244 -0
  151. package/dist/domain/threads/template-validate.js +574 -0
  152. package/dist/domain/threads/template-validate.parity.d.ts +1 -0
  153. package/dist/domain/threads/template-validate.parity.js +47 -0
  154. package/dist/domain/threads/template-writer.d.ts +55 -0
  155. package/dist/domain/threads/template-writer.js +131 -0
  156. package/dist/domain/ui-service/app-router.d.ts +143 -1
  157. package/dist/domain/ui-service/app-router.js +29 -3
  158. package/dist/domain/ui-service/input-schemas.d.ts +228 -4
  159. package/dist/domain/ui-service/input-schemas.js +132 -1
  160. package/dist/domain/ui-service/mutate/config.d.ts +10 -1
  161. package/dist/domain/ui-service/mutate/config.js +45 -5
  162. package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
  163. package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
  164. package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
  165. package/dist/domain/ui-service/mutate/profiles.js +156 -0
  166. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  167. package/dist/domain/ui-service/mutate/schedules.js +53 -3
  168. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  169. package/dist/domain/ui-service/mutate/sessions.js +25 -1
  170. package/dist/domain/ui-service/mutate/system.d.ts +2 -1
  171. package/dist/domain/ui-service/mutate/system.js +17 -3
  172. package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
  173. package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
  174. package/dist/domain/ui-service/query/config.js +30 -0
  175. package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
  176. package/dist/domain/ui-service/query/custom-providers.js +13 -0
  177. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
  178. package/dist/domain/ui-service/query/machine-detail.js +56 -0
  179. package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
  180. package/dist/domain/ui-service/query/machine-probe.js +136 -0
  181. package/dist/domain/ui-service/query/schedules.js +5 -0
  182. package/dist/domain/ui-service/query/sessions.js +8 -2
  183. package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
  184. package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
  185. package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
  186. package/dist/domain/ui-service/query/thread-templates.js +44 -7
  187. package/dist/domain/ui-service/types.d.ts +298 -7
  188. package/dist/domain/ui-service/ui-service.js +27 -3
  189. package/dist/entry/app.js +24 -3
  190. package/dist/entry/auth-cli.d.ts +4 -1
  191. package/dist/entry/auth-cli.js +10 -2
  192. package/dist/entry/cli-help.js +6 -2
  193. package/dist/entry/cli.js +2 -1
  194. package/dist/entry/daemon.d.ts +0 -11
  195. package/dist/entry/daemon.js +5 -49
  196. package/dist/entry/provider-cli.d.ts +16 -0
  197. package/dist/entry/provider-cli.js +203 -0
  198. package/dist/events/event-types.d.ts +2 -1
  199. package/dist/orchestration/agent-runner.js +3 -2
  200. package/dist/orchestration/routing/commands/cost.d.ts +8 -0
  201. package/dist/orchestration/routing/commands/cost.js +93 -21
  202. package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
  203. package/dist/orchestration/routing/commands/login-custom.js +89 -0
  204. package/dist/orchestration/routing/commands/login.d.ts +3 -0
  205. package/dist/orchestration/routing/commands/login.js +7 -0
  206. package/dist/orchestration/routing/message-router.js +48 -33
  207. package/dist/orchestration/routing/webhook.js +1 -1
  208. package/dist/orchestration/session-events.d.ts +2 -1
  209. package/dist/orchestration/session-events.js +1 -0
  210. package/dist/orchestration/thread-callback.js +1 -1
  211. package/dist/store/conversation-history-repo.d.ts +5 -1
  212. package/dist/store/conversation-history-repo.js +2 -1
  213. package/dist/store/cost-repo.d.ts +17 -0
  214. package/dist/store/cost-repo.js +47 -5
  215. package/dist/store/profile-repo.d.ts +0 -10
  216. package/dist/store/profile-repo.js +34 -56
  217. package/dist/store/session-registry-repo.d.ts +12 -0
  218. package/dist/store/session-registry-repo.js +16 -0
  219. package/package.json +1 -1
  220. package/web/dist/assets/index-DYMfaAi4.css +1 -0
  221. package/web/dist/assets/index-uOoZjGKa.js +141 -0
  222. package/web/dist/index.html +2 -2
  223. package/web/dist/assets/index-DrNx9R6c.js +0 -139
  224. package/web/dist/assets/index-zpf3OSKC.css +0 -1
@@ -1,33 +1,105 @@
1
- import { formatCostReport, checkBudget, setBudget } from '../../../domain/costs/cost-tracker.js';
1
+ // input: !cost / !budget chat commands
2
+ // output: cost report and global / per-project budget display + edit
3
+ // pos: chat surface over domain/costs/cost-tracker budget resolution
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { formatCostReport, checkBudget, setBudget, clearProjectBudget, listProjectBudgets, } from '../../../domain/costs/cost-tracker.js';
6
+ import { projectStore } from '../../../domain/projects/index.js';
2
7
  import { Icons } from '../../../core/icons.js';
3
8
  import { t } from '../../../core/i18n.js';
9
+ /** Reserved sub-commands; a project literally named `list` or `clear` is not addressable here. */
10
+ const RESERVED = new Set(['list', 'clear', 'reset']);
11
+ /** An amount token: `$50/d` / `1000/m`. Everything else in argument position is a project id. */
12
+ function isAmountToken(token) {
13
+ return token.includes('/d') || token.includes('/m');
14
+ }
15
+ function parseAmount(args, suffix) {
16
+ const raw = args.find(a => a.includes(suffix))?.replace(/[^\d.]/g, '');
17
+ if (!raw)
18
+ return undefined;
19
+ const n = parseFloat(raw);
20
+ return Number.isFinite(n) && n > 0 ? n : undefined;
21
+ }
4
22
  export async function handleCostCmd(channel, adapter, trimmedMessage) {
5
23
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
6
24
  const project = trimmedMessage.split(/\s+/).slice(1).join(' ').trim() || null;
7
25
  await adapter.postMessage(dest, { text: await formatCostReport(project) });
8
26
  }
27
+ /**
28
+ * `!budget` — global status
29
+ * `!budget $50/d $1000/m` — set the global limits
30
+ * `!budget list` — global limits + every per-project override
31
+ * `!budget <project>` — that project's status (own override or inherited globals)
32
+ * `!budget <project> $50/d $1000/m` — set that project's override (both limits required)
33
+ * `!budget <project> clear` — drop that project's override
34
+ */
9
35
  export async function handleBudgetCmd(channel, adapter, trimmedMessage) {
10
36
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
11
- const args = trimmedMessage.split(/\s+/).slice(1);
12
- if (args.length === 0) {
13
- const b = await checkBudget();
14
- await adapter.postMessage(dest, {
15
- text: t('cmd.cost.budgetHeader', {
16
- dailyBudget: b.dailyBudget,
17
- dailySpent: b.dailySpent.toFixed(2),
18
- dailyRemaining: b.dailyRemaining.toFixed(2),
19
- monthlyBudget: b.monthlyBudget,
20
- monthlySpent: b.monthlySpent.toFixed(2),
21
- monthlyRemaining: b.monthlyRemaining.toFixed(2),
22
- }),
23
- });
37
+ const post = (text) => adapter.postMessage(dest, { text });
38
+ const args = trimmedMessage.split(/\s+/).slice(1).filter(a => a.length > 0);
39
+ const first = args[0]?.toLowerCase();
40
+ if (first === 'list') {
41
+ await post(await formatBudgetList());
42
+ return;
43
+ }
44
+ // The project selector is the leading non-amount token; without one this is the global form.
45
+ const project = args.length > 0 && !isAmountToken(args[0]) && !RESERVED.has(first) ? args[0] : null;
46
+ if (project && !projectStore.exists(project)) {
47
+ const known = projectStore.list().map(p => p.id).join(', ');
48
+ await post(`${Icons.error} ${t('cmd.cost.budgetUnknownProject', { project, known })}`);
49
+ return;
50
+ }
51
+ const rest = project ? args.slice(1) : args;
52
+ if (rest.length === 0) {
53
+ await post(await formatBudgetStatus(project));
54
+ return;
55
+ }
56
+ if (project && RESERVED.has(rest[0].toLowerCase())) {
57
+ const removed = await clearProjectBudget(project);
58
+ await post(removed
59
+ ? `${Icons.ok} ${t('cmd.cost.budgetCleared', { project })}`
60
+ : t('cmd.cost.budgetNoOverride', { project }));
61
+ return;
62
+ }
63
+ const daily = parseAmount(rest, '/d');
64
+ const monthly = parseAmount(rest, '/m');
65
+ // Per-project overrides are pair-only — a half-set override would resolve against a limit
66
+ // the project never declared. The global form still accepts a single limit (existing behaviour),
67
+ // but arguments that parse to no limit at all are a usage error, not a no-op write.
68
+ if (project ? (daily == null || monthly == null) : (daily == null && monthly == null)) {
69
+ await post(`${Icons.error} ${t('cmd.cost.budgetPairRequired', { project: project ?? '<project>' })}`);
24
70
  return;
25
71
  }
26
- const daily = args.find(a => a.includes('/d'))?.replace(/[^\d.]/g, '');
27
- const monthly = args.find(a => a.includes('/m'))?.replace(/[^\d.]/g, '');
28
- const result = await setBudget({
29
- daily_usd: daily ? parseFloat(daily) : undefined,
30
- monthly_usd: monthly ? parseFloat(monthly) : undefined,
31
- });
32
- await adapter.postMessage(dest, { text: `${Icons.ok} ${t('cmd.cost.budgetUpdated', { daily: result.daily_usd, monthly: result.monthly_usd })}` });
72
+ const result = await setBudget({ daily_usd: daily, monthly_usd: monthly, project });
73
+ await post(`${Icons.ok} ${project
74
+ ? t('cmd.cost.budgetUpdatedProject', { project, daily: result.daily_usd, monthly: result.monthly_usd })
75
+ : t('cmd.cost.budgetUpdated', { daily: result.daily_usd, monthly: result.monthly_usd })}`);
76
+ }
77
+ async function formatBudgetStatus(project) {
78
+ const b = await checkBudget(project);
79
+ const vars = {
80
+ dailyBudget: b.dailyBudget,
81
+ dailySpent: b.dailySpent.toFixed(2),
82
+ dailyRemaining: b.dailyRemaining.toFixed(2),
83
+ monthlyBudget: b.monthlyBudget,
84
+ monthlySpent: b.monthlySpent.toFixed(2),
85
+ monthlyRemaining: b.monthlyRemaining.toFixed(2),
86
+ };
87
+ if (!project)
88
+ return t('cmd.cost.budgetHeader', vars);
89
+ const scope = t(b.scope === 'project' ? 'cmd.cost.budgetScopeProject' : 'cmd.cost.budgetScopeGlobal');
90
+ return t('cmd.cost.budgetHeaderProject', { ...vars, project, scope });
91
+ }
92
+ async function formatBudgetList() {
93
+ const global = await checkBudget();
94
+ const overrides = await listProjectBudgets();
95
+ const lines = [t('cmd.cost.budgetListHeader', { daily: global.dailyBudget, monthly: global.monthlyBudget })];
96
+ if (overrides.length === 0) {
97
+ lines.push(t('cmd.cost.budgetListEmpty'));
98
+ }
99
+ else {
100
+ for (const o of overrides) {
101
+ lines.push(t('cmd.cost.budgetListItem', { project: o.project, daily: o.daily_usd, monthly: o.monthly_usd }));
102
+ }
103
+ }
104
+ return lines.join('\n');
33
105
  }
@@ -0,0 +1,26 @@
1
+ import { type CustomProviderStores } from '../../../domain/pi-providers/index.js';
2
+ import type { CommandResult } from './command-context.js';
3
+ export type CustomProviderRequest = {
4
+ kind: 'list';
5
+ } | {
6
+ kind: 'add';
7
+ name: string;
8
+ api: string;
9
+ upstreamUrl: string;
10
+ models: string[];
11
+ } | {
12
+ kind: 'remove';
13
+ name: string;
14
+ } | {
15
+ kind: 'usage';
16
+ };
17
+ /**
18
+ * `!login custom [list | add <name> <api> <url> <model...> | remove <name>]`.
19
+ *
20
+ * There is deliberately no key argument: a chat message is a durable, widely readable transcript,
21
+ * and an upstream secret does not belong in one. A provider added here routes through the gateway
22
+ * with the caller's own key passed through; to attach a stored key use the CLI (`--key -` reads it
23
+ * from stdin) or the Web settings page, both of which keep the secret off any transcript.
24
+ */
25
+ export declare function parseCustomProviderRequest(args: string[]): CustomProviderRequest;
26
+ export declare function handleCustomProviderCommand(args: string[], stores?: CustomProviderStores): Promise<CommandResult>;
@@ -0,0 +1,89 @@
1
+ // input: `!login custom` arguments and the custom provider stores
2
+ // output: chat listing, creation and deletion of user-defined PI providers
3
+ // pos: Chat surface for custom PI provider management
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { t } from '../../../core/i18n.js';
6
+ import { CUSTOM_PROVIDER_APIS, defaultCustomProviderStores, getCustomProvider, listCustomProviders, removeCustomProvider, upsertCustomProvider, } from '../../../domain/pi-providers/index.js';
7
+ /**
8
+ * `!login custom [list | add <name> <api> <url> <model...> | remove <name>]`.
9
+ *
10
+ * There is deliberately no key argument: a chat message is a durable, widely readable transcript,
11
+ * and an upstream secret does not belong in one. A provider added here routes through the gateway
12
+ * with the caller's own key passed through; to attach a stored key use the CLI (`--key -` reads it
13
+ * from stdin) or the Web settings page, both of which keep the secret off any transcript.
14
+ */
15
+ export function parseCustomProviderRequest(args) {
16
+ if (args.length === 0 || (args.length === 1 && args[0] === 'list'))
17
+ return { kind: 'list' };
18
+ if (args[0] === 'remove') {
19
+ return args.length === 2 ? { kind: 'remove', name: args[1] } : { kind: 'usage' };
20
+ }
21
+ if (args[0] === 'add') {
22
+ const [, name, api, upstreamUrl, ...models] = args;
23
+ if (!name || !api || !upstreamUrl || models.length === 0)
24
+ return { kind: 'usage' };
25
+ return { kind: 'add', name, api, upstreamUrl, models };
26
+ }
27
+ return { kind: 'usage' };
28
+ }
29
+ function issueText(issue) {
30
+ return t(`provider.issue.${issue}`);
31
+ }
32
+ function renderProvider(provider) {
33
+ return provider.routed
34
+ ? t('provider.cli.listItem', {
35
+ name: provider.name,
36
+ api: provider.api,
37
+ upstream: provider.upstreamUrl ?? '',
38
+ })
39
+ : t('provider.cli.listItemUnrouted', { name: provider.name, api: provider.api });
40
+ }
41
+ function usage() {
42
+ return { text: `${t('provider.chat.usage')}\n${t('provider.chat.keyNotice')}` };
43
+ }
44
+ function runList(stores) {
45
+ const providers = listCustomProviders(stores);
46
+ if (providers.length === 0)
47
+ return { text: t('provider.cli.listEmpty') };
48
+ return { text: providers.map(renderProvider).join('\n') };
49
+ }
50
+ function runAdd(request, stores) {
51
+ if (!CUSTOM_PROVIDER_APIS.includes(request.api)) {
52
+ return { text: `${issueText('api-invalid')} ${CUSTOM_PROVIDER_APIS.join(' | ')}` };
53
+ }
54
+ const result = upsertCustomProvider(stores, {
55
+ name: request.name,
56
+ api: request.api,
57
+ upstreamUrl: request.upstreamUrl,
58
+ models: request.models.map((id) => ({ id })),
59
+ });
60
+ if (result.ok === false)
61
+ return { text: result.errors.map(issueText).join('\n') };
62
+ return {
63
+ text: [
64
+ t('provider.cli.added', {
65
+ name: result.provider.name,
66
+ upstream: result.provider.upstreamUrl ?? '',
67
+ }),
68
+ t('provider.chat.keyNotice'),
69
+ ].join('\n'),
70
+ };
71
+ }
72
+ function runRemove(name, stores) {
73
+ if (!getCustomProvider(stores, name))
74
+ return { text: t('provider.cli.notFound', { name }) };
75
+ const result = removeCustomProvider(stores, name);
76
+ if (result.ok === false)
77
+ return { text: result.errors.map(issueText).join('\n') };
78
+ return { text: t('provider.cli.removed', { name }) };
79
+ }
80
+ export async function handleCustomProviderCommand(args, stores = defaultCustomProviderStores()) {
81
+ const request = parseCustomProviderRequest(args);
82
+ if (request.kind === 'list')
83
+ return runList(stores);
84
+ if (request.kind === 'add')
85
+ return runAdd(request, stores);
86
+ if (request.kind === 'remove')
87
+ return runRemove(request.name, stores);
88
+ return usage();
89
+ }
@@ -1,12 +1,15 @@
1
1
  import { type AuthLoginService, type AuthStatusSnapshot } from '../../../domain/auth/index.js';
2
2
  import type { CommandActionRouter } from '../../interactions/command-action-router.js';
3
3
  import type { PlatformAdapter } from '../../../platform/index.js';
4
+ import type { CustomProviderStores } from '../../../domain/pi-providers/index.js';
4
5
  import type { CommandResult } from './command-context.js';
5
6
  type AuthStatusReader = () => Promise<AuthStatusSnapshot>;
6
7
  export interface LoginCommandDependencies {
7
8
  readStatus?: AuthStatusReader;
8
9
  authLogin?: AuthLoginService;
9
10
  router?: CommandActionRouter;
11
+ /** Files `!login custom` reads and writes; defaults to the host's own catalog and gateway. */
12
+ customProviderStores?: CustomProviderStores;
10
13
  }
11
14
  export declare function createLoginHandler(input?: LoginCommandDependencies): (channel: string, _adapter: PlatformAdapter, message: string) => Promise<CommandResult>;
12
15
  export {};
@@ -5,6 +5,7 @@
5
5
  import { setTimeout as delay } from 'node:timers/promises';
6
6
  import { t } from '../../../core/i18n.js';
7
7
  import { authLoginService, formatAuthStatusSummary, LOGIN_FLOW_TTL_MS, getAuthStatus, } from '../../../domain/auth/index.js';
8
+ import { handleCustomProviderCommand } from './login-custom.js';
8
9
  import { openAuthRequiredLoginAction, } from './login-notice.js';
9
10
  const LOGIN_MODAL_CALLBACK = 'cmd_login_submit';
10
11
  const FLOW_WAIT_MS = LOGIN_FLOW_TTL_MS;
@@ -28,6 +29,9 @@ function parseRequest(message) {
28
29
  return parseClaudeRequest(args.slice(1));
29
30
  if (args[0] === 'pi')
30
31
  return parsePiRequest(args.slice(1));
32
+ // Custom providers have no login flow — they are defined, listed and deleted instead.
33
+ if (args[0] === 'custom')
34
+ return { kind: 'custom', args: args.slice(1) };
31
35
  return { kind: 'usage' };
32
36
  }
33
37
  function loginProviders(snapshot) {
@@ -546,6 +550,9 @@ export function createLoginHandler(input = {}) {
546
550
  if (request.kind === 'status') {
547
551
  return { text: formatAuthStatusSummary(await dependencies.readStatus()) };
548
552
  }
553
+ if (request.kind === 'custom') {
554
+ return handleCustomProviderCommand(request.args, input.customProviderStores);
555
+ }
549
556
  if (request.kind === 'usage')
550
557
  return { text: t('cmd.auth.usage') };
551
558
  if (request.backend === 'claude')
@@ -6,44 +6,53 @@ const log = createLogger('app');
6
6
  import { getTemplate, getAgent } from '../../domain/threads/index.js';
7
7
  import { orchestrator } from '../orchestrator.js';
8
8
  const THREAD_RESERVED_SUBCOMMANDS = new Set(['cancel', 'list', 'agents', 'templates']);
9
+ const COMMAND_MENTION_TOKEN = /(^|\s+)(?:<@[^>\s]+>|@[^\s@]+)(?=\s|$)/g;
9
10
  export function registerMessageHandler(adapter, deps) {
10
- const { dispatchCommand, handleMessageEdit } = deps;
11
11
  adapter.onMessageEdit(async (ctx) => {
12
- handleMessageEdit(ctx, adapter);
12
+ deps.handleMessageEdit(ctx, adapter);
13
13
  });
14
- adapter.onMessage(async (ctx) => {
15
- const message = ctx.message;
16
- log.info('Message event:', JSON.stringify({ kind: message.kind, isBot: message.isBot, text: message.text?.substring(0, 50), files: message.files?.length, threadId: message.ref.threadId }));
17
- if (routeBotMessage(message)) { /* stripped BRANCH_CALLBACK prefix, continue */ }
18
- else if (message.isBot)
19
- return;
20
- if (message.kind === 'system')
21
- return;
22
- const hasFiles = (message.files?.length || 0) > 0;
23
- const userMessage = message.text;
24
- const trimmedMessage = userMessage?.trim();
25
- const forwardedContent = extractForwardedContent(message);
26
- if (!userMessage && !hasFiles && !forwardedContent)
27
- return;
28
- const threadAnchorId = message.ref.threadId || null;
29
- if (shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, message.ref.conduit, adapter, threadAnchorId))
30
- return;
31
- const channel = message.ref.conduit;
32
- let agentMessage = normalizeSkillCommandPrefix(userMessage || '');
33
- if (forwardedContent) {
34
- agentMessage = `[Forwarded message]\n${forwardedContent}\n[End forwarded message]\n\n${agentMessage || 'The user forwarded the above message to you.'}`;
35
- }
36
- const threadAddMatch = trimmedMessage?.match(/^!thread\s+add\s+(\S+)(?:\s+([\s\S]+))?$/) ?? null;
37
- const threadStartMatch = trimmedMessage?.match(/^!thread\s+(\S+)\s+([\s\S]+)/) ?? null;
38
- const existingThread = threadAnchorId ? threadStore.findByPlatformThread(channel, threadAnchorId) : null;
39
- const isActiveThread = !!(existingThread && (existingThread.status === 'running' || existingThread.status === 'waiting'));
40
- await orchestrator.handleMessage({
41
- message, channel, adapter, threadAnchorId, hasFiles,
42
- userMessage: userMessage || '', agentMessage,
43
- threadAddMatch, threadStartMatch, existingThread, isActiveThread,
44
- });
14
+ adapter.onMessage((ctx) => routeIncomingMessage(ctx.message, adapter, deps.dispatchCommand));
15
+ }
16
+ async function routeIncomingMessage(message, adapter, dispatchCommand) {
17
+ log.info('Message event:', JSON.stringify({ kind: message.kind, isBot: message.isBot, text: message.text?.substring(0, 50), files: message.files?.length, threadId: message.ref.threadId }));
18
+ if (!shouldRouteIncomingMessage(message))
19
+ return;
20
+ const hasFiles = (message.files?.length || 0) > 0;
21
+ const userMessage = message.text;
22
+ const forwardedContent = extractForwardedContent(message);
23
+ if (!userMessage && !hasFiles && !forwardedContent)
24
+ return;
25
+ const channel = message.ref.conduit;
26
+ const threadAnchorId = message.ref.threadId || null;
27
+ const commandMessage = normalizeCommandMentions(userMessage?.trim());
28
+ if (shouldSkipForCommandDispatch(commandMessage, dispatchCommand, channel, adapter, threadAnchorId))
29
+ return;
30
+ const agentMessage = buildAgentMessage(userMessage || '', forwardedContent);
31
+ const threadRouting = buildThreadRouting(commandMessage, channel, threadAnchorId);
32
+ await orchestrator.handleMessage({
33
+ message, channel, adapter, threadAnchorId, hasFiles,
34
+ userMessage: userMessage || '', agentMessage, ...threadRouting,
45
35
  });
46
36
  }
37
+ function shouldRouteIncomingMessage(message) {
38
+ if (!routeBotMessage(message) && message.isBot)
39
+ return false;
40
+ return message.kind !== 'system';
41
+ }
42
+ function buildAgentMessage(userMessage, forwardedContent) {
43
+ const agentMessage = normalizeSkillCommandPrefix(userMessage);
44
+ if (!forwardedContent)
45
+ return agentMessage;
46
+ const fallback = agentMessage || 'The user forwarded the above message to you.';
47
+ return `[Forwarded message]\n${forwardedContent}\n[End forwarded message]\n\n${fallback}`;
48
+ }
49
+ function buildThreadRouting(commandMessage, channel, threadAnchorId) {
50
+ const threadAddMatch = commandMessage?.match(/^!thread\s+add\s+(\S+)(?:\s+([\s\S]+))?$/) ?? null;
51
+ const threadStartMatch = commandMessage?.match(/^!thread\s+(\S+)\s+([\s\S]+)/) ?? null;
52
+ const existingThread = threadAnchorId ? threadStore.findByPlatformThread(channel, threadAnchorId) : null;
53
+ const isActiveThread = !!(existingThread && (existingThread.status === 'running' || existingThread.status === 'waiting'));
54
+ return { threadAddMatch, threadStartMatch, existingThread, isActiveThread };
55
+ }
47
56
  // --- Bot message filter ---
48
57
  function routeBotMessage(message) {
49
58
  if (!message.isBot)
@@ -56,6 +65,12 @@ function routeBotMessage(message) {
56
65
  return false;
57
66
  }
58
67
  // --- Command dispatch check ---
68
+ function normalizeCommandMentions(message) {
69
+ if (!message)
70
+ return message;
71
+ const withoutMentions = message.replace(COMMAND_MENTION_TOKEN, '').trim();
72
+ return withoutMentions.startsWith('!') ? withoutMentions : message;
73
+ }
59
74
  function shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, channel, adapter, threadAnchorId) {
60
75
  const threadAddMatch = trimmedMessage?.match(/^!thread\s+add\s+(\S+)(?:\s+([\s\S]+))?$/);
61
76
  const isThreadExecCmd = (() => {
@@ -387,7 +387,7 @@ function createWebhookHandler(_options = {}) {
387
387
  }
388
388
  else if (t) {
389
389
  const totalNumTurns = t.steps.reduce((s, st) => s + (st.numTurns || 0), 0);
390
- const summaryText = buildThreadSummary({ thread: t, totalCostUsd: t.totalCostUsd, totalNumTurns, finalOutput: null, lastAgentResult: null, executionId: null });
390
+ const summaryText = buildThreadSummary({ thread: t, totalCostUsd: t.totalCostUsd, totalNumTurns, finalOutput: null, lastAgentResult: null, executionId: null, stopReason: null });
391
391
  void jobCtx.adapter.updateMessage(statusMsg, {
392
392
  text: summaryText,
393
393
  richBlocks: buildSealedStatusActionBlocks(summaryText, { channel, sessionName: null, isDm: false, threadId: t.id }),
@@ -1,5 +1,5 @@
1
1
  import type { AttachmentMeta } from '../domain/ui-service/types.js';
2
- import type { ChatNoticeLevel, SessionContextUsage } from '../core/types/agent-types.js';
2
+ import type { ChatNoticeLevel, NoticeAction, SessionContextUsage } from '../core/types/agent-types.js';
3
3
  export interface SessionMessagePayload {
4
4
  sessionId: string;
5
5
  channel: string;
@@ -18,6 +18,7 @@ export interface SessionMessagePayload {
18
18
  blockId?: string;
19
19
  /** Semantic presentation for system-authored assistant messages in chat clients. */
20
20
  noticeLevel?: ChatNoticeLevel;
21
+ noticeAction?: NoticeAction;
21
22
  /** Set on a user message injected into a live turn and not yet read by the model. It carries no
22
23
  * history entry yet — the client shows it as a provisional row until the matching
23
24
  * `session.message.delivered` commits it. Absent on every ordinary message. */
@@ -28,6 +28,7 @@ export function publishSessionMessage(p) {
28
28
  ...(p.ts !== undefined ? { ts: p.ts } : {}),
29
29
  ...(p.blockId !== undefined ? { blockId: p.blockId } : {}),
30
30
  ...(p.noticeLevel !== undefined ? { noticeLevel: p.noticeLevel } : {}),
31
+ ...(p.noticeAction !== undefined ? { noticeAction: p.noticeAction } : {}),
31
32
  ...(p.pending !== undefined ? { pending: p.pending } : {}),
32
33
  ...(p.pendingId !== undefined ? { pendingId: p.pendingId } : {}),
33
34
  });
@@ -126,7 +126,7 @@ export async function sealSuspendedStatusMsg(threadId, adapter) {
126
126
  return;
127
127
  const totalNumTurns = t.steps.reduce((acc, st) => acc + (st.numTurns || 0), 0);
128
128
  // Background seal: buildThreadSummary text, no interactive action blocks (no live user to click).
129
- await sealThreadStatus(a, ref, { thread: t, totalCostUsd: t.totalCostUsd, totalNumTurns, finalOutput: null, lastAgentResult: null, executionId: null })
129
+ await sealThreadStatus(a, ref, { thread: t, totalCostUsd: t.totalCostUsd, totalNumTurns, finalOutput: null, lastAgentResult: null, executionId: null, stopReason: null })
130
130
  .catch((e) => log.warn(`seal status msg ${threadId}: ${e.message}`));
131
131
  }
132
132
  const defaultResume = (parentId) => {
@@ -1,4 +1,4 @@
1
- import type { ChatNoticeLevel } from '../core/types/agent-types.js';
1
+ import type { ChatNoticeLevel, NoticeAction } from '../core/types/agent-types.js';
2
2
  export type HistoryEventType = 'user' | 'assistant' | 'tool' | 'interaction';
3
3
  export interface HistoryDebugDetails {
4
4
  /** Exact text handed to the adapter for this user turn. */
@@ -41,6 +41,8 @@ export interface HistoryEvent {
41
41
  text?: string;
42
42
  /** Semantic chat notice styling for system-authored assistant messages. */
43
43
  noticeLevel?: ChatNoticeLevel;
44
+ /** Control offered by that notice; persisted so it survives a transcript reload. */
45
+ noticeAction?: NoticeAction;
44
46
  /** tool name (tool events only). */
45
47
  toolName?: string;
46
48
  /** compact tool input summary (tool events only). */
@@ -87,6 +89,7 @@ interface RawEvent {
87
89
  originalTs?: string;
88
90
  text?: string;
89
91
  noticeLevel?: ChatNoticeLevel;
92
+ noticeAction?: NoticeAction;
90
93
  toolName?: string;
91
94
  toolInput?: string;
92
95
  /** DEBUG-only correlation and lossless payload fields. */
@@ -167,6 +170,7 @@ export declare class ConversationHistoryRepo {
167
170
  type: 'image' | 'video' | 'file';
168
171
  }[];
169
172
  noticeLevel?: ChatNoticeLevel;
173
+ noticeAction?: NoticeAction;
170
174
  }): Promise<void>;
171
175
  /** Append a tool call.
172
176
  * An optional `ts` override lets the caller share a single timestamp with the EventBus event. */
@@ -83,7 +83,7 @@ export class ConversationHistoryRepo {
83
83
  appendAssistant(sessionId, opts) {
84
84
  return this.append(sessionId, {
85
85
  type: 'assistant', text: opts.text, ts: opts.ts ?? nowIso(),
86
- attachments: opts.attachments, noticeLevel: opts.noticeLevel,
86
+ attachments: opts.attachments, noticeLevel: opts.noticeLevel, noticeAction: opts.noticeAction,
87
87
  });
88
88
  }
89
89
  /** Append a tool call.
@@ -274,6 +274,7 @@ export class ConversationHistoryRepo {
274
274
  type: 'assistant', text, ts: ev.ts, turnIndex: tIdx,
275
275
  ...(hasAttachments ? { attachments: ev.attachments } : {}),
276
276
  ...(ev.noticeLevel ? { noticeLevel: ev.noticeLevel } : {}),
277
+ ...(ev.noticeAction ? { noticeAction: ev.noticeAction } : {}),
277
278
  });
278
279
  }
279
280
  }
@@ -2,10 +2,20 @@ import type { CostEntry } from '../domain/costs/cost-tracker.js';
2
2
  export interface CostsData {
3
3
  entries: CostEntry[];
4
4
  }
5
+ /** A per-project override. Pair-only by design: a project either overrides BOTH limits or
6
+ * inherits BOTH globals — no per-field inheritance (see plan/per-project-budget.md). */
7
+ export interface ProjectBudget {
8
+ daily_usd: number;
9
+ monthly_usd: number;
10
+ }
5
11
  export interface BudgetConfig {
6
12
  daily_usd: number;
7
13
  monthly_usd: number;
14
+ /** Per-project overrides keyed by project id. Empty when no project overrides the globals. */
15
+ projects: Record<string, ProjectBudget>;
8
16
  }
17
+ /** Fill missing/invalid top-level fields from defaults and normalise the per-project map. */
18
+ export declare function migrateBudget(raw: unknown): BudgetConfig;
9
19
  export declare class CostRepo {
10
20
  private costMutex;
11
21
  private _ready;
@@ -43,6 +53,13 @@ export declare class CostRepo {
43
53
  readCosts(): Promise<CostsData>;
44
54
  readBudget(): Promise<BudgetConfig>;
45
55
  writeBudget(budget: BudgetConfig): Promise<void>;
56
+ /**
57
+ * Drop the cached budget so the next readBudget() re-reads from disk.
58
+ * budget.json is also written out-of-band by the UI service (mutate/config.ts writes the file
59
+ * directly to stay hermetic over its configDir argument); without this the in-process view
60
+ * would stay stale until restart.
61
+ */
62
+ invalidateBudget(): void;
46
63
  /**
47
64
  * Wait for any in-flight cost append / prune to complete, then flush budget repo.
48
65
  * For graceful SIGTERM drain.
@@ -1,7 +1,9 @@
1
1
  // input: costs.jsonl + budget.json
2
- // output: CostRepo (recordEntry / recordEntryBatch / readCosts / readBudget / writeBudget / flush)
2
+ // output: CostRepo (recordEntry / recordEntryBatch / readCosts / readBudget / writeBudget /
3
+ // invalidateBudget / flush) + migrateBudget
3
4
  // pos: Cost + Budget persistence layer. Costs use JSONL + append-only (avoiding repeated full-file reads/writes),
4
- // Budget still uses the JsonRepository abstraction.
5
+ // Budget still uses the JsonRepository abstraction. Budget carries global limits plus an
6
+ // optional per-project override map (pair-only overrides).
5
7
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
8
  import * as path from 'path';
7
9
  import fs from 'node:fs/promises';
@@ -10,7 +12,38 @@ import { atomicWrite } from '../core/atomic-write.js';
10
12
  import { AsyncMutex } from '../core/async-mutex.js';
11
13
  import { STORE_DIR, CONFIG_DIR } from '../core/paths.js';
12
14
  const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000;
13
- const DEFAULT_BUDGET = { daily_usd: 300, monthly_usd: 8000 };
15
+ const DEFAULT_BUDGET = { daily_usd: 300, monthly_usd: 8000, projects: {} };
16
+ function isPositiveNumber(v) {
17
+ return typeof v === 'number' && Number.isFinite(v) && v > 0;
18
+ }
19
+ /**
20
+ * Normalise the `projects` map from disk. Entries that are not a complete, positive
21
+ * {daily_usd, monthly_usd} pair are dropped rather than partially trusted — a half-written
22
+ * override would otherwise silently resolve against a field that does not exist.
23
+ */
24
+ function normalizeProjects(raw) {
25
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
26
+ return {};
27
+ const out = {};
28
+ for (const [id, value] of Object.entries(raw)) {
29
+ if (!id || !value || typeof value !== 'object')
30
+ continue;
31
+ const { daily_usd, monthly_usd } = value;
32
+ if (!isPositiveNumber(daily_usd) || !isPositiveNumber(monthly_usd))
33
+ continue;
34
+ out[id] = { daily_usd, monthly_usd };
35
+ }
36
+ return out;
37
+ }
38
+ /** Fill missing/invalid top-level fields from defaults and normalise the per-project map. */
39
+ export function migrateBudget(raw) {
40
+ const partial = (raw && typeof raw === 'object' ? raw : {});
41
+ return {
42
+ daily_usd: isPositiveNumber(partial.daily_usd) ? partial.daily_usd : DEFAULT_BUDGET.daily_usd,
43
+ monthly_usd: isPositiveNumber(partial.monthly_usd) ? partial.monthly_usd : DEFAULT_BUDGET.monthly_usd,
44
+ projects: normalizeProjects(partial.projects),
45
+ };
46
+ }
14
47
  function resolveCostsPath() {
15
48
  return process.env.CORTEX_COSTS_FILE || path.join(STORE_DIR, 'costs.jsonl');
16
49
  }
@@ -38,8 +71,8 @@ export class CostRepo {
38
71
  if (!this._budgetRepo) {
39
72
  this._budgetRepo = new JsonRepository({
40
73
  filePath: this._budgetPath ?? resolveBudgetPath(),
41
- defaultValue: () => ({ ...DEFAULT_BUDGET }),
42
- migrate: (raw) => ({ ...DEFAULT_BUDGET, ...raw }),
74
+ defaultValue: () => ({ ...DEFAULT_BUDGET, projects: {} }),
75
+ migrate: migrateBudget,
43
76
  });
44
77
  }
45
78
  return this._budgetRepo;
@@ -114,6 +147,15 @@ export class CostRepo {
114
147
  async writeBudget(budget) {
115
148
  await this.budgetRepo.write(budget);
116
149
  }
150
+ /**
151
+ * Drop the cached budget so the next readBudget() re-reads from disk.
152
+ * budget.json is also written out-of-band by the UI service (mutate/config.ts writes the file
153
+ * directly to stay hermetic over its configDir argument); without this the in-process view
154
+ * would stay stale until restart.
155
+ */
156
+ invalidateBudget() {
157
+ this._budgetRepo?.invalidate();
158
+ }
117
159
  /**
118
160
  * Wait for any in-flight cost append / prune to complete, then flush budget repo.
119
161
  * For graceful SIGTERM drain.
@@ -24,14 +24,4 @@ export declare class ProfileRepo {
24
24
  }
25
25
  export declare const profileRepo: ProfileRepo;
26
26
  export declare function setAdminNotifier(fn: (text: string) => void): void;
27
- /**
28
- * Watch profiles.json for external edits and hot-reload the cache.
29
- * Mirrors the pattern used by startMachineRegistryWatcher() in dispatch-utils.ts.
30
- *
31
- * Returns a stop function — call it to tear down the watcher (e.g. in tests or SIGTERM).
32
- *
33
- * @param repo ProfileRepo instance to invalidate on change (defaults to singleton).
34
- * @param filePath Path to watch (defaults to PROFILES_FILE).
35
- * @param onReload Called only after a valid file has replaced the cached profile snapshot.
36
- */
37
27
  export declare function startProfileWatcher(repo?: ProfileRepo, filePath?: string, onReload?: () => void): () => void;