@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
@@ -3,11 +3,11 @@
3
3
  // pos: PI provider and resume-target discovery
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { execFile } from 'child_process';
6
- import { readdirSync } from 'fs';
7
- import * as path from 'path';
8
6
  import { parsePiListModelsOutput } from '../../core/gateway-generator.js';
9
- import { selectPISessionFilename } from '../../core/pi-session-filename.js';
10
7
  import { createLogger } from '../../core/log.js';
8
+ // Filename lookup moved out so a trial adapter can resolve a transcript path without importing
9
+ // this module's host-scanning provider singleton (design §13 A7/A8, T12).
10
+ export { findPISessionFilePath } from './session-files.js';
11
11
  const log = createLogger('pi-adapter');
12
12
  export const PI_PROVIDER_CACHE_TTL_MS = 5 * 60_000;
13
13
  export const PI_PROVIDER_RETRY_MS = 30_000;
@@ -87,15 +87,3 @@ export function createPIProviderDiscovery(options = {}) {
87
87
  return new CachedPIProviderDiscovery(options.scan ?? discoverPIProviders, options.now ?? Date.now, options.cacheTtlMs ?? PI_PROVIDER_CACHE_TTL_MS, options.retryMs ?? PI_PROVIDER_RETRY_MS);
88
88
  }
89
89
  export const piProviderDiscovery = createPIProviderDiscovery();
90
- /** Resolve PI's exact id-bearing filename without opening transcript bodies. */
91
- export function findPISessionFilePath(sessionDir, sessionId) {
92
- if (!sessionId)
93
- return null;
94
- try {
95
- const filename = selectPISessionFilename(readdirSync(sessionDir), sessionId);
96
- return filename ? path.join(sessionDir, filename) : null;
97
- }
98
- catch {
99
- return null;
100
- }
101
- }
@@ -4,6 +4,7 @@
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { toCanonical } from '../normalize/tool-names.js';
6
6
  import { isPlanFilePath } from '../claude/event-parser.js';
7
+ import { decodeQuotaNotice } from '../../domain/costs/codex-quota.js';
7
8
  export function createPIEventParserState() {
8
9
  return {
9
10
  sessionId: null,
@@ -349,6 +350,13 @@ function handleExtensionUiRequest(ev) {
349
350
  const method = ev['method'];
350
351
  if (typeof id !== 'string' || typeof method !== 'string')
351
352
  return [];
353
+ // `notify` is PI's only fire-and-forget message to the host, so the quota probe extension rides
354
+ // it to report what it read off the provider response headers. Anything without the quota prefix
355
+ // is a real user notification and keeps falling through to the drop below.
356
+ if (method === 'notify') {
357
+ const reading = decodeQuotaNotice(ev['message']);
358
+ return reading ? [{ type: 'rate_limit', raw: reading }] : [];
359
+ }
352
360
  // Only dialog methods produce ask_user_question; fire-and-forget methods → [].
353
361
  if (method !== 'select' && method !== 'confirm' && method !== 'input' && method !== 'editor') {
354
362
  return [];
@@ -1,6 +1,8 @@
1
1
  import type { ExtensionAPI } from './pi-ext-types.js';
2
2
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
3
3
  import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
4
+ /** The one server `benchmark-thread-run` exposes, named as the Claude-side config names it. */
5
+ export declare const BENCHMARK_THREAD_SERVER_NAME = "cortex-benchmark-thread";
4
6
  type BridgeClient = Pick<Client, 'listTools' | 'callTool'>;
5
7
  export interface McpClientHandle {
6
8
  client: BridgeClient;
@@ -11,6 +13,17 @@ export interface McpBridgeDeps {
11
13
  spawnClient(serverPath: string, serverName: string): Promise<McpClientHandle>;
12
14
  reportFailure(error: unknown): void;
13
15
  }
16
+ export interface ServerState {
17
+ name: string;
18
+ path: string;
19
+ handle: McpClientHandle | null;
20
+ }
21
+ /**
22
+ * §5.6 P1: under a restricted composition the server set is the composition's and nothing else —
23
+ * decided before any ambient switch is consulted, so a stray `CORTEX_THREAD_ID` or `SLACK_CHANNEL`
24
+ * in the child environment cannot layer a server onto a benchmark trial.
25
+ */
26
+ export declare function buildServerStates(env: NodeJS.ProcessEnv): ServerState[];
14
27
  export declare function installMcpBridge(pi: ExtensionAPI, deps?: McpBridgeDeps): Promise<void>;
15
28
  export default function mcpBridge(pi: ExtensionAPI): Promise<void>;
16
29
  export {};
@@ -9,6 +9,8 @@ import { createLogger } from '../../core/log.js';
9
9
  import { resolve, dirname } from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { mapMcpContent, shouldLoadFeishu, shouldLoadSlack, shouldLoadThreadControl, shouldLoadWeb, } from './mcp-bridge-logic.js';
12
+ import { benchmarkCallOptions, remainingTrialMs } from './mcp-duration.js';
13
+ import { PI_MCP_COMPOSITION_ENV } from './policy-guard.js';
12
14
  // __dirname is provided by PI's jiti CJS compat layer when loading .ts extension files.
13
15
  // In ESM contexts (agent-server tests via tsx), derive it from import.meta.url instead.
14
16
  // eslint-disable-next-line no-undef
@@ -22,6 +24,9 @@ const EXT_SERVER_PATH = resolve(_dirname, '../../domain/mcp/server.js');
22
24
  const SLACK_SERVER_PATH = resolve(_dirname, '../../domain/mcp/slack-server.js');
23
25
  const FEISHU_SERVER_PATH = resolve(_dirname, '../../domain/mcp/feishu-server.js');
24
26
  const WEB_SERVER_PATH = resolve(_dirname, '../../domain/mcp/web-server.js');
27
+ const BENCHMARK_THREAD_SERVER_PATH = resolve(_dirname, '../../domain/mcp/benchmark-thread-server.js');
28
+ /** The one server `benchmark-thread-run` exposes, named as the Claude-side config names it. */
29
+ export const BENCHMARK_THREAD_SERVER_NAME = 'cortex-benchmark-thread';
25
30
  const log = createLogger('pi-mcp-bridge');
26
31
  async function spawnMcpClient(serverPath, serverName) {
27
32
  const transport = new StdioClientTransport({
@@ -48,7 +53,18 @@ async function spawnMcpClient(serverPath, serverName) {
48
53
  throw error;
49
54
  }
50
55
  }
51
- function buildServerStates(env) {
56
+ /**
57
+ * §5.6 P1: under a restricted composition the server set is the composition's and nothing else —
58
+ * decided before any ambient switch is consulted, so a stray `CORTEX_THREAD_ID` or `SLACK_CHANNEL`
59
+ * in the child environment cannot layer a server onto a benchmark trial.
60
+ */
61
+ export function buildServerStates(env) {
62
+ const composition = env[PI_MCP_COMPOSITION_ENV];
63
+ if (composition === 'none')
64
+ return [];
65
+ if (composition === 'benchmark-thread-run') {
66
+ return [{ name: BENCHMARK_THREAD_SERVER_NAME, path: BENCHMARK_THREAD_SERVER_PATH, handle: null }];
67
+ }
52
68
  const core = { name: 'core', path: CORE_SERVER_PATH, handle: null };
53
69
  if (env.CORTEX_PI_SUBAGENT === '1')
54
70
  return [core];
@@ -149,18 +165,27 @@ class McpBridgeSession {
149
165
  }
150
166
  }
151
167
  }
168
+ /**
169
+ * §5.6 P2/P5/P6: the options for one call, derived now. A trial deadline yields the explicit
170
+ * bounded window; its absence yields signal forwarding alone, because this bridge has no mandate
171
+ * to invent a ceiling for a daemon session.
172
+ */
173
+ callOptions(signal) {
174
+ const remainingMs = remainingTrialMs(this.deps.env);
175
+ if (remainingMs === null)
176
+ return signal ? { signal } : {};
177
+ return benchmarkCallOptions(remainingMs, signal, () => { });
178
+ }
152
179
  registerTool(handle, tool) {
153
180
  const parameters = Type.Unsafe(tool.inputSchema);
181
+ const callOptions = (signal) => this.callOptions(signal);
154
182
  this.pi.registerTool({
155
183
  name: tool.name,
156
184
  label: tool.name,
157
185
  description: tool.description ?? '',
158
186
  parameters,
159
- async execute(_id, params) {
160
- const result = await handle.client.callTool({
161
- name: tool.name,
162
- arguments: params,
163
- });
187
+ async execute(_id, params, signal) {
188
+ const result = await handle.client.callTool({ name: tool.name, arguments: params }, undefined, callOptions(signal));
164
189
  const content = result.content.map(mapMcpContent);
165
190
  return { content, details: { isError: result.isError ?? false } };
166
191
  },
@@ -0,0 +1,28 @@
1
+ import type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';
2
+ /** The trial deadline as an absolute epoch. A duration cannot cross a process boundary and stay
3
+ * honest, so the child is handed the instant and derives its budget at the moment of use (P5). */
4
+ export declare const PI_BENCHMARK_DEADLINE_ENV = "CORTEX_BENCHMARK_DEADLINE_EPOCH_MS";
5
+ /**
6
+ * P3: `SUPERVISOR_GRACE_MS + QUIESCENCE_MARGIN_MS` — the same window the shipped quiescence budget
7
+ * uses. An MCP call outlives the deadline by exactly the interval in which finalization may run, so
8
+ * a tool that is still answering when the deadline lands is cut off with the trial, not before it.
9
+ */
10
+ export declare const MCP_CLEANUP_GRACE_MS: number;
11
+ /**
12
+ * P7: the interval at which a running call is expected to report progress. Strictly below the SDK's
13
+ * 60 000 ms reference window — four beats per window leaves three missed beats of tolerance before a
14
+ * client on the default timeout would give up.
15
+ */
16
+ export declare const MCP_PROGRESS_HEARTBEAT_MS = 15000;
17
+ /**
18
+ * P5: the remaining trial budget, recomputed on every read. Returns null when this process carries
19
+ * no trial deadline, which is the daemon case — an absent deadline is not a budget of zero and not
20
+ * an unbounded one, it is the absence of a bound this module may impose.
21
+ */
22
+ export declare function remainingTrialMs(env: NodeJS.ProcessEnv, nowEpochMs?: number): number | null;
23
+ /**
24
+ * P2/P4/P6: the options every benchmark `callTool` carries. `timeout` and `maxTotalTimeout` are the
25
+ * same value, so `resetTimeoutOnProgress` can keep a live call from expiring mid-answer while
26
+ * heartbeats still cannot push it past deadline + grace.
27
+ */
28
+ export declare function benchmarkCallOptions(remainingMs: number, signal?: AbortSignal, onprogress?: RequestOptions['onprogress']): RequestOptions;
@@ -0,0 +1,48 @@
1
+ // input: the trial's absolute deadline, a PI abort signal and a progress callback
2
+ // output: explicit MCP RequestOptions bounding one benchmark tool call
3
+ // pos: PI MCP duration contract (design §5.6 P2–P7)
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ /** The trial deadline as an absolute epoch. A duration cannot cross a process boundary and stay
6
+ * honest, so the child is handed the instant and derives its budget at the moment of use (P5). */
7
+ export const PI_BENCHMARK_DEADLINE_ENV = 'CORTEX_BENCHMARK_DEADLINE_EPOCH_MS';
8
+ /**
9
+ * P3: `SUPERVISOR_GRACE_MS + QUIESCENCE_MARGIN_MS` — the same window the shipped quiescence budget
10
+ * uses. An MCP call outlives the deadline by exactly the interval in which finalization may run, so
11
+ * a tool that is still answering when the deadline lands is cut off with the trial, not before it.
12
+ */
13
+ export const MCP_CLEANUP_GRACE_MS = 1_000 + 5_000;
14
+ /**
15
+ * P7: the interval at which a running call is expected to report progress. Strictly below the SDK's
16
+ * 60 000 ms reference window — four beats per window leaves three missed beats of tolerance before a
17
+ * client on the default timeout would give up.
18
+ */
19
+ export const MCP_PROGRESS_HEARTBEAT_MS = 15_000;
20
+ /**
21
+ * P5: the remaining trial budget, recomputed on every read. Returns null when this process carries
22
+ * no trial deadline, which is the daemon case — an absent deadline is not a budget of zero and not
23
+ * an unbounded one, it is the absence of a bound this module may impose.
24
+ */
25
+ export function remainingTrialMs(env, nowEpochMs = Date.now()) {
26
+ const raw = env[PI_BENCHMARK_DEADLINE_ENV];
27
+ if (raw === undefined || raw.trim() === '')
28
+ return null;
29
+ const deadlineEpochMs = Number(raw);
30
+ if (!Number.isFinite(deadlineEpochMs))
31
+ return null;
32
+ return Math.max(0, deadlineEpochMs - nowEpochMs);
33
+ }
34
+ /**
35
+ * P2/P4/P6: the options every benchmark `callTool` carries. `timeout` and `maxTotalTimeout` are the
36
+ * same value, so `resetTimeoutOnProgress` can keep a live call from expiring mid-answer while
37
+ * heartbeats still cannot push it past deadline + grace.
38
+ */
39
+ export function benchmarkCallOptions(remainingMs, signal, onprogress) {
40
+ const budgetMs = remainingMs + MCP_CLEANUP_GRACE_MS;
41
+ return {
42
+ timeout: budgetMs,
43
+ maxTotalTimeout: budgetMs,
44
+ resetTimeoutOnProgress: true,
45
+ ...(signal ? { signal } : {}),
46
+ ...(onprogress ? { onprogress } : {}),
47
+ };
48
+ }
@@ -0,0 +1,40 @@
1
+ /** Serialized compiled guard for this role. Its presence — even empty — puts the PI process in
2
+ * guarded mode, where no branch may return allow by default (design §13 GT6, §6.8 G3). */
3
+ export declare const PI_POLICY_GUARD_ENV = "CORTEX_PI_POLICY_GUARD";
4
+ /** The guard's lease-state input (§6.8 G4). */
5
+ export declare const PI_LEASE_STATE_ENV = "CORTEX_PI_LEASE_STATE";
6
+ /** Resolved MCP composition for this spawn; the bridge derives its server set from it (§5.6 P1). */
7
+ export declare const PI_MCP_COMPOSITION_ENV = "CORTEX_PI_MCP_COMPOSITION";
8
+ /** D-GUARD-STATIC: Gate 2 lands the guard mechanism, not the lease transition, so the state is a
9
+ * constant the factory supplies. Gates 3/6/7 vary this same parameter without reshaping the guard. */
10
+ export declare const GATE2_LEASE_STATE = "parent-writable";
11
+ export interface GuardDecision {
12
+ allow: boolean;
13
+ reason: string;
14
+ }
15
+ export type PolicyGuardEvaluator = (toolName: string, leaseState: string) => GuardDecision;
16
+ /**
17
+ * Read a compiled guard as the per-lease-state allow-list of §6.6, in PI-native names. Throws on
18
+ * anything else: an unreadable guard must not be turned into a permissive one.
19
+ */
20
+ export declare function compilePiPolicyGuard(raw: unknown): PolicyGuardEvaluator;
21
+ /**
22
+ * The decision every guarded PI tool dispatch goes through. A missing evaluator, an evaluator that
23
+ * throws and an evaluator that answers with anything other than an explicit allow all deny — there
24
+ * is deliberately no branch here that yields allow without one (§6.8 G3, battery T8).
25
+ */
26
+ export declare function guardDecision(evaluator: PolicyGuardEvaluator | null, toolName: string, leaseState: string): GuardDecision;
27
+ export interface PiToolGate {
28
+ /** True when the benchmark policy guard governs this process. */
29
+ readonly guarded: boolean;
30
+ decide(nativeToolName: string, claudeLabel?: string): GuardDecision;
31
+ }
32
+ /** The guarded gate every benchmark PI process runs under. Exported so a caller can install an
33
+ * evaluator that is not env-derived; the decision path is the same `guardDecision` either way. */
34
+ export declare function benchmarkToolGate(evaluator: PolicyGuardEvaluator | null, leaseState: string): PiToolGate;
35
+ /**
36
+ * Pick the gate this PI process runs under. The selection is total and ordered: a guard present in
37
+ * the environment always wins, and the guarded branch never falls through to the allowlist gate.
38
+ * That is what removes §6.6 defect 4 — the empty-value allow-all — from the benchmark path.
39
+ */
40
+ export declare function resolvePiToolGate(env: NodeJS.ProcessEnv): PiToolGate;
@@ -0,0 +1,111 @@
1
+ // input: a compiled benchmark policy guard, a lease state, a PI-native tool name
2
+ // output: a fail-closed allow/deny decision for PI's tool-dispatch boundary
3
+ // pos: PI application point of the mandatory benchmark policy guard
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ /** Serialized compiled guard for this role. Its presence — even empty — puts the PI process in
6
+ * guarded mode, where no branch may return allow by default (design §13 GT6, §6.8 G3). */
7
+ export const PI_POLICY_GUARD_ENV = 'CORTEX_PI_POLICY_GUARD';
8
+ /** The guard's lease-state input (§6.8 G4). */
9
+ export const PI_LEASE_STATE_ENV = 'CORTEX_PI_LEASE_STATE';
10
+ /** Resolved MCP composition for this spawn; the bridge derives its server set from it (§5.6 P1). */
11
+ export const PI_MCP_COMPOSITION_ENV = 'CORTEX_PI_MCP_COMPOSITION';
12
+ /** D-GUARD-STATIC: Gate 2 lands the guard mechanism, not the lease transition, so the state is a
13
+ * constant the factory supplies. Gates 3/6/7 vary this same parameter without reshaping the guard. */
14
+ export const GATE2_LEASE_STATE = 'parent-writable';
15
+ function deny(reason) {
16
+ return { allow: false, reason };
17
+ }
18
+ function allowList(value, state) {
19
+ if (!Array.isArray(value) || value.some(name => typeof name !== 'string' || name.length === 0)) {
20
+ throw new Error(`policy guard state '${state}' must be an array of tool names`);
21
+ }
22
+ return new Set(value);
23
+ }
24
+ /**
25
+ * Read a compiled guard as the per-lease-state allow-list of §6.6, in PI-native names. Throws on
26
+ * anything else: an unreadable guard must not be turned into a permissive one.
27
+ */
28
+ export function compilePiPolicyGuard(raw) {
29
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
30
+ throw new Error('policy guard must be an object keyed by lease state');
31
+ }
32
+ const table = new Map();
33
+ for (const [state, value] of Object.entries(raw)) {
34
+ table.set(state, allowList(value, state));
35
+ }
36
+ return (toolName, leaseState) => {
37
+ const allowed = table.get(leaseState);
38
+ if (allowed === undefined)
39
+ return deny(`no allow-list for lease state '${leaseState}'`);
40
+ return allowed.has(toolName)
41
+ ? { allow: true, reason: `'${toolName}' is allow-listed in '${leaseState}'` }
42
+ : deny(`'${toolName}' is not allow-listed in '${leaseState}'`);
43
+ };
44
+ }
45
+ /**
46
+ * The decision every guarded PI tool dispatch goes through. A missing evaluator, an evaluator that
47
+ * throws and an evaluator that answers with anything other than an explicit allow all deny — there
48
+ * is deliberately no branch here that yields allow without one (§6.8 G3, battery T8).
49
+ */
50
+ export function guardDecision(evaluator, toolName, leaseState) {
51
+ if (evaluator === null)
52
+ return deny('no benchmark policy guard is installed');
53
+ try {
54
+ const decision = evaluator(toolName, leaseState);
55
+ if (!decision || decision.allow !== true) {
56
+ return deny(decision?.reason ?? 'guard returned no decision');
57
+ }
58
+ return decision;
59
+ }
60
+ catch (error) {
61
+ return deny(`guard evaluation failed: ${error.message}`);
62
+ }
63
+ }
64
+ /** Match Claude-native labels against the active agent's comma-separated allowlist. Unguarded
65
+ * daemon sessions only; a benchmark spawn never reaches it (see `resolvePiToolGate`). */
66
+ function legacyAllowlistGate(allowedToolsEnv) {
67
+ const allowAll = !allowedToolsEnv || allowedToolsEnv.trim() === '';
68
+ const allowed = new Set((allowedToolsEnv ?? '').split(',').map(tool => tool.trim()).filter(Boolean));
69
+ return {
70
+ guarded: false,
71
+ decide: (nativeToolName, claudeLabel) => {
72
+ if (allowAll)
73
+ return { allow: true, reason: 'no allowlist configured' };
74
+ const label = claudeLabel ?? nativeToolName;
75
+ return allowed.has(label)
76
+ ? { allow: true, reason: `'${label}' is allow-listed` }
77
+ : deny(`'${label}' is not allow-listed`);
78
+ },
79
+ };
80
+ }
81
+ /** The guarded gate every benchmark PI process runs under. Exported so a caller can install an
82
+ * evaluator that is not env-derived; the decision path is the same `guardDecision` either way. */
83
+ export function benchmarkToolGate(evaluator, leaseState) {
84
+ return {
85
+ guarded: true,
86
+ decide: nativeToolName => guardDecision(evaluator, nativeToolName, leaseState),
87
+ };
88
+ }
89
+ function guardedGate(serialized, leaseState) {
90
+ let evaluator;
91
+ try {
92
+ evaluator = compilePiPolicyGuard(JSON.parse(serialized));
93
+ }
94
+ catch (error) {
95
+ // Guarded mode with an unreadable guard: deny, never fall back to the allowlist gate.
96
+ const reason = `benchmark policy guard is unreadable: ${error.message}`;
97
+ evaluator = () => deny(reason);
98
+ }
99
+ return benchmarkToolGate(evaluator, leaseState ?? '');
100
+ }
101
+ /**
102
+ * Pick the gate this PI process runs under. The selection is total and ordered: a guard present in
103
+ * the environment always wins, and the guarded branch never falls through to the allowlist gate.
104
+ * That is what removes §6.6 defect 4 — the empty-value allow-all — from the benchmark path.
105
+ */
106
+ export function resolvePiToolGate(env) {
107
+ const serialized = env[PI_POLICY_GUARD_ENV];
108
+ if (serialized === undefined)
109
+ return legacyAllowlistGate(env.CORTEX_PI_ALLOWED_TOOLS);
110
+ return guardedGate(serialized, env[PI_LEASE_STATE_ENV]);
111
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * One provider entry to write into the cortex-controlled `models.json`. cortex uses PI's
3
+ * "Override Built-in Providers" mechanism (docs/models.md §Overriding Built-in Providers):
4
+ * specifying only `baseUrl` redirects all of that provider's traffic to our gateway while
5
+ * keeping PI's built-in model catalog and OAuth/API-key auth resolution from auth.json intact.
6
+ */
7
+ export interface ProviderOverride {
8
+ /** PI provider name (e.g. "anthropic", "deepseek", "openai-codex"). */
9
+ name: string;
10
+ /**
11
+ * Path segment appended to the gateway URL. Defaults to `/${name}`.
12
+ * An explicit empty string keeps the gateway URL exact; other values select a non-standard path
13
+ * (e.g. deepseek's anthropic-compat endpoint: `/deepseek/anthropic`).
14
+ */
15
+ basePath?: string;
16
+ /**
17
+ * Per-spawn PI compat flags to write into this provider's models.json entry.
18
+ * Merged ON TOP of PROVIDER_COMPAT_OVERRIDES (explicit wins). Normally unset —
19
+ * the static table covers the known cases.
20
+ */
21
+ compat?: Record<string, unknown>;
22
+ /**
23
+ * Complete provider block for a user-defined provider, written verbatim. PI knows nothing about
24
+ * such a provider, so a `baseUrl`-only override would strip the protocol (`api`) and the model
25
+ * list and leave PI unable to call it. When set, `basePath`/`compat` are ignored — the definition
26
+ * already carries its own gateway `baseUrl`.
27
+ */
28
+ entry?: Record<string, unknown>;
29
+ }
30
+ export interface WriteProvidersOpts {
31
+ /** Target file path. Required: an implicit host default is exactly the ambient reach §13 A3
32
+ * forbids, so every caller states where the catalog lands. */
33
+ modelsPath: string;
34
+ }
35
+ /**
36
+ * Atomic-write models.json with multi-provider baseUrl overrides. Each provider entry has a
37
+ * `baseUrl` pointing to `<gatewayUrl><basePath>`; no apiKey is written so PI resolves credentials
38
+ * from auth.json (or environment variables) per PI's auth resolution order.
39
+ *
40
+ * Called by PIAdapter.spawn() — sole writer of this file, no other code path touches it.
41
+ */
42
+ export declare function writeProvidersConfig(providers: ProviderOverride[], gatewayUrl: string, opts: WriteProvidersOpts): void;
43
+ /**
44
+ * Compute the set of PI providers whose baseUrl should be overridden to the gateway for a spawn.
45
+ *
46
+ * Design: "route through gateway" and "PI has credentials" are independent concerns. Discovery
47
+ * (`pi --list-models`) only reports providers the user is authenticated to, but a profile may
48
+ * legitimately route a provider through the gateway even without direct PI credentials (the
49
+ * gateway injects managed keys). So the override set is the union of:
50
+ * - `discovered` — providers PI reports creds for (credential passthrough via auth.json)
51
+ * - `currentProvider` — the provider THIS spawn uses (`--provider`); it MUST be routed, always
52
+ *
53
+ * `gatewayPath`, when set, becomes the current provider's `basePath` (decouples the gateway route
54
+ * from the provider name — e.g. provider "anthropic" landing on "/deepseek-anthropic"). It wins
55
+ * over the default `/<name>` even if the current provider was also discovered.
56
+ */
57
+ export declare function buildProviderOverrides(discovered: string[], currentProvider: string | null, gatewayPath?: string | null): ProviderOverride[];
58
+ /**
59
+ * Attach user-defined provider definitions to the overrides that name them, so the catalog carries
60
+ * a complete block for each one. Overrides without a definition (PI built-ins) are untouched.
61
+ */
62
+ export declare function withCustomEntries(overrides: ProviderOverride[], definitions: Record<string, Record<string, unknown>>): ProviderOverride[];
@@ -0,0 +1,101 @@
1
+ // input: provider override set, gateway base URL, explicit models.json path
2
+ // output: an atomically written multi-provider PI models.json
3
+ // pos: Ambient-free PI provider catalog writer
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'fs';
6
+ import * as path from 'path';
7
+ /**
8
+ * PI compat flags that PI auto-detects from the provider's *real* endpoint URL but loses once
9
+ * cortex rewrites `baseUrl` to the gateway. PI's `detectCompat()` keys `supportsDeveloperRole`
10
+ * off `baseUrl.includes("deepseek.com")` ONLY (not the provider name), so routing DeepSeek
11
+ * through `http://127.0.0.1:9880/deepseek` makes PI wrongly assume the endpoint accepts the
12
+ * OpenAI `developer` system-prompt role — DeepSeek's API rejects it with HTTP 400 (empty output).
13
+ * We re-assert the lost flags here, keyed by PI provider name (the override preserves the name).
14
+ * Add a row here if another gateway-routed provider exhibits the same URL-detection loss.
15
+ */
16
+ const PROVIDER_COMPAT_OVERRIDES = {
17
+ deepseek: { supportsDeveloperRole: false },
18
+ };
19
+ /**
20
+ * Atomic-write models.json with multi-provider baseUrl overrides. Each provider entry has a
21
+ * `baseUrl` pointing to `<gatewayUrl><basePath>`; no apiKey is written so PI resolves credentials
22
+ * from auth.json (or environment variables) per PI's auth resolution order.
23
+ *
24
+ * Called by PIAdapter.spawn() — sole writer of this file, no other code path touches it.
25
+ */
26
+ export function writeProvidersConfig(providers, gatewayUrl, opts) {
27
+ const targetPath = opts.modelsPath;
28
+ const providersBlock = {};
29
+ for (const p of providers) {
30
+ if (p.entry) {
31
+ providersBlock[p.name] = p.entry;
32
+ continue;
33
+ }
34
+ const basePath = p.basePath ?? `/${p.name}`;
35
+ const entry = {
36
+ baseUrl: `${gatewayUrl}${basePath}`,
37
+ };
38
+ // Re-assert compat flags PI can no longer auto-detect now that baseUrl is the gateway.
39
+ // Static table first, then per-override compat (explicit wins).
40
+ const compat = { ...PROVIDER_COMPAT_OVERRIDES[p.name], ...p.compat };
41
+ if (Object.keys(compat).length > 0)
42
+ entry.compat = compat;
43
+ providersBlock[p.name] = entry;
44
+ }
45
+ const data = { providers: providersBlock };
46
+ const content = JSON.stringify(data, null, 2) + '\n';
47
+ mkdirSync(path.dirname(targetPath), { recursive: true });
48
+ // Atomic write: tmp + rename
49
+ const tmp = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
50
+ try {
51
+ writeFileSync(tmp, content, 'utf8');
52
+ renameSync(tmp, targetPath);
53
+ }
54
+ catch (err) {
55
+ // Best-effort cleanup of orphan tmp file (rename failure case)
56
+ try {
57
+ if (existsSync(tmp))
58
+ unlinkSync(tmp);
59
+ }
60
+ catch { /* ignore */ }
61
+ throw err;
62
+ }
63
+ }
64
+ /**
65
+ * Compute the set of PI providers whose baseUrl should be overridden to the gateway for a spawn.
66
+ *
67
+ * Design: "route through gateway" and "PI has credentials" are independent concerns. Discovery
68
+ * (`pi --list-models`) only reports providers the user is authenticated to, but a profile may
69
+ * legitimately route a provider through the gateway even without direct PI credentials (the
70
+ * gateway injects managed keys). So the override set is the union of:
71
+ * - `discovered` — providers PI reports creds for (credential passthrough via auth.json)
72
+ * - `currentProvider` — the provider THIS spawn uses (`--provider`); it MUST be routed, always
73
+ *
74
+ * `gatewayPath`, when set, becomes the current provider's `basePath` (decouples the gateway route
75
+ * from the provider name — e.g. provider "anthropic" landing on "/deepseek-anthropic"). It wins
76
+ * over the default `/<name>` even if the current provider was also discovered.
77
+ */
78
+ export function buildProviderOverrides(discovered, currentProvider, gatewayPath) {
79
+ const byName = new Map();
80
+ for (const name of discovered) {
81
+ if (!byName.has(name))
82
+ byName.set(name, { name });
83
+ }
84
+ if (currentProvider) {
85
+ byName.set(currentProvider, {
86
+ name: currentProvider,
87
+ ...(gatewayPath !== undefined && gatewayPath !== null ? { basePath: gatewayPath } : {}),
88
+ });
89
+ }
90
+ return Array.from(byName.values());
91
+ }
92
+ /**
93
+ * Attach user-defined provider definitions to the overrides that name them, so the catalog carries
94
+ * a complete block for each one. Overrides without a definition (PI built-ins) are untouched.
95
+ */
96
+ export function withCustomEntries(overrides, definitions) {
97
+ return overrides.map((override) => {
98
+ const entry = definitions[override.name];
99
+ return entry ? { ...override, entry } : override;
100
+ });
101
+ }
@@ -0,0 +1,11 @@
1
+ import type { ExtensionAPI } from './pi-ext-types.js';
2
+ /**
3
+ * Report what the provider says about its own quota. Codex publishes utilization on every response
4
+ * header set — including error responses — so the probe reads each one and forwards a reading over
5
+ * `ctx.ui.notify`, the only fire-and-forget message PI's RPC mode gives an extension.
6
+ *
7
+ * Everything here is best-effort: a throw would surface as an `extension_error` and pollute the
8
+ * turn, so a broken or absent UI channel simply costs one reading. The next response carries a
9
+ * fresh snapshot, and a missing reading is never read as "quota is fine".
10
+ */
11
+ export default function quotaProbe(pi: ExtensionAPI): void;
@@ -0,0 +1,36 @@
1
+ // input: PI ExtensionAPI, provider response headers, codex quota codec
2
+ // output: quota notices emitted on PI's fire-and-forget UI channel
3
+ // pos: PI child-side probe reporting provider quota to the server
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { parseCodexQuotaHeaders, encodeQuotaNotice } from '../../domain/costs/codex-quota.js';
6
+ function headersOf(event) {
7
+ const headers = event?.headers;
8
+ return headers && typeof headers === 'object' && !Array.isArray(headers)
9
+ ? headers
10
+ : null;
11
+ }
12
+ /**
13
+ * Report what the provider says about its own quota. Codex publishes utilization on every response
14
+ * header set — including error responses — so the probe reads each one and forwards a reading over
15
+ * `ctx.ui.notify`, the only fire-and-forget message PI's RPC mode gives an extension.
16
+ *
17
+ * Everything here is best-effort: a throw would surface as an `extension_error` and pollute the
18
+ * turn, so a broken or absent UI channel simply costs one reading. The next response carries a
19
+ * fresh snapshot, and a missing reading is never read as "quota is fine".
20
+ */
21
+ export default function quotaProbe(pi) {
22
+ pi.on('after_provider_response', (event, ctx) => {
23
+ try {
24
+ const headers = headersOf(event);
25
+ if (!headers)
26
+ return;
27
+ const reading = parseCodexQuotaHeaders(headers, { nowMs: Date.now() });
28
+ if (!reading)
29
+ return;
30
+ ctx?.ui?.notify(encodeQuotaNotice(reading));
31
+ }
32
+ catch {
33
+ // Reporting is advisory; never fail the provider call over it.
34
+ }
35
+ });
36
+ }
@@ -0,0 +1,25 @@
1
+ import { type RateLimitSource } from '../../domain/costs/rate-limit-throttle.js';
2
+ import type { CodexQuotaReading } from '../../domain/costs/codex-quota.js';
3
+ import type { AgentSpawnConfig } from '../types.js';
4
+ /** Signature of the throttle entry point; injected in tests, defaulted to the real one. */
5
+ type SubmitRateLimit = (info: {
6
+ rateLimitType: string;
7
+ utilization: number;
8
+ resetsAt: number;
9
+ }, source: RateLimitSource) => Promise<void>;
10
+ /**
11
+ * Resolve the two keys the dispatch gate looks a throttle up by. `configIsRateLimited` asks
12
+ * `isProviderModeRateLimited(resolveRateLimitProvider(config), config.mode || 'api')`, so a reading
13
+ * filed under any other pair would be recorded and then never consulted. The provider mirrors
14
+ * `resolveRateLimitProvider` (profile provider, else the backend name); the mode is recovered from
15
+ * the gateway sub-path `/m/<mode>/<provider>` that spawn-config derives from the profile's mode,
16
+ * and its absence means the profile had no mode — which the gate reads as 'api'.
17
+ */
18
+ export declare function resolveQuotaSource(config: Pick<AgentSpawnConfig, 'piProvider' | 'piGatewayPath'>): RateLimitSource;
19
+ /**
20
+ * File each advertised window as its own throttle event. The throttle owns the thresholds and
21
+ * decides whether a window is worth pausing for, so every window is submitted as observed —
22
+ * including the ones far below the line, which keep the recorded reset time fresh.
23
+ */
24
+ export declare function reportCodexQuota(reading: CodexQuotaReading, source: RateLimitSource, submit?: SubmitRateLimit): Promise<void>;
25
+ export {};