@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.
- package/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
- package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
- package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
- package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
- package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
- package/defaults/prompts/directives/benchmark-coder.md +1 -0
- package/defaults/prompts/directives/benchmark-fixer.md +1 -0
- package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
- package/dist/agent-adapter/capabilities.d.ts +32 -1
- package/dist/agent-adapter/capabilities.js +39 -1
- package/dist/agent-adapter/claude/adapter.d.ts +15 -0
- package/dist/agent-adapter/claude/adapter.js +29 -7
- package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
- package/dist/agent-adapter/claude/spawn-args.js +29 -6
- package/dist/agent-adapter/index.js +11 -1
- package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
- package/dist/agent-adapter/normalize/tool-names.js +10 -0
- package/dist/agent-adapter/pi/adapter.d.ts +20 -8
- package/dist/agent-adapter/pi/adapter.js +130 -35
- package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
- package/dist/agent-adapter/pi/agent-dir.js +48 -89
- package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
- package/dist/agent-adapter/pi/custom-catalog.js +42 -0
- package/dist/agent-adapter/pi/defaults.d.ts +9 -0
- package/dist/agent-adapter/pi/defaults.js +14 -4
- package/dist/agent-adapter/pi/discovery.d.ts +1 -3
- package/dist/agent-adapter/pi/discovery.js +3 -15
- package/dist/agent-adapter/pi/event-parser.js +8 -0
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
- package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
- package/dist/agent-adapter/pi/mcp-duration.js +48 -0
- package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
- package/dist/agent-adapter/pi/policy-guard.js +111 -0
- package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
- package/dist/agent-adapter/pi/providers-config.js +101 -0
- package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
- package/dist/agent-adapter/pi/quota-probe.js +36 -0
- package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
- package/dist/agent-adapter/pi/quota-sink.js +31 -0
- package/dist/agent-adapter/pi/session-files.d.ts +2 -0
- package/dist/agent-adapter/pi/session-files.js +19 -0
- package/dist/agent-adapter/pi/session-support.d.ts +14 -3
- package/dist/agent-adapter/pi/session-support.js +8 -0
- package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
- package/dist/agent-adapter/pi/spawn-args.js +13 -0
- package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
- package/dist/agent-adapter/pi/tool-shims.js +32 -21
- package/dist/agent-adapter/pi/web-search.js +36 -8
- package/dist/agent-adapter/types.d.ts +14 -0
- package/dist/core/locales/en.d.ts +54 -1
- package/dist/core/locales/en.js +2 -0
- package/dist/core/locales/slices/commands.d.ts +12 -1
- package/dist/core/locales/slices/commands.js +24 -2
- package/dist/core/locales/slices/providers.d.ts +45 -0
- package/dist/core/locales/slices/providers.js +95 -0
- package/dist/core/locales/zh.js +2 -0
- package/dist/core/resilient-watch.d.ts +28 -0
- package/dist/core/resilient-watch.js +110 -0
- package/dist/core/settings.js +15 -20
- package/dist/core/types/agent-types.d.ts +6 -0
- package/dist/core/types/thread-types.d.ts +21 -3
- package/dist/core/utils.d.ts +21 -1
- package/dist/core/utils.js +37 -1
- package/dist/domain/agent-run/agent-run-cli.js +3 -1
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
- package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
- package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
- package/dist/domain/agent-run/identity.d.ts +5 -0
- package/dist/domain/agent-run/identity.js +4 -1
- package/dist/domain/agent-run/journal.d.ts +3 -2
- package/dist/domain/agent-run/manifest.js +11 -4
- package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
- package/dist/domain/agent-run/pinned-node-process.js +9 -0
- package/dist/domain/agent-run/role-surface.d.ts +2 -2
- package/dist/domain/agent-run/role-surface.js +7 -3
- package/dist/domain/agent-run/run-config.d.ts +10 -1
- package/dist/domain/agent-run/run-config.js +57 -6
- package/dist/domain/agent-run/runner.js +149 -31
- package/dist/domain/agents/facade.d.ts +37 -122
- package/dist/domain/agents/facade.js +47 -115
- package/dist/domain/agents/spawn-config.d.ts +135 -0
- package/dist/domain/agents/spawn-config.js +121 -0
- package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
- package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
- package/dist/domain/benchmark/arm-schema.d.ts +43 -0
- package/dist/domain/benchmark/arm-schema.js +243 -0
- package/dist/domain/benchmark/capabilities.d.ts +4 -0
- package/dist/domain/benchmark/capabilities.js +54 -0
- package/dist/domain/benchmark/decimal-text.d.ts +27 -0
- package/dist/domain/benchmark/decimal-text.js +67 -0
- package/dist/domain/benchmark/lease-echo.d.ts +43 -0
- package/dist/domain/benchmark/lease-echo.js +56 -0
- package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
- package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
- package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
- package/dist/domain/benchmark/policy-compiler.js +680 -0
- package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
- package/dist/domain/benchmark/resolved-policy.js +195 -0
- package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
- package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
- package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
- package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
- package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
- package/dist/domain/benchmark/variant-proposal.js +42 -0
- package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
- package/dist/domain/benchmark/workspace-lease.js +272 -0
- package/dist/domain/costs/codex-quota.d.ts +29 -0
- package/dist/domain/costs/codex-quota.js +102 -0
- package/dist/domain/costs/cost-tracker.d.ts +48 -9
- package/dist/domain/costs/cost-tracker.js +74 -18
- package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
- package/dist/domain/costs/rate-limit-throttle.js +61 -6
- package/dist/domain/costs/resume-registry.d.ts +3 -1
- package/dist/domain/costs/resume-registry.js +10 -1
- package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
- package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
- package/dist/domain/mcp/tools/cost.js +15 -6
- package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
- package/dist/domain/pi-providers/custom-provider-model.js +122 -0
- package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
- package/dist/domain/pi-providers/custom-provider-service.js +143 -0
- package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
- package/dist/domain/pi-providers/gateway-route-store.js +78 -0
- package/dist/domain/pi-providers/index.d.ts +4 -0
- package/dist/domain/pi-providers/index.js +8 -0
- package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
- package/dist/domain/pi-providers/models-json-store.js +77 -0
- package/dist/domain/remote/client-hot-reload.d.ts +9 -1
- package/dist/domain/remote/client-hot-reload.js +60 -12
- package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
- package/dist/domain/scheduling/jobs/_shared.js +11 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
- package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
- package/dist/domain/sessions/session-lifecycle.js +20 -1
- package/dist/domain/system/install-cli.js +8 -3
- package/dist/domain/system/system-notice.d.ts +4 -1
- package/dist/domain/system/system-notice.js +6 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
- package/dist/domain/tasks/dispatch-utils.js +24 -37
- package/dist/domain/threads/runner.d.ts +16 -1
- package/dist/domain/threads/runner.js +62 -8
- package/dist/domain/threads/template-loader.d.ts +5 -0
- package/dist/domain/threads/template-loader.js +120 -36
- package/dist/domain/threads/template-validate.d.ts +244 -0
- package/dist/domain/threads/template-validate.js +574 -0
- package/dist/domain/threads/template-validate.parity.d.ts +1 -0
- package/dist/domain/threads/template-validate.parity.js +47 -0
- package/dist/domain/threads/template-writer.d.ts +55 -0
- package/dist/domain/threads/template-writer.js +131 -0
- package/dist/domain/ui-service/app-router.d.ts +143 -1
- package/dist/domain/ui-service/app-router.js +29 -3
- package/dist/domain/ui-service/input-schemas.d.ts +228 -4
- package/dist/domain/ui-service/input-schemas.js +132 -1
- package/dist/domain/ui-service/mutate/config.d.ts +10 -1
- package/dist/domain/ui-service/mutate/config.js +45 -5
- package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
- package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
- package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
- package/dist/domain/ui-service/mutate/profiles.js +156 -0
- package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
- package/dist/domain/ui-service/mutate/schedules.js +53 -3
- package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
- package/dist/domain/ui-service/mutate/sessions.js +25 -1
- package/dist/domain/ui-service/mutate/system.d.ts +2 -1
- package/dist/domain/ui-service/mutate/system.js +17 -3
- package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
- package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
- package/dist/domain/ui-service/query/config.js +30 -0
- package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
- package/dist/domain/ui-service/query/custom-providers.js +13 -0
- package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
- package/dist/domain/ui-service/query/machine-detail.js +56 -0
- package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
- package/dist/domain/ui-service/query/machine-probe.js +136 -0
- package/dist/domain/ui-service/query/schedules.js +5 -0
- package/dist/domain/ui-service/query/sessions.js +8 -2
- package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
- package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
- package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
- package/dist/domain/ui-service/query/thread-templates.js +44 -7
- package/dist/domain/ui-service/types.d.ts +298 -7
- package/dist/domain/ui-service/ui-service.js +27 -3
- package/dist/entry/app.js +24 -3
- package/dist/entry/auth-cli.d.ts +4 -1
- package/dist/entry/auth-cli.js +10 -2
- package/dist/entry/cli-help.js +6 -2
- package/dist/entry/cli.js +2 -1
- package/dist/entry/daemon.d.ts +0 -11
- package/dist/entry/daemon.js +5 -49
- package/dist/entry/provider-cli.d.ts +16 -0
- package/dist/entry/provider-cli.js +203 -0
- package/dist/events/event-types.d.ts +2 -1
- package/dist/orchestration/agent-runner.js +3 -2
- package/dist/orchestration/routing/commands/cost.d.ts +8 -0
- package/dist/orchestration/routing/commands/cost.js +93 -21
- package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
- package/dist/orchestration/routing/commands/login-custom.js +89 -0
- package/dist/orchestration/routing/commands/login.d.ts +3 -0
- package/dist/orchestration/routing/commands/login.js +7 -0
- package/dist/orchestration/routing/message-router.js +48 -33
- package/dist/orchestration/routing/webhook.js +1 -1
- package/dist/orchestration/session-events.d.ts +2 -1
- package/dist/orchestration/session-events.js +1 -0
- package/dist/orchestration/thread-callback.js +1 -1
- package/dist/store/conversation-history-repo.d.ts +5 -1
- package/dist/store/conversation-history-repo.js +2 -1
- package/dist/store/cost-repo.d.ts +17 -0
- package/dist/store/cost-repo.js +47 -5
- package/dist/store/profile-repo.d.ts +0 -10
- package/dist/store/profile-repo.js +34 -56
- package/dist/store/session-registry-repo.d.ts +12 -0
- package/dist/store/session-registry-repo.js +16 -0
- package/package.json +1 -1
- package/web/dist/assets/index-DYMfaAi4.css +1 -0
- package/web/dist/assets/index-uOoZjGKa.js +141 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-DrNx9R6c.js +0 -139
- package/web/dist/assets/index-zpf3OSKC.css +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { costRepo } from '../../store/cost-repo.js';
|
|
2
|
-
export type { CostsData, BudgetConfig } from '../../store/cost-repo.js';
|
|
1
|
+
import { costRepo, type BudgetConfig } from '../../store/cost-repo.js';
|
|
2
|
+
export type { CostsData, BudgetConfig, ProjectBudget } from '../../store/cost-repo.js';
|
|
3
3
|
export interface CostEntry {
|
|
4
4
|
timestamp: string;
|
|
5
5
|
project: string;
|
|
@@ -52,8 +52,13 @@ export interface CostSummary {
|
|
|
52
52
|
total: TokenBucket;
|
|
53
53
|
};
|
|
54
54
|
entryCount: number;
|
|
55
|
-
/** Daily budget denominator
|
|
55
|
+
/** Daily budget denominator. Resolves to the project's own limit when the summary is
|
|
56
|
+
* project-scoped and that project has an override; otherwise the global `daily_usd`. */
|
|
56
57
|
dailyBudget: number;
|
|
58
|
+
/** Monthly budget denominator, resolved on the same rule as `dailyBudget`. */
|
|
59
|
+
monthlyBudget: number;
|
|
60
|
+
/** Which budget the two denominators above came from. */
|
|
61
|
+
budgetScope: BudgetScope;
|
|
57
62
|
/** Today's scoped spend extrapolated linearly by the elapsed fraction of the local day.
|
|
58
63
|
* 0 when nothing was spent today; noisy early in the day (small fraction) by construction. */
|
|
59
64
|
forecastToday: number;
|
|
@@ -64,6 +69,13 @@ export interface CostSummary {
|
|
|
64
69
|
* Categories with no scoped entries are simply absent (no fabricated placeholders). */
|
|
65
70
|
byTriggerScoped: Record<string, PeriodBucket>;
|
|
66
71
|
}
|
|
72
|
+
/** 'project' — the numbers come from budget.json `projects[<id>]`; 'global' — from the top level. */
|
|
73
|
+
export type BudgetScope = 'project' | 'global';
|
|
74
|
+
export interface ResolvedBudget {
|
|
75
|
+
daily_usd: number;
|
|
76
|
+
monthly_usd: number;
|
|
77
|
+
scope: BudgetScope;
|
|
78
|
+
}
|
|
67
79
|
export interface BudgetStatus {
|
|
68
80
|
withinBudget: boolean;
|
|
69
81
|
dailyBudget: number;
|
|
@@ -73,7 +85,16 @@ export interface BudgetStatus {
|
|
|
73
85
|
monthlySpent: number;
|
|
74
86
|
monthlyRemaining: number;
|
|
75
87
|
byMode: Record<string, ModeBuckets>;
|
|
88
|
+
/** The project this status was scoped to; null for the global view. */
|
|
89
|
+
project: string | null;
|
|
90
|
+
/** Whether the limits above are the project's own override or the inherited globals. */
|
|
91
|
+
scope: BudgetScope;
|
|
76
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* Resolve which budget applies to a project. Pure — takes the already-read config.
|
|
95
|
+
* A project with no override inherits the global pair in full (overrides are pair-only).
|
|
96
|
+
*/
|
|
97
|
+
export declare function pickBudget(config: BudgetConfig, projectId?: string | null): ResolvedBudget;
|
|
77
98
|
/**
|
|
78
99
|
* Record a cost entry after a Claude invocation.
|
|
79
100
|
* source: 'estimate' (default, from Claude CLI) or 'gateway' (from aistatus gateway usage data)
|
|
@@ -114,24 +135,42 @@ declare function getCostSummary(project?: string | null, opts?: {
|
|
|
114
135
|
now?: number;
|
|
115
136
|
}): Promise<CostSummary>;
|
|
116
137
|
/**
|
|
117
|
-
* Check global
|
|
118
|
-
*
|
|
138
|
+
* Check budget status. Without `project` this is the global view (all spend vs the global limits);
|
|
139
|
+
* with one, both the spend and the limits are scoped to that project — the limits being its own
|
|
140
|
+
* override when it has one, the inherited globals otherwise.
|
|
141
|
+
*
|
|
142
|
+
* Advisory only: `withinBudget` is reported, never enforced. No caller gates on it.
|
|
119
143
|
*/
|
|
120
|
-
declare function checkBudget(): Promise<BudgetStatus>;
|
|
144
|
+
declare function checkBudget(project?: string | null): Promise<BudgetStatus>;
|
|
121
145
|
/**
|
|
122
|
-
* Update
|
|
146
|
+
* Update budget limits. Without `project` the global pair is updated field-by-field and every
|
|
147
|
+
* per-project override is preserved. With `project`, BOTH limits are required (overrides are
|
|
148
|
+
* pair-only) and only that project's entry is written — globals and sibling overrides untouched.
|
|
123
149
|
*/
|
|
124
|
-
declare function setBudget({ daily_usd, monthly_usd }: {
|
|
150
|
+
declare function setBudget({ daily_usd, monthly_usd, project }: {
|
|
125
151
|
daily_usd?: number;
|
|
126
152
|
monthly_usd?: number;
|
|
153
|
+
project?: string | null;
|
|
127
154
|
}): Promise<{
|
|
128
155
|
daily_usd: number;
|
|
129
156
|
monthly_usd: number;
|
|
157
|
+
scope: BudgetScope;
|
|
130
158
|
}>;
|
|
159
|
+
/**
|
|
160
|
+
* Remove one project's override so it inherits the globals again.
|
|
161
|
+
* Returns false when the project had no override (nothing written).
|
|
162
|
+
*/
|
|
163
|
+
declare function clearProjectBudget(project: string): Promise<boolean>;
|
|
164
|
+
/** Every project that currently overrides the globals, sorted by id. */
|
|
165
|
+
declare function listProjectBudgets(): Promise<{
|
|
166
|
+
project: string;
|
|
167
|
+
daily_usd: number;
|
|
168
|
+
monthly_usd: number;
|
|
169
|
+
}[]>;
|
|
131
170
|
/**
|
|
132
171
|
* Format cost summary as a readable string for Slack.
|
|
133
172
|
*/
|
|
134
173
|
declare function formatCostReport(project?: string | null): Promise<string>;
|
|
135
174
|
/** Reset the project name cache. Pass an array to pre-seed the cache (for tests). */
|
|
136
175
|
declare function _resetProjectCache(names?: string[] | null): void;
|
|
137
|
-
export { costRepo, recordCost, detectProject, getCostSummary, checkBudget, setBudget, formatCostReport, _resetProjectCache };
|
|
176
|
+
export { costRepo, recordCost, detectProject, getCostSummary, checkBudget, setBudget, clearProjectBudget, listProjectBudgets, formatCostReport, _resetProjectCache, };
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// input: costs.json, budget.json, env overrides
|
|
2
|
-
// output: recordCost / checkBudget /
|
|
3
|
-
//
|
|
2
|
+
// output: recordCost / pickBudget / checkBudget / setBudget / clearProjectBudget /
|
|
3
|
+
// listProjectBudgets / formatCostReport / ...
|
|
4
|
+
// pos: budget resolution (global + per-project overrides) and cost record aggregation.
|
|
5
|
+
// Budget is advisory — nothing gates on it.
|
|
4
6
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
7
|
import { costRepo } from '../../store/cost-repo.js';
|
|
6
8
|
import { projectStore } from '../projects/index.js';
|
|
@@ -15,6 +17,17 @@ function getProjectNames() {
|
|
|
15
17
|
}
|
|
16
18
|
return _projectNames;
|
|
17
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Resolve which budget applies to a project. Pure — takes the already-read config.
|
|
22
|
+
* A project with no override inherits the global pair in full (overrides are pair-only).
|
|
23
|
+
*/
|
|
24
|
+
export function pickBudget(config, projectId) {
|
|
25
|
+
const override = projectId ? config.projects?.[projectId] : undefined;
|
|
26
|
+
if (override) {
|
|
27
|
+
return { daily_usd: override.daily_usd, monthly_usd: override.monthly_usd, scope: 'project' };
|
|
28
|
+
}
|
|
29
|
+
return { daily_usd: config.daily_usd, monthly_usd: config.monthly_usd, scope: 'global' };
|
|
30
|
+
}
|
|
18
31
|
const COST_CATEGORIES = ['total', 'api', 'plan'];
|
|
19
32
|
function normalizeCostMode(mode) {
|
|
20
33
|
return mode === 'plan' ? 'plan' : 'api';
|
|
@@ -209,6 +222,7 @@ async function getCostSummary(project, opts) {
|
|
|
209
222
|
const todayScoped = periods.today.total;
|
|
210
223
|
const fractionElapsed = (now - dayStart.getTime()) / DAY_MS;
|
|
211
224
|
const forecastToday = fractionElapsed > 0 ? todayScoped / fractionElapsed : todayScoped;
|
|
225
|
+
const resolved = pickBudget(budget, project);
|
|
212
226
|
return {
|
|
213
227
|
today: periods.today.total,
|
|
214
228
|
week: periods.week.total,
|
|
@@ -221,41 +235,80 @@ async function getCostSummary(project, opts) {
|
|
|
221
235
|
byBackend,
|
|
222
236
|
tokens,
|
|
223
237
|
entryCount: matchCount,
|
|
224
|
-
dailyBudget:
|
|
238
|
+
dailyBudget: resolved.daily_usd,
|
|
239
|
+
monthlyBudget: resolved.monthly_usd,
|
|
240
|
+
budgetScope: resolved.scope,
|
|
225
241
|
forecastToday,
|
|
226
242
|
dailyCost: dailyKeys.map(date => ({ date, cost: dailyMap.get(date) })),
|
|
227
243
|
byTriggerScoped,
|
|
228
244
|
};
|
|
229
245
|
}
|
|
230
246
|
/**
|
|
231
|
-
* Check global
|
|
232
|
-
*
|
|
247
|
+
* Check budget status. Without `project` this is the global view (all spend vs the global limits);
|
|
248
|
+
* with one, both the spend and the limits are scoped to that project — the limits being its own
|
|
249
|
+
* override when it has one, the inherited globals otherwise.
|
|
250
|
+
*
|
|
251
|
+
* Advisory only: `withinBudget` is reported, never enforced. No caller gates on it.
|
|
233
252
|
*/
|
|
234
|
-
async function checkBudget() {
|
|
235
|
-
const
|
|
253
|
+
async function checkBudget(project) {
|
|
254
|
+
const scoped = project ?? null;
|
|
255
|
+
const summary = await getCostSummary(scoped);
|
|
236
256
|
const budget = await costRepo.readBudget();
|
|
257
|
+
const resolved = pickBudget(budget, scoped);
|
|
237
258
|
return {
|
|
238
|
-
withinBudget: summary.today <
|
|
239
|
-
dailyBudget:
|
|
259
|
+
withinBudget: summary.today < resolved.daily_usd && summary.month < resolved.monthly_usd,
|
|
260
|
+
dailyBudget: resolved.daily_usd,
|
|
240
261
|
dailySpent: summary.today,
|
|
241
|
-
dailyRemaining: Math.max(0,
|
|
242
|
-
monthlyBudget:
|
|
262
|
+
dailyRemaining: Math.max(0, resolved.daily_usd - summary.today),
|
|
263
|
+
monthlyBudget: resolved.monthly_usd,
|
|
243
264
|
monthlySpent: summary.month,
|
|
244
|
-
monthlyRemaining: Math.max(0,
|
|
265
|
+
monthlyRemaining: Math.max(0, resolved.monthly_usd - summary.month),
|
|
245
266
|
byMode: summary.byMode,
|
|
267
|
+
project: scoped,
|
|
268
|
+
scope: resolved.scope,
|
|
246
269
|
};
|
|
247
270
|
}
|
|
248
271
|
/**
|
|
249
|
-
* Update
|
|
272
|
+
* Update budget limits. Without `project` the global pair is updated field-by-field and every
|
|
273
|
+
* per-project override is preserved. With `project`, BOTH limits are required (overrides are
|
|
274
|
+
* pair-only) and only that project's entry is written — globals and sibling overrides untouched.
|
|
250
275
|
*/
|
|
251
|
-
async function setBudget({ daily_usd, monthly_usd }) {
|
|
276
|
+
async function setBudget({ daily_usd, monthly_usd, project }) {
|
|
252
277
|
const budget = await costRepo.readBudget();
|
|
278
|
+
if (project) {
|
|
279
|
+
if (daily_usd == null || monthly_usd == null) {
|
|
280
|
+
throw Object.assign(new Error('A per-project budget must set both daily and monthly limits'), { code: 'invalid-args' });
|
|
281
|
+
}
|
|
282
|
+
budget.projects = { ...budget.projects, [project]: { daily_usd, monthly_usd } };
|
|
283
|
+
await costRepo.writeBudget(budget);
|
|
284
|
+
return { daily_usd, monthly_usd, scope: 'project' };
|
|
285
|
+
}
|
|
253
286
|
if (daily_usd != null)
|
|
254
287
|
budget.daily_usd = daily_usd;
|
|
255
288
|
if (monthly_usd != null)
|
|
256
289
|
budget.monthly_usd = monthly_usd;
|
|
257
290
|
await costRepo.writeBudget(budget);
|
|
258
|
-
return budget;
|
|
291
|
+
return { daily_usd: budget.daily_usd, monthly_usd: budget.monthly_usd, scope: 'global' };
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Remove one project's override so it inherits the globals again.
|
|
295
|
+
* Returns false when the project had no override (nothing written).
|
|
296
|
+
*/
|
|
297
|
+
async function clearProjectBudget(project) {
|
|
298
|
+
const budget = await costRepo.readBudget();
|
|
299
|
+
if (!budget.projects?.[project])
|
|
300
|
+
return false;
|
|
301
|
+
const { [project]: _removed, ...rest } = budget.projects;
|
|
302
|
+
budget.projects = rest;
|
|
303
|
+
await costRepo.writeBudget(budget);
|
|
304
|
+
return true;
|
|
305
|
+
}
|
|
306
|
+
/** Every project that currently overrides the globals, sorted by id. */
|
|
307
|
+
async function listProjectBudgets() {
|
|
308
|
+
const budget = await costRepo.readBudget();
|
|
309
|
+
return Object.entries(budget.projects ?? {})
|
|
310
|
+
.map(([project, limits]) => ({ project, ...limits }))
|
|
311
|
+
.sort((a, b) => a.project.localeCompare(b.project));
|
|
259
312
|
}
|
|
260
313
|
function buildModeBucket(periods, mode) {
|
|
261
314
|
return {
|
|
@@ -280,9 +333,12 @@ function formatTokens(count) {
|
|
|
280
333
|
*/
|
|
281
334
|
async function formatCostReport(project = null) {
|
|
282
335
|
const summary = await getCostSummary(project);
|
|
283
|
-
const budget = await checkBudget();
|
|
336
|
+
const budget = await checkBudget(project);
|
|
337
|
+
const scopeNote = project
|
|
338
|
+
? budget.scope === 'project' ? ' _(per-project limits)_' : ' _(inherited global limits)_'
|
|
339
|
+
: '';
|
|
284
340
|
const lines = [];
|
|
285
|
-
lines.push(project ? `*Cost Report (project: ${project})
|
|
341
|
+
lines.push(project ? `*Cost Report (project: ${project})*${scopeNote}` : '*Cost Report*');
|
|
286
342
|
lines.push(`• Today: $${summary.today.toFixed(2)} / $${budget.dailyBudget} (remaining: $${budget.dailyRemaining.toFixed(2)})`);
|
|
287
343
|
lines.push(`• This month: $${summary.month.toFixed(2)} / $${budget.monthlyBudget} (remaining: $${budget.monthlyRemaining.toFixed(2)})`);
|
|
288
344
|
lines.push(`• This week: $${summary.week.toFixed(2)}`);
|
|
@@ -336,4 +392,4 @@ async function formatCostReport(project = null) {
|
|
|
336
392
|
function _resetProjectCache(names) {
|
|
337
393
|
_projectNames = names ?? null;
|
|
338
394
|
}
|
|
339
|
-
export { costRepo, recordCost, detectProject, getCostSummary, checkBudget, setBudget, formatCostReport, _resetProjectCache };
|
|
395
|
+
export { costRepo, recordCost, detectProject, getCostSummary, checkBudget, setBudget, clearProjectBudget, listProjectBudgets, formatCostReport, _resetProjectCache, };
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import type { PlatformAdapter } from '../../platform/index.js';
|
|
2
|
+
/** Interactive action id used on rate-limit notices ("Resume now" button). Handlers are
|
|
3
|
+
* registered by the composition root via adapter.onAction; the button value carries the
|
|
4
|
+
* provider key (empty = all providers). */
|
|
5
|
+
export declare const RATE_LIMIT_CLEAR_ACTION_ID = "rate-limit:clear";
|
|
2
6
|
export interface RateLimitSource {
|
|
3
7
|
provider: string;
|
|
4
8
|
displayName: string;
|
|
@@ -36,6 +40,17 @@ export interface ThrottleStateView extends RateLimitThrottleState {
|
|
|
36
40
|
rateLimitedModes: string[];
|
|
37
41
|
rateLimitedTypes: string[];
|
|
38
42
|
}
|
|
43
|
+
export interface ClearedThrottleProvider {
|
|
44
|
+
provider: string;
|
|
45
|
+
displayName: string;
|
|
46
|
+
/** Window types cleared (e.g. five_hour / outage). */
|
|
47
|
+
types: string[];
|
|
48
|
+
/** Latest resetsAt among the cleared windows (epoch sec) — how long was remaining. */
|
|
49
|
+
resetsAt: number;
|
|
50
|
+
}
|
|
51
|
+
export interface ClearThrottleResult {
|
|
52
|
+
cleared: ClearedThrottleProvider[];
|
|
53
|
+
}
|
|
39
54
|
interface RateLimitInfo {
|
|
40
55
|
status?: string;
|
|
41
56
|
resetsAt?: number;
|
|
@@ -47,6 +62,13 @@ interface RateLimitInfo {
|
|
|
47
62
|
declare function initRateLimitThrottle(adapter: PlatformAdapter, persistence: ThrottlePersistence, onResume?: (providers: string[]) => void, onChange?: () => void): Promise<void>;
|
|
48
63
|
declare function activateOutageWindow(provider: string | null, durationMs: number): Promise<void>;
|
|
49
64
|
declare function handleRateLimitEvent(info: RateLimitInfo, rawSource?: string | RateLimitSource): Promise<void>;
|
|
65
|
+
/** Manually lift an active rate-limit (or outage) throttle early, for one provider or all.
|
|
66
|
+
* Walks the same recovery path as a natural window expiry: persists the cleared state,
|
|
67
|
+
* re-schedules the resume timer, notifies the UI, and fires onResume so paused work is
|
|
68
|
+
* dispatched immediately. Idempotent — no active window yields an empty result and no notices.
|
|
69
|
+
* If the provider is actually still rate-limited, the next API call's rate-limit event
|
|
70
|
+
* re-activates the throttle automatically. */
|
|
71
|
+
declare function clearThrottle(provider?: string | null): Promise<ClearThrottleResult>;
|
|
50
72
|
declare function isThrottled(): boolean;
|
|
51
73
|
declare function isProviderRateLimited(provider: string | null | undefined): boolean;
|
|
52
74
|
declare function isProviderUsageRateLimited(provider: string | null | undefined): boolean;
|
|
@@ -54,4 +76,4 @@ declare function isProviderModeRateLimited(provider: string, mode: string): bool
|
|
|
54
76
|
declare function isModeRateLimited(mode: string): boolean;
|
|
55
77
|
declare function getThrottleState(): ThrottleStateView;
|
|
56
78
|
declare function _testReset(): void;
|
|
57
|
-
export { initRateLimitThrottle, activateOutageWindow, handleRateLimitEvent, isThrottled, isProviderRateLimited, isProviderUsageRateLimited, isProviderModeRateLimited, isModeRateLimited, getThrottleState, _testReset, };
|
|
79
|
+
export { initRateLimitThrottle, activateOutageWindow, handleRateLimitEvent, clearThrottle, isThrottled, isProviderRateLimited, isProviderUsageRateLimited, isProviderModeRateLimited, isModeRateLimited, getThrottleState, _testReset, };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// input: provider state, persistence, timer generations
|
|
2
|
-
// output: committed throttle gates and
|
|
2
|
+
// output: committed throttle gates, clear callbacks, and manual early-release
|
|
3
3
|
// pos: Provider-scoped limit and outage state machine
|
|
4
4
|
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import { emitSystemNotice } from '../system/system-notice.js';
|
|
@@ -7,6 +7,10 @@ import { createLogger } from '../../core/log.js';
|
|
|
7
7
|
import { AsyncMutex } from '../../core/async-mutex.js';
|
|
8
8
|
import { Icons } from '../../core/icons.js';
|
|
9
9
|
const log = createLogger('rate-limit-throttle');
|
|
10
|
+
/** Interactive action id used on rate-limit notices ("Resume now" button). Handlers are
|
|
11
|
+
* registered by the composition root via adapter.onAction; the button value carries the
|
|
12
|
+
* provider key (empty = all providers). */
|
|
13
|
+
export const RATE_LIMIT_CLEAR_ACTION_ID = 'rate-limit:clear';
|
|
10
14
|
const TYPE_THRESHOLDS = {
|
|
11
15
|
five_hour: 0.90,
|
|
12
16
|
seven_day: 0.95,
|
|
@@ -71,10 +75,18 @@ function fireResume(providers) {
|
|
|
71
75
|
log.error(`onResume hook failed: ${error.message}`);
|
|
72
76
|
}
|
|
73
77
|
}
|
|
74
|
-
function sendDM(text, title = 'Rate limit') {
|
|
78
|
+
function sendDM(text, title = 'Rate limit', actions) {
|
|
75
79
|
if (!_adapter)
|
|
76
80
|
return;
|
|
77
|
-
void emitSystemNotice(_adapter, {
|
|
81
|
+
void emitSystemNotice(_adapter, {
|
|
82
|
+
text,
|
|
83
|
+
level: 'warning',
|
|
84
|
+
title,
|
|
85
|
+
...(actions && actions.length > 0 ? { actions } : {}),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function clearAction(provider) {
|
|
89
|
+
return [{ type: 'button', text: 'Resume now', actionId: RATE_LIMIT_CLEAR_ACTION_ID, value: provider, style: 'primary' }];
|
|
78
90
|
}
|
|
79
91
|
function formatResetTime(epochSec) {
|
|
80
92
|
return new Date(epochSec * 1000).toLocaleString('en-GB', {
|
|
@@ -301,7 +313,7 @@ async function activateOutageWindowLocked(provider, durationMs) {
|
|
|
301
313
|
const reset = state.windows.find((window) => window.type === OUTAGE_WINDOW_TYPE).resetsAt;
|
|
302
314
|
log.info(`Provider outage activated: provider=${source.provider}, durationMs=${durationMs}`);
|
|
303
315
|
sendDM(`${Icons.warning} ${source.displayName} provider outage detected.
|
|
304
|
-
Automated work will retry at ${formatResetTime(reset)} (in ${formatRemaining(reset)}).`, 'Provider outage');
|
|
316
|
+
Automated work will retry at ${formatResetTime(reset)} (in ${formatRemaining(reset)}).`, 'Provider outage', clearAction(source.provider));
|
|
305
317
|
}
|
|
306
318
|
async function activateOutageWindow(provider, durationMs) {
|
|
307
319
|
await _mutationMutex.run(() => activateOutageWindowLocked(provider, durationMs));
|
|
@@ -336,12 +348,55 @@ async function handleRateLimitEventLocked(info, rawSource) {
|
|
|
336
348
|
log.info(`Throttle updated: provider=${source.provider}, type=${info.rateLimitType}, utilization=${info.utilization}, mode=${source.mode ?? '(none)'}`);
|
|
337
349
|
if (isNewProvider) {
|
|
338
350
|
sendDM(`${Icons.warning} ${source.displayName} rate limit throttle activated [${info.rateLimitType}] — utilization ${(info.utilization * 100).toFixed(0)}%.
|
|
339
|
-
Auto-resume at ${formatResetTime(info.resetsAt)} (in ${formatRemaining(info.resetsAt)})
|
|
351
|
+
Auto-resume at ${formatResetTime(info.resetsAt)} (in ${formatRemaining(info.resetsAt)}).`, 'Rate limit', clearAction(source.provider));
|
|
340
352
|
}
|
|
341
353
|
}
|
|
342
354
|
async function handleRateLimitEvent(info, rawSource) {
|
|
343
355
|
await _mutationMutex.run(() => handleRateLimitEventLocked(info, rawSource));
|
|
344
356
|
}
|
|
357
|
+
async function clearThrottleLocked(provider) {
|
|
358
|
+
if (!_persistence)
|
|
359
|
+
return { cleared: [] };
|
|
360
|
+
const candidate = cloneProviders();
|
|
361
|
+
const targets = provider
|
|
362
|
+
? (candidate.has(provider) ? [provider] : [])
|
|
363
|
+
: [...candidate.keys()];
|
|
364
|
+
if (targets.length === 0)
|
|
365
|
+
return { cleared: [] };
|
|
366
|
+
const cleared = [];
|
|
367
|
+
for (const key of targets) {
|
|
368
|
+
const state = candidate.get(key);
|
|
369
|
+
const resetsAt = state.windows.reduce((max, w) => Math.max(max, w.resetsAt), 0);
|
|
370
|
+
cleared.push({
|
|
371
|
+
provider: key,
|
|
372
|
+
displayName: state.displayName,
|
|
373
|
+
types: state.windows.map((w) => w.type),
|
|
374
|
+
resetsAt,
|
|
375
|
+
});
|
|
376
|
+
candidate.delete(key);
|
|
377
|
+
}
|
|
378
|
+
await persist(candidate);
|
|
379
|
+
publishProviders(candidate);
|
|
380
|
+
scheduleResumeTimer();
|
|
381
|
+
fireChange();
|
|
382
|
+
fireResume(cleared.map((c) => c.provider));
|
|
383
|
+
for (const item of cleared) {
|
|
384
|
+
const names = item.types.join(', ');
|
|
385
|
+
log.info(`Throttle manually cleared: provider=${item.provider}, types=${names}`);
|
|
386
|
+
sendDM(`${Icons.ok} ${item.displayName} rate limit throttle cleared manually — paused work is resuming now.
|
|
387
|
+
If the provider is still rate-limited, the next request will re-activate the throttle automatically.`);
|
|
388
|
+
}
|
|
389
|
+
return { cleared };
|
|
390
|
+
}
|
|
391
|
+
/** Manually lift an active rate-limit (or outage) throttle early, for one provider or all.
|
|
392
|
+
* Walks the same recovery path as a natural window expiry: persists the cleared state,
|
|
393
|
+
* re-schedules the resume timer, notifies the UI, and fires onResume so paused work is
|
|
394
|
+
* dispatched immediately. Idempotent — no active window yields an empty result and no notices.
|
|
395
|
+
* If the provider is actually still rate-limited, the next API call's rate-limit event
|
|
396
|
+
* re-activates the throttle automatically. */
|
|
397
|
+
async function clearThrottle(provider) {
|
|
398
|
+
return _mutationMutex.run(() => clearThrottleLocked(provider));
|
|
399
|
+
}
|
|
345
400
|
function isThrottled() {
|
|
346
401
|
return _providers.size > 0;
|
|
347
402
|
}
|
|
@@ -384,4 +439,4 @@ function _testReset() {
|
|
|
384
439
|
_onResume = null;
|
|
385
440
|
_onChange = null;
|
|
386
441
|
}
|
|
387
|
-
export { initRateLimitThrottle, activateOutageWindow, handleRateLimitEvent, isThrottled, isProviderRateLimited, isProviderUsageRateLimited, isProviderModeRateLimited, isModeRateLimited, getThrottleState, _testReset, };
|
|
442
|
+
export { initRateLimitThrottle, activateOutageWindow, handleRateLimitEvent, clearThrottle, isThrottled, isProviderRateLimited, isProviderUsageRateLimited, isProviderModeRateLimited, isModeRateLimited, getThrottleState, _testReset, };
|
|
@@ -27,6 +27,8 @@ declare function initResumeRegistry(persistence: ResumePersistence, onChange?: (
|
|
|
27
27
|
/** Record an interrupted session/thread for later resume. Idempotent per key
|
|
28
28
|
* (direct→channel, thread→threadId): a newer record overwrites the older one. */
|
|
29
29
|
declare function recordResume(entry: ResumeEntry): void;
|
|
30
|
+
/** Cancel a queued direct resume — the user declining the auto-continue for that channel. */
|
|
31
|
+
declare function removeDirectResume(channel: string): boolean;
|
|
30
32
|
declare function removeThreadResume(threadId: string): boolean;
|
|
31
33
|
/** Drain the registry: return all pending entries and clear (persists the empty list).
|
|
32
34
|
* "take + clear" is atomic so each entry is dispatched at most once. */
|
|
@@ -35,4 +37,4 @@ declare function takeReadyResumes(activeProviders: string[]): ResumeEntry[];
|
|
|
35
37
|
declare function getResumeCountsByProvider(): Record<string, ProviderResumeCounts>;
|
|
36
38
|
declare function getResumeCount(): number;
|
|
37
39
|
declare function _testReset(): void;
|
|
38
|
-
export { initResumeRegistry, recordResume, removeThreadResume, takeAllResumes, takeReadyResumes, getResumeCountsByProvider, getResumeCount, _testReset, };
|
|
40
|
+
export { initResumeRegistry, recordResume, removeDirectResume, removeThreadResume, takeAllResumes, takeReadyResumes, getResumeCountsByProvider, getResumeCount, _testReset, };
|
|
@@ -68,6 +68,15 @@ function recordResume(entry) {
|
|
|
68
68
|
persist();
|
|
69
69
|
fireChange();
|
|
70
70
|
}
|
|
71
|
+
/** Cancel a queued direct resume — the user declining the auto-continue for that channel. */
|
|
72
|
+
function removeDirectResume(channel) {
|
|
73
|
+
const removed = _direct.delete(channel);
|
|
74
|
+
if (!removed)
|
|
75
|
+
return false;
|
|
76
|
+
persist();
|
|
77
|
+
fireChange();
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
71
80
|
function removeThreadResume(threadId) {
|
|
72
81
|
const removed = _threads.delete(threadId);
|
|
73
82
|
if (!removed)
|
|
@@ -120,4 +129,4 @@ function _testReset() {
|
|
|
120
129
|
_persistence = null;
|
|
121
130
|
_onChange = null;
|
|
122
131
|
}
|
|
123
|
-
export { initResumeRegistry, recordResume, removeThreadResume, takeAllResumes, takeReadyResumes, getResumeCountsByProvider, getResumeCount, _testReset, };
|
|
132
|
+
export { initResumeRegistry, recordResume, removeDirectResume, removeThreadResume, takeAllResumes, takeReadyResumes, getResumeCountsByProvider, getResumeCount, _testReset, };
|
|
@@ -2,11 +2,20 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
export declare const BENCHMARK_THREAD_POLICY_ENV = "CORTEX_BENCHMARK_THREAD_POLICY_PATH";
|
|
4
4
|
export declare const MAX_BENCHMARK_HANDOFF_LENGTH = 2000;
|
|
5
|
+
/**
|
|
6
|
+
* The document names WHICH trial this is and WHERE its compiler input lives. It carries no role, no
|
|
7
|
+
* system prompt, no tool list, no plugin dir, no MCP config, no thread template and no compiled
|
|
8
|
+
* policy: every one of those is composed by the production path and re-derived from
|
|
9
|
+
* `run_config_path` inside this process. `.strict()` is what makes that a property of the schema
|
|
10
|
+
* rather than a convention. Design section 16 (16.3.2) PW3 and PW3-NEG.
|
|
11
|
+
*/
|
|
5
12
|
declare const policySchema: z.ZodObject<{
|
|
6
|
-
schema_version: z.ZodLiteral<"cortex-benchmark-thread-policy/
|
|
13
|
+
schema_version: z.ZodLiteral<"cortex-benchmark-thread-policy/2">;
|
|
7
14
|
canonical_instruction: z.ZodString;
|
|
8
15
|
workspace_cwd: z.ZodString;
|
|
9
|
-
|
|
16
|
+
run_config_path: z.ZodString;
|
|
17
|
+
trial_root: z.ZodString;
|
|
18
|
+
template: z.ZodUnion<readonly [z.ZodLiteral<"benchmark-coder-review">, z.ZodLiteral<"benchmark-coder-review-fix">]>;
|
|
10
19
|
profile_name: z.ZodString;
|
|
11
20
|
root_run_id: z.ZodString;
|
|
12
21
|
trajectory_root: z.ZodString;
|
|
@@ -19,5 +28,20 @@ declare const policySchema: z.ZodObject<{
|
|
|
19
28
|
}, z.core.$strict>;
|
|
20
29
|
type BenchmarkThreadPolicy = Readonly<z.infer<typeof policySchema>>;
|
|
21
30
|
export declare function loadBenchmarkThreadPolicy(env?: NodeJS.ProcessEnv): BenchmarkThreadPolicy;
|
|
31
|
+
interface ProgressHeartbeatExtra {
|
|
32
|
+
_meta?: {
|
|
33
|
+
progressToken?: string | number;
|
|
34
|
+
};
|
|
35
|
+
sendNotification(notification: {
|
|
36
|
+
method: 'notifications/progress';
|
|
37
|
+
params: {
|
|
38
|
+
progressToken: string | number;
|
|
39
|
+
progress: number;
|
|
40
|
+
message: string;
|
|
41
|
+
};
|
|
42
|
+
}): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
/** §5.6 P7: keep the client-side timeout reset alive while the blocking call is running. */
|
|
45
|
+
export declare function startMcpProgressHeartbeat(extra: ProgressHeartbeatExtra, intervalMs?: number): () => void;
|
|
22
46
|
export declare function registerBenchmarkThreadRunTool(server: McpServer, policy: BenchmarkThreadPolicy, shutdownSignal: AbortSignal): void;
|
|
23
47
|
export {};
|
|
@@ -1,19 +1,33 @@
|
|
|
1
|
-
// input: immutable benchmark policy, MCP request signal, local orchestrator
|
|
2
|
-
// output: one bounded blocking thread_run tool
|
|
1
|
+
// input: immutable benchmark policy, MCP request signal/progress, local orchestrator
|
|
2
|
+
// output: one bounded blocking thread_run tool with progress heartbeats
|
|
3
3
|
// pos: Benchmark-only thread admission and result boundary
|
|
4
4
|
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
import { runBenchmarkThread, } from '../../agent-run/benchmark-local-thread-orchestrator.js';
|
|
8
|
+
import { runBenchmarkThread, trialThreadAdapterInput, } from '../../agent-run/benchmark-local-thread-orchestrator.js';
|
|
9
|
+
import { createBenchmarkTrialRunAgent } from '../../benchmark/trial-thread-adapter.js';
|
|
10
|
+
import { MCP_PROGRESS_HEARTBEAT_MS } from '../../../agent-adapter/pi/mcp-duration.js';
|
|
9
11
|
export const BENCHMARK_THREAD_POLICY_ENV = 'CORTEX_BENCHMARK_THREAD_POLICY_PATH';
|
|
10
12
|
export const MAX_BENCHMARK_HANDOFF_LENGTH = 2_000;
|
|
11
13
|
const MAX_BENCHMARK_SUMMARY_CODE_POINTS = 2_000;
|
|
14
|
+
/**
|
|
15
|
+
* The document names WHICH trial this is and WHERE its compiler input lives. It carries no role, no
|
|
16
|
+
* system prompt, no tool list, no plugin dir, no MCP config, no thread template and no compiled
|
|
17
|
+
* policy: every one of those is composed by the production path and re-derived from
|
|
18
|
+
* `run_config_path` inside this process. `.strict()` is what makes that a property of the schema
|
|
19
|
+
* rather than a convention. Design section 16 (16.3.2) PW3 and PW3-NEG.
|
|
20
|
+
*/
|
|
12
21
|
const policySchema = z.object({
|
|
13
|
-
schema_version: z.literal('cortex-benchmark-thread-policy/
|
|
22
|
+
schema_version: z.literal('cortex-benchmark-thread-policy/2'),
|
|
14
23
|
canonical_instruction: z.string().min(1),
|
|
15
24
|
workspace_cwd: z.string().min(1).refine(path.isAbsolute, 'workspace_cwd must be absolute'),
|
|
16
|
-
|
|
25
|
+
run_config_path: z.string().min(1).refine(path.isAbsolute, 'run_config_path must be absolute'),
|
|
26
|
+
trial_root: z.string().min(1).refine(path.isAbsolute, 'trial_root must be absolute'),
|
|
27
|
+
template: z.union([
|
|
28
|
+
z.literal('benchmark-coder-review'),
|
|
29
|
+
z.literal('benchmark-coder-review-fix'),
|
|
30
|
+
]),
|
|
17
31
|
profile_name: z.string().min(1),
|
|
18
32
|
root_run_id: z.string().min(1),
|
|
19
33
|
trajectory_root: z.string().min(1).refine(path.isAbsolute, 'trajectory_root must be absolute'),
|
|
@@ -70,7 +84,7 @@ function linkedSignal(request, shutdown) {
|
|
|
70
84
|
link(shutdown);
|
|
71
85
|
return controller.signal;
|
|
72
86
|
}
|
|
73
|
-
function orchestratorRequest(policy, input, signal) {
|
|
87
|
+
function orchestratorRequest(policy, input, signal, trialPolicy) {
|
|
74
88
|
return {
|
|
75
89
|
workspaceCwd: policy.workspace_cwd,
|
|
76
90
|
template: policy.template,
|
|
@@ -79,6 +93,9 @@ function orchestratorRequest(policy, input, signal) {
|
|
|
79
93
|
profileName: policy.profile_name,
|
|
80
94
|
rootRunId: policy.root_run_id,
|
|
81
95
|
trajectoryRoot: policy.trajectory_root,
|
|
96
|
+
runConfigPath: policy.run_config_path,
|
|
97
|
+
trialRoot: policy.trial_root,
|
|
98
|
+
trialPolicy,
|
|
82
99
|
limits: {
|
|
83
100
|
maxSteps: policy.limits.max_steps,
|
|
84
101
|
maxCostUsd: policy.limits.max_cost_usd,
|
|
@@ -118,6 +135,45 @@ function callLimitResult() {
|
|
|
118
135
|
message: 'thread_run has already been admitted for this trial',
|
|
119
136
|
}, true);
|
|
120
137
|
}
|
|
138
|
+
/** §5.6 P7: keep the client-side timeout reset alive while the blocking call is running. */
|
|
139
|
+
export function startMcpProgressHeartbeat(extra, intervalMs = MCP_PROGRESS_HEARTBEAT_MS) {
|
|
140
|
+
const progressToken = extra._meta?.progressToken;
|
|
141
|
+
if (progressToken === undefined)
|
|
142
|
+
return () => { };
|
|
143
|
+
let progress = 0;
|
|
144
|
+
const timer = setInterval(() => {
|
|
145
|
+
progress += 1;
|
|
146
|
+
void extra.sendNotification({
|
|
147
|
+
method: 'notifications/progress',
|
|
148
|
+
params: { progressToken, progress, message: 'thread_run in progress' },
|
|
149
|
+
}).catch(() => { });
|
|
150
|
+
}, intervalMs);
|
|
151
|
+
timer.unref?.();
|
|
152
|
+
return () => clearInterval(timer);
|
|
153
|
+
}
|
|
154
|
+
async function executeAdmittedRun(policy, input, shutdownSignal, extra) {
|
|
155
|
+
const stopHeartbeat = startMcpProgressHeartbeat(extra);
|
|
156
|
+
try {
|
|
157
|
+
const signal = linkedSignal(extra.signal, shutdownSignal);
|
|
158
|
+
// The trial is re-compiled here, in this process, from the document the parent's `agent-run`
|
|
159
|
+
// was given. Nothing pre-built travels on the request, and the override set is exactly the one
|
|
160
|
+
// member — a lifecycle hook runner is refused by presence on the far side.
|
|
161
|
+
const trial = trialThreadAdapterInput(policy.run_config_path, policy.trial_root);
|
|
162
|
+
const result = await runBenchmarkThread(orchestratorRequest(policy, input, signal, trial.policy), { runAgent: createBenchmarkTrialRunAgent(trial) });
|
|
163
|
+
if (result.state !== 'completed' || !result.manifestCommitted)
|
|
164
|
+
return failedRunResult(result);
|
|
165
|
+
const payload = successPayload(result);
|
|
166
|
+
return { ...textResult(payload), structuredContent: payload };
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
return textResult({
|
|
170
|
+
code: 'benchmark_thread_run_failed', message: error.message,
|
|
171
|
+
}, true);
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
stopHeartbeat();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
121
177
|
export function registerBenchmarkThreadRunTool(server, policy, shutdownSignal) {
|
|
122
178
|
let admitted = false;
|
|
123
179
|
server.registerTool('thread_run', {
|
|
@@ -128,19 +184,6 @@ export function registerBenchmarkThreadRunTool(server, policy, shutdownSignal) {
|
|
|
128
184
|
if (admitted)
|
|
129
185
|
return callLimitResult();
|
|
130
186
|
admitted = true;
|
|
131
|
-
|
|
132
|
-
const signal = linkedSignal(extra.signal, shutdownSignal);
|
|
133
|
-
const result = await runBenchmarkThread(orchestratorRequest(policy, input, signal));
|
|
134
|
-
if (result.state !== 'completed' || !result.manifestCommitted) {
|
|
135
|
-
return failedRunResult(result);
|
|
136
|
-
}
|
|
137
|
-
const payload = successPayload(result);
|
|
138
|
-
return { ...textResult(payload), structuredContent: payload };
|
|
139
|
-
}
|
|
140
|
-
catch (error) {
|
|
141
|
-
return textResult({
|
|
142
|
-
code: 'benchmark_thread_run_failed', message: error.message,
|
|
143
|
-
}, true);
|
|
144
|
-
}
|
|
187
|
+
return executeAdmittedRun(policy, input, shutdownSignal, extra);
|
|
145
188
|
});
|
|
146
189
|
}
|
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
// input: McpServer, cost-repo, cost-tracker
|
|
2
|
-
// output: cost_query tool registration
|
|
3
|
-
// pos: MCP tool for querying current cost and budget status
|
|
2
|
+
// output: cost_query tool registration (optional projectId scope)
|
|
3
|
+
// pos: MCP tool for querying current cost and budget status, global or per-project
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
-
import {
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { getCostSummary, pickBudget } from '../../costs/cost-tracker.js';
|
|
6
7
|
import { costRepo } from '../../../store/cost-repo.js';
|
|
7
8
|
export function registerCostTools(server) {
|
|
8
|
-
server.tool('cost_query', 'Query current cost and budget status. Returns today/month spending, budget limits, remaining budget, api/plan cost split, source breakdown (gateway vs estimate), and token usage.
|
|
9
|
+
server.tool('cost_query', 'Query current cost and budget status. Returns today/month spending, budget limits, remaining budget, api/plan cost split, source breakdown (gateway vs estimate), and token usage. Pass projectId to scope both the spend and the budget limits to one project.', {
|
|
10
|
+
projectId: z.string().optional().describe('Scope the report to one project. Omit for the global view.'),
|
|
11
|
+
}, { readOnlyHint: true }, async ({ projectId }) => {
|
|
9
12
|
try {
|
|
10
|
-
const
|
|
11
|
-
const
|
|
13
|
+
const scope = projectId ?? null;
|
|
14
|
+
const budgetConfig = await costRepo.readBudget();
|
|
15
|
+
const budget = pickBudget(budgetConfig, scope);
|
|
16
|
+
const summaryData = await getCostSummary(scope);
|
|
12
17
|
const now = new Date();
|
|
13
18
|
const pad = (n) => String(n).padStart(2, '0');
|
|
14
19
|
const todayStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
|
@@ -21,7 +26,11 @@ export function registerCostTools(server) {
|
|
|
21
26
|
const monthPlan = summaryData.byMode.month.plan;
|
|
22
27
|
const dailyPct = ((todayTotal / budget.daily_usd) * 100).toFixed(1);
|
|
23
28
|
const monthlyPct = ((monthTotal / budget.monthly_usd) * 100).toFixed(1);
|
|
29
|
+
const scopeLabel = budget.scope === 'project' ? 'per-project budget' : 'global budget';
|
|
24
30
|
const lines = [
|
|
31
|
+
scope
|
|
32
|
+
? `Project: ${scope} (${scopeLabel})`
|
|
33
|
+
: 'Scope: all projects (global budget)',
|
|
25
34
|
`Today (${todayStr}): $${todayTotal.toFixed(2)} / $${budget.daily_usd} (${dailyPct}%, ${summaryData.entryCount} sessions in window)`,
|
|
26
35
|
` API: $${todayApi.toFixed(2)} | Plan: $${todayPlan.toFixed(2)}`,
|
|
27
36
|
`Month (${monthStr}): $${monthTotal.toFixed(2)} / $${budget.monthly_usd} (${monthlyPct}%)`,
|