@cortex-agent/server 2026.8.3-2 → 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 (219) 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/domain/agent-run/agent-run-cli.js +3 -1
  67. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
  68. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
  69. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
  70. package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
  71. package/dist/domain/agent-run/identity.d.ts +5 -0
  72. package/dist/domain/agent-run/identity.js +4 -1
  73. package/dist/domain/agent-run/journal.d.ts +3 -2
  74. package/dist/domain/agent-run/manifest.js +11 -4
  75. package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
  76. package/dist/domain/agent-run/pinned-node-process.js +9 -0
  77. package/dist/domain/agent-run/role-surface.d.ts +2 -2
  78. package/dist/domain/agent-run/role-surface.js +7 -3
  79. package/dist/domain/agent-run/run-config.d.ts +10 -1
  80. package/dist/domain/agent-run/run-config.js +57 -6
  81. package/dist/domain/agent-run/runner.js +149 -31
  82. package/dist/domain/agents/facade.d.ts +37 -122
  83. package/dist/domain/agents/facade.js +47 -115
  84. package/dist/domain/agents/spawn-config.d.ts +135 -0
  85. package/dist/domain/agents/spawn-config.js +121 -0
  86. package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
  87. package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
  88. package/dist/domain/benchmark/arm-schema.d.ts +43 -0
  89. package/dist/domain/benchmark/arm-schema.js +243 -0
  90. package/dist/domain/benchmark/capabilities.d.ts +4 -0
  91. package/dist/domain/benchmark/capabilities.js +54 -0
  92. package/dist/domain/benchmark/decimal-text.d.ts +27 -0
  93. package/dist/domain/benchmark/decimal-text.js +67 -0
  94. package/dist/domain/benchmark/lease-echo.d.ts +43 -0
  95. package/dist/domain/benchmark/lease-echo.js +56 -0
  96. package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
  97. package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
  98. package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
  99. package/dist/domain/benchmark/policy-compiler.js +680 -0
  100. package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
  101. package/dist/domain/benchmark/resolved-policy.js +195 -0
  102. package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
  103. package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
  104. package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
  105. package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
  106. package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
  107. package/dist/domain/benchmark/variant-proposal.js +42 -0
  108. package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
  109. package/dist/domain/benchmark/workspace-lease.js +272 -0
  110. package/dist/domain/costs/codex-quota.d.ts +29 -0
  111. package/dist/domain/costs/codex-quota.js +102 -0
  112. package/dist/domain/costs/cost-tracker.d.ts +48 -9
  113. package/dist/domain/costs/cost-tracker.js +74 -18
  114. package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
  115. package/dist/domain/costs/rate-limit-throttle.js +61 -6
  116. package/dist/domain/costs/resume-registry.d.ts +3 -1
  117. package/dist/domain/costs/resume-registry.js +10 -1
  118. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
  119. package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
  120. package/dist/domain/mcp/tools/cost.js +15 -6
  121. package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
  122. package/dist/domain/pi-providers/custom-provider-model.js +122 -0
  123. package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
  124. package/dist/domain/pi-providers/custom-provider-service.js +143 -0
  125. package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
  126. package/dist/domain/pi-providers/gateway-route-store.js +78 -0
  127. package/dist/domain/pi-providers/index.d.ts +4 -0
  128. package/dist/domain/pi-providers/index.js +8 -0
  129. package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
  130. package/dist/domain/pi-providers/models-json-store.js +77 -0
  131. package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
  132. package/dist/domain/scheduling/jobs/_shared.js +11 -2
  133. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
  134. package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
  135. package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
  136. package/dist/domain/sessions/session-lifecycle.js +20 -1
  137. package/dist/domain/system/system-notice.d.ts +4 -1
  138. package/dist/domain/system/system-notice.js +6 -2
  139. package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
  140. package/dist/domain/tasks/dispatch-utils.js +24 -37
  141. package/dist/domain/threads/runner.d.ts +16 -1
  142. package/dist/domain/threads/runner.js +62 -8
  143. package/dist/domain/threads/template-loader.d.ts +5 -0
  144. package/dist/domain/threads/template-loader.js +120 -36
  145. package/dist/domain/threads/template-validate.d.ts +244 -0
  146. package/dist/domain/threads/template-validate.js +574 -0
  147. package/dist/domain/threads/template-validate.parity.d.ts +1 -0
  148. package/dist/domain/threads/template-validate.parity.js +47 -0
  149. package/dist/domain/threads/template-writer.d.ts +55 -0
  150. package/dist/domain/threads/template-writer.js +131 -0
  151. package/dist/domain/ui-service/app-router.d.ts +143 -1
  152. package/dist/domain/ui-service/app-router.js +29 -3
  153. package/dist/domain/ui-service/input-schemas.d.ts +228 -4
  154. package/dist/domain/ui-service/input-schemas.js +132 -1
  155. package/dist/domain/ui-service/mutate/config.d.ts +10 -1
  156. package/dist/domain/ui-service/mutate/config.js +45 -5
  157. package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
  158. package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
  159. package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
  160. package/dist/domain/ui-service/mutate/profiles.js +156 -0
  161. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  162. package/dist/domain/ui-service/mutate/schedules.js +53 -3
  163. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  164. package/dist/domain/ui-service/mutate/sessions.js +25 -1
  165. package/dist/domain/ui-service/mutate/system.d.ts +2 -1
  166. package/dist/domain/ui-service/mutate/system.js +17 -3
  167. package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
  168. package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
  169. package/dist/domain/ui-service/query/config.js +30 -0
  170. package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
  171. package/dist/domain/ui-service/query/custom-providers.js +13 -0
  172. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
  173. package/dist/domain/ui-service/query/machine-detail.js +56 -0
  174. package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
  175. package/dist/domain/ui-service/query/machine-probe.js +136 -0
  176. package/dist/domain/ui-service/query/schedules.js +5 -0
  177. package/dist/domain/ui-service/query/sessions.js +8 -2
  178. package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
  179. package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
  180. package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
  181. package/dist/domain/ui-service/query/thread-templates.js +44 -7
  182. package/dist/domain/ui-service/types.d.ts +298 -7
  183. package/dist/domain/ui-service/ui-service.js +27 -3
  184. package/dist/entry/app.js +24 -3
  185. package/dist/entry/auth-cli.d.ts +4 -1
  186. package/dist/entry/auth-cli.js +10 -2
  187. package/dist/entry/cli-help.js +6 -2
  188. package/dist/entry/cli.js +2 -1
  189. package/dist/entry/daemon.d.ts +0 -11
  190. package/dist/entry/daemon.js +5 -49
  191. package/dist/entry/provider-cli.d.ts +16 -0
  192. package/dist/entry/provider-cli.js +203 -0
  193. package/dist/events/event-types.d.ts +2 -1
  194. package/dist/orchestration/agent-runner.js +3 -2
  195. package/dist/orchestration/routing/commands/cost.d.ts +8 -0
  196. package/dist/orchestration/routing/commands/cost.js +93 -21
  197. package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
  198. package/dist/orchestration/routing/commands/login-custom.js +89 -0
  199. package/dist/orchestration/routing/commands/login.d.ts +3 -0
  200. package/dist/orchestration/routing/commands/login.js +7 -0
  201. package/dist/orchestration/routing/message-router.js +48 -33
  202. package/dist/orchestration/routing/webhook.js +1 -1
  203. package/dist/orchestration/session-events.d.ts +2 -1
  204. package/dist/orchestration/session-events.js +1 -0
  205. package/dist/orchestration/thread-callback.js +1 -1
  206. package/dist/store/conversation-history-repo.d.ts +5 -1
  207. package/dist/store/conversation-history-repo.js +2 -1
  208. package/dist/store/cost-repo.d.ts +17 -0
  209. package/dist/store/cost-repo.js +47 -5
  210. package/dist/store/profile-repo.d.ts +0 -10
  211. package/dist/store/profile-repo.js +34 -56
  212. package/dist/store/session-registry-repo.d.ts +12 -0
  213. package/dist/store/session-registry-repo.js +16 -0
  214. package/package.json +1 -1
  215. package/web/dist/assets/index-DYMfaAi4.css +1 -0
  216. package/web/dist/assets/index-uOoZjGKa.js +141 -0
  217. package/web/dist/index.html +2 -2
  218. package/web/dist/assets/index-XqBCYtkw.js +0 -139
  219. package/web/dist/assets/index-zpf3OSKC.css +0 -1
@@ -2,7 +2,6 @@
2
2
  // output: PI sessions, resume path registry, events and compact
3
3
  // pos: PI backend adapter
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
- import { spawn as defaultSpawn } from 'child_process';
6
5
  import { existsSync, mkdirSync } from 'fs';
7
6
  import * as path from 'path';
8
7
  import { DATA_DIR } from '../../core/utils.js';
@@ -13,24 +12,38 @@ import { resolveMcpComposition } from '../types.js';
13
12
  import { buildPiEnv, buildSpawnArgs } from './spawn-args.js';
14
13
  import { createLineSplitter, encodeCommand } from './framing.js';
15
14
  import { piRpcLineToNormalized, createPIEventParserState, piContextUsageFromStats } from './event-parser.js';
16
- import { PI_AGENT_DIR, writeProvidersConfig, buildProviderOverrides, ensureAuthVisible, } from './agent-dir.js';
15
+ import { writeProvidersConfig, buildProviderOverrides, withCustomEntries, } from './providers-config.js';
16
+ import { readCustomProviderEntries } from './custom-catalog.js';
17
17
  import { fromCanonical } from '../normalize/tool-names.js';
18
- import { piProviderDiscovery, findPISessionFilePath, } from './discovery.js';
19
- import { CLOSE_EXIT_WAIT_MS, DEFAULT_PI_BINARY, EventQueue, PI_IDLE_SESSION_TIMEOUT, PI_MAX_TIMEOUT, PI_TURN_IDLE_TIMEOUT, PIContextUsageProbe, PI_CONTEXT_USAGE_TIMEOUT_MS, PISteeringQueue, SWITCH_SESSION_TIMEOUT_MS, buildPromptText, isPIContextSampleBoundary, parseRpcObject, } from './session-support.js';
20
- import { DEFAULT_SESSION_DIR, HOOK_BRIDGE_PATH, MCP_BRIDGE_PATH, TOOL_SHIMS_PATH } from './defaults.js';
18
+ import { findPISessionFilePath } from './session-files.js';
19
+ import { reportCodexQuota, resolveQuotaSource } from './quota-sink.js';
20
+ import { CLOSE_EXIT_WAIT_MS, DEFAULT_PI_BINARY, EventQueue, PI_IDLE_SESSION_TIMEOUT, PI_MAX_TIMEOUT, PI_TURN_IDLE_TIMEOUT, PIContextUsageProbe, PI_CONTEXT_USAGE_TIMEOUT_MS, PISteeringQueue, SWITCH_SESSION_TIMEOUT_MS, buildPromptText, defaultPiSpawn, isPIContextSampleBoundary, parseRpcObject, } from './session-support.js';
21
+ import { DEFAULT_SESSION_DIR, HOOK_BRIDGE_PATH, MCP_BRIDGE_PATH, PI_AGENT_DIR, QUOTA_PROBE_PATH, TOOL_SHIMS_PATH, piModelsPath, } from './defaults.js';
21
22
  const log = createLogger('pi-adapter');
22
- export class UnsupportedMcpCompositionError extends Error {
23
- composition;
24
- name = 'UnsupportedMcpCompositionError';
25
- constructor(composition) {
26
- super(`PI backend does not support MCP composition: ${composition}`);
27
- this.composition = composition;
28
- }
29
- }
30
- function assertSupportedMcpComposition(config) {
31
- const composition = resolveMcpComposition(config.mcpComposition, config.cortexContext?.useCoreMcp);
32
- if (composition === 'none' || composition === 'benchmark-thread-run') {
33
- throw new UnsupportedMcpCompositionError(composition);
23
+ /** Discovery that reports nothing. The daemon injects the cached host scanner; a trial injects its
24
+ * single-provider catalog. Neither is a module default here (§13 A7/A8). */
25
+ const NO_PROVIDER_DISCOVERY = {
26
+ getProviders: () => [],
27
+ refresh: () => { },
28
+ };
29
+ /**
30
+ * A benchmark spawn is one carrying a compiled policy guard: §6.8 G1 makes the guard mandatory for
31
+ * every benchmark role, so its presence is the marker. Everything a trial must not fall back to is
32
+ * required here, which is what makes each ambient default unreachable rather than merely unused
33
+ * (§13 S6.1, A12, A13).
34
+ */
35
+ function assertBenchmarkSpawn(config, agentDir) {
36
+ const missing = [
37
+ ['processSpawner', config.processSpawner],
38
+ ['cliPath', config.cliPath],
39
+ ['cwd', config.cwd],
40
+ ['pinnedEnv', config.pinnedEnv],
41
+ ['agentDir', agentDir],
42
+ ['piGatewayBaseUrl', config.piGatewayBaseUrl],
43
+ ['streamDeltas', config.streamDeltas],
44
+ ].filter(([, value]) => value === undefined).map(([name]) => name);
45
+ if (missing.length > 0) {
46
+ throw new Error(`PI benchmark spawn is missing required inputs: ${missing.join(', ')}`);
34
47
  }
35
48
  }
36
49
  function record(value) {
@@ -89,12 +102,15 @@ class PISession {
89
102
  */
90
103
  currentSessionId = null;
91
104
  proc;
105
+ /** Present when the process was launched through a containment supervisor (§13 P1). */
106
+ supervision;
92
107
  events = new EventQueue();
93
108
  splitter = createLineSplitter();
94
109
  parserState = createPIEventParserState();
95
110
  registry;
96
111
  registrySessionDir;
97
112
  onClose;
113
+ onProviderQuota;
98
114
  stderrTail = '';
99
115
  alive = true;
100
116
  exitPromise;
@@ -130,12 +146,15 @@ class PISession {
130
146
  this.registry = opts.registry;
131
147
  this.registrySessionDir = opts.registrySessionDir;
132
148
  this.onClose = opts.onClose;
133
- this.streamDeltas = getSettings().streamDeltas;
134
- this.proc = opts.spawner(DEFAULT_PI_BINARY, opts.cliArgs, {
149
+ this.onProviderQuota = opts.onProviderQuota;
150
+ this.streamDeltas = opts.streamDeltas;
151
+ const spawned = opts.spawner(opts.command, opts.cliArgs, {
135
152
  cwd: opts.cwd,
136
153
  env: opts.env,
137
154
  stdio: ['pipe', 'pipe', 'pipe'],
138
155
  });
156
+ this.proc = spawned.process;
157
+ this.supervision = spawned.supervision;
139
158
  this.contextUsageProbe = new PIContextUsageProbe((command) => {
140
159
  const stdin = this.proc.stdin;
141
160
  if (!stdin || stdin.destroyed || stdin.writableEnded)
@@ -397,6 +416,7 @@ class PISession {
397
416
  const finishDeferred = this.handleInjectionProtocol(raw);
398
417
  for (const evt of piRpcLineToNormalized(line, this.parserState)) {
399
418
  this.captureSessionStarted(evt);
419
+ this.captureProviderQuota(evt);
400
420
  const output = this.processPendingTurnEvent(evt);
401
421
  if (output !== null)
402
422
  this.emitOrProbeContext(output);
@@ -472,6 +492,14 @@ class PISession {
472
492
  this.registry.set(evt.sessionId, path.join(this.registrySessionDir, `${evt.sessionId}.jsonl`));
473
493
  }
474
494
  }
495
+ /** Forward a provider quota reading, which arrives independently of any pending turn. */
496
+ captureProviderQuota(evt) {
497
+ if (evt.type !== 'rate_limit')
498
+ return;
499
+ const reading = evt.raw;
500
+ if (reading?.windows?.length)
501
+ this.onProviderQuota?.(reading);
502
+ }
475
503
  /** Update the outer send() promise and optionally replace/suppress a terminal event. */
476
504
  processPendingTurnEvent(evt) {
477
505
  const turn = this.pendingTurn;
@@ -741,6 +769,22 @@ class PISession {
741
769
  return ok;
742
770
  }
743
771
  }
772
+ /**
773
+ * A spawn reports provider quota when Cortex routes its traffic (`piGatewayBaseUrl`) and it is not
774
+ * a benchmark trial. The compiled guard is the trial marker (§6.8 G1), and a trial must stay out of
775
+ * daemon-wide state: its readings would throttle production work on behalf of an experiment.
776
+ */
777
+ function reportsProviderQuota(config) {
778
+ return !!config.piGatewayBaseUrl && config.benchmarkPolicyGuard === undefined;
779
+ }
780
+ function buildExtensionPaths(config) {
781
+ const paths = [MCP_BRIDGE_PATH, TOOL_SHIMS_PATH];
782
+ if (config.disableHooks !== true)
783
+ paths.push(HOOK_BRIDGE_PATH);
784
+ if (reportsProviderQuota(config))
785
+ paths.push(QUOTA_PROBE_PATH);
786
+ return paths;
787
+ }
744
788
  export class PIAdapter {
745
789
  backend = 'pi';
746
790
  capabilities = CAPABILITIES_BY_BACKEND.pi;
@@ -749,12 +793,20 @@ export class PIAdapter {
749
793
  providerDiscovery;
750
794
  configuredProviderOverrides = new Map();
751
795
  sessionPathRegistry = new Map();
796
+ /** Injected PI home, or undefined when the caller left it to the daemon default. */
797
+ configuredAgentDir;
798
+ prepareAgentDir;
799
+ /** Injected user catalog path, or undefined when this instance mirrors no custom provider. */
800
+ userModelsPath;
752
801
  /** sessionDir for the <sessionId>.jsonl path convention. Exposed for tests. */
753
802
  sessionDir;
754
- constructor(spawner = defaultSpawn, sessionDir = DEFAULT_SESSION_DIR, providerDiscovery = piProviderDiscovery) {
803
+ constructor(spawner = defaultPiSpawn, sessionDir = DEFAULT_SESSION_DIR, providerDiscovery = NO_PROVIDER_DISCOVERY, hooks = {}) {
755
804
  this.spawner = spawner;
756
805
  this.sessionDir = sessionDir;
757
806
  this.providerDiscovery = providerDiscovery;
807
+ this.configuredAgentDir = hooks.agentDir;
808
+ this.prepareAgentDir = hooks.prepareAgentDir;
809
+ this.userModelsPath = hooks.userModelsPath;
758
810
  }
759
811
  gatewayOverrides(discovered, currentProvider, gatewayPath) {
760
812
  if (currentProvider) {
@@ -767,7 +819,14 @@ export class PIAdapter {
767
819
  return Array.from(byName.values());
768
820
  }
769
821
  spawn(config) {
770
- assertSupportedMcpComposition(config);
822
+ const guard = config.benchmarkPolicyGuard;
823
+ if (guard !== undefined)
824
+ assertBenchmarkSpawn(config, this.configuredAgentDir);
825
+ // P13: the two benchmark compositions are supported now. Strictness is not a promise made in a
826
+ // comment — the bridge derives its server set from this value, so `none` yields zero servers and
827
+ // `benchmark-thread-run` yields exactly `cortex-benchmark-thread` (§5.6 P1).
828
+ const composition = resolveMcpComposition(config.mcpComposition, config.cortexContext?.useCoreMcp);
829
+ const agentDir = this.configuredAgentDir ?? PI_AGENT_DIR;
771
830
  const sessionDir = this.sessionDir;
772
831
  mkdirSync(sessionDir, { recursive: true });
773
832
  // Resolve the backend id to one exact path before spawn and pass that path to --session.
@@ -790,8 +849,9 @@ export class PIAdapter {
790
849
  systemPrompt: config.systemPrompt ?? null,
791
850
  appendSystemPrompt: config.appendSystemPrompt ?? null,
792
851
  pluginDirs: config.pluginDirs ?? null,
793
- // All three extensions always injected: MCP bridge (task 5754) + tool shims (task 5b5c) + hook bridge (task d3ae).
794
- extensionPaths: [MCP_BRIDGE_PATH, TOOL_SHIMS_PATH, HOOK_BRIDGE_PATH],
852
+ // P9: the MCP bridge and the guard's host (tool shims) are always injected; the hook bridge is
853
+ // derived from the role, so a role that declares no hook surface never loads it.
854
+ extensionPaths: buildExtensionPaths(config),
795
855
  thinking: config.thinking ?? null,
796
856
  extraOption: config.extraOption ?? null,
797
857
  });
@@ -803,10 +863,12 @@ export class PIAdapter {
803
863
  // resolved from auth.json as usual.
804
864
  if (config.piGatewayBaseUrl) {
805
865
  try {
806
- ensureAuthVisible();
866
+ this.prepareAgentDir?.(agentDir);
807
867
  }
808
868
  catch (err) {
809
- log.warn(`Failed to mirror PI auth.json: ${err.message}`);
869
+ if (guard !== undefined)
870
+ throw err;
871
+ log.warn(`Failed to prepare the PI agent dir: ${err.message}`);
810
872
  }
811
873
  try {
812
874
  // Override set = providers PI reports creds for (discovered) ∪ the provider THIS spawn
@@ -814,15 +876,22 @@ export class PIAdapter {
814
876
  // when discovery doesn't list it (e.g. an anthropic-protocol relay whose key the gateway
815
877
  // injects). config.piGatewayPath, when set, decouples the gateway route from the provider name.
816
878
  const discovered = this.providerDiscovery.getProviders();
817
- const overrides = this.gatewayOverrides(discovered, config.piProvider ?? null, config.piGatewayPath ?? null);
879
+ // A user-defined provider is unknown to PI, so a baseUrl-only override would hand the
880
+ // subprocess a provider with no protocol and no models. Its full definition rides along.
881
+ const overrides = withCustomEntries(this.gatewayOverrides(discovered, config.piProvider ?? null, config.piGatewayPath ?? null), this.userModelsPath ? readCustomProviderEntries(this.userModelsPath) : {});
818
882
  if (overrides.length > 0) {
819
- writeProvidersConfig(overrides, config.piGatewayBaseUrl);
883
+ // A3: the catalog lands where the agent dir says, never at an implicit host default.
884
+ writeProvidersConfig(overrides, config.piGatewayBaseUrl, {
885
+ modelsPath: piModelsPath(agentDir),
886
+ });
820
887
  }
821
888
  else {
822
889
  log.warn('No PI providers to route (empty discovery and no profile provider); PI subprocess may fail to authenticate');
823
890
  }
824
891
  }
825
892
  catch (err) {
893
+ if (guard !== undefined)
894
+ throw err;
826
895
  log.warn(`Failed to write PI models.json: ${err.message}`);
827
896
  }
828
897
  }
@@ -830,34 +899,60 @@ export class PIAdapter {
830
899
  // pseudo-tools it registers — mirroring the Claude backend's `--tools` allowlist. Without this,
831
900
  // thread-dispatched agents (whose config excludes AskUserQuestion/EnterPlanMode/ExitPlanMode)
832
901
  // would still be handed those interaction tools and deadlock on an approval no human can answer.
833
- const allowedTools = config.rawTools
834
- ?? (config.tools && config.tools.length > 0
835
- ? config.tools.map((t) => fromCanonical('claude', t)).filter((n) => !!n).join(',')
836
- : undefined);
902
+ // P11: with a guard present the allow-list no longer decides anything — GT6's dispatch guard
903
+ // does — so the fail-open variable is not even exported into the child.
904
+ const allowedTools = guard !== undefined
905
+ ? undefined
906
+ : config.rawTools
907
+ ?? (config.tools && config.tools.length > 0
908
+ ? config.tools.map((t) => fromCanonical('claude', t)).filter((n) => !!n).join(',')
909
+ : undefined);
837
910
  const env = buildPiEnv({
838
911
  sessionId: config.sessionId,
839
- channel: config.channel,
912
+ // C7/A13: `channel` is what emits SLACK_CHANNEL / FEISHU_CHANNEL — a platform surface a trial
913
+ // has no business naming, and the switch that layers the Slack and Feishu MCP servers.
914
+ channel: guard === undefined ? config.channel : undefined,
840
915
  callbackSource: config.callbackSource,
841
916
  scheduleTaskId: config.scheduleTaskId,
842
917
  extraEnv: config.env,
843
918
  context: config.cortexContext,
844
- piAgentDir: PI_AGENT_DIR,
919
+ piAgentDir: agentDir,
845
920
  allowedTools,
846
- });
921
+ policyGuard: guard,
922
+ leaseState: config.benchmarkLeaseState,
923
+ mcpComposition: composition,
924
+ deadlineEpochMs: config.benchmarkDeadlineEpochMs,
925
+ // A13: the trial's exact allowlisted environment replaces host inheritance wholesale.
926
+ }, config.pinnedEnv);
847
927
  const cwd = config.cwd ?? DATA_DIR;
848
928
  const session = new PISession({
849
929
  sessionKey: config.sessionKey,
850
930
  sessionDir,
931
+ // P2: one resolved binary for the whole session; PATH resolution is the daemon's fallback.
932
+ command: config.cliPath ?? DEFAULT_PI_BINARY,
851
933
  cliArgs,
852
934
  cwd,
853
935
  env,
854
- spawner: this.spawner,
936
+ // S6.1: the spawn config is the single supervisor injection point for both backends. The
937
+ // constructor argument survives only as a test seam.
938
+ spawner: config.processSpawner ?? this.spawner,
939
+ // A15: an explicit per-spawn value, never a watched daemon setting, on the benchmark path.
940
+ streamDeltas: config.streamDeltas ?? getSettings().streamDeltas,
855
941
  registry: this.sessionPathRegistry,
856
942
  registrySessionDir: sessionDir,
857
943
  onClose: (key) => this.sessions.delete(key),
944
+ // Only gateway-routed runs carry the probe, so only they can report; the closure freezes the
945
+ // provider/mode this session was routed under rather than re-deriving it later.
946
+ onProviderQuota: reportsProviderQuota(config)
947
+ ? (reading) => {
948
+ void reportCodexQuota(reading, resolveQuotaSource(config))
949
+ .catch((err) => log.error('reportCodexQuota error:', err));
950
+ }
951
+ : undefined,
858
952
  });
859
953
  this.sessions.set(config.sessionKey, session);
860
954
  return {
955
+ supervision: session.supervision,
861
956
  sessionKey: config.sessionKey,
862
957
  get sessionId() {
863
958
  return session.sessionId;
@@ -1,57 +1,9 @@
1
- /** PI_CODING_AGENT_DIR: PI reads models.json, auth.json from this dir. */
2
- export declare const PI_AGENT_DIR: string;
3
- export declare const PI_SESSIONS_DIR: string;
4
- export declare const PI_MODELS_PATH: string;
1
+ export { PI_AGENT_DIR, PI_SESSIONS_DIR, PI_MODELS_PATH } from './defaults.js';
2
+ export { buildProviderOverrides, writeProvidersConfig, type ProviderOverride, type WriteProvidersOpts, } from './providers-config.js';
5
3
  export declare const PI_DEFAULT_AGENTS_DIR: string;
6
- /**
7
- * One provider entry to write into the cortex-controlled `models.json`. cortex uses PI's
8
- * "Override Built-in Providers" mechanism (docs/models.md §Overriding Built-in Providers):
9
- * specifying only `baseUrl` redirects all of that provider's traffic to our gateway while
10
- * keeping PI's built-in model catalog and OAuth/API-key auth resolution from auth.json intact.
11
- */
12
- export interface ProviderOverride {
13
- /** PI provider name (e.g. "anthropic", "deepseek", "openai-codex"). */
14
- name: string;
15
- /**
16
- * Path segment appended to the gateway URL. Defaults to `/${name}`.
17
- * Set explicitly when a provider needs to land on a non-standard gateway path
18
- * (e.g. deepseek's anthropic-compat endpoint: `/deepseek/anthropic`).
19
- */
20
- basePath?: string;
21
- /**
22
- * Per-spawn PI compat flags to write into this provider's models.json entry.
23
- * Merged ON TOP of PROVIDER_COMPAT_OVERRIDES (explicit wins). Normally unset —
24
- * the static table covers the known cases.
25
- */
26
- compat?: Record<string, unknown>;
27
- }
28
- export interface WriteProvidersOpts {
29
- /** Override target file path. Defaults to PI_MODELS_PATH. */
30
- modelsPath?: string;
31
- }
32
- /**
33
- * Atomic-write models.json with multi-provider baseUrl overrides. Each provider entry has a
34
- * `baseUrl` pointing to `<gatewayUrl><basePath>`; no apiKey is written so PI resolves credentials
35
- * from auth.json (or environment variables) per PI's auth resolution order.
36
- *
37
- * Called by PIAdapter.spawn() — sole writer of this file, no other code path touches it.
38
- */
39
- export declare function writeProvidersConfig(providers: ProviderOverride[], gatewayUrl: string, opts?: WriteProvidersOpts): void;
40
- /**
41
- * Compute the set of PI providers whose baseUrl should be overridden to the gateway for a spawn.
42
- *
43
- * Design: "route through gateway" and "PI has credentials" are independent concerns. Discovery
44
- * (`pi --list-models`) only reports providers the user is authenticated to, but a profile may
45
- * legitimately route a provider through the gateway even without direct PI credentials (the
46
- * gateway injects managed keys). So the override set is the union of:
47
- * - `discovered` — providers PI reports creds for (credential passthrough via auth.json)
48
- * - `currentProvider` — the provider THIS spawn uses (`--provider`); it MUST be routed, always
49
- *
50
- * `gatewayPath`, when set, becomes the current provider's `basePath` (decouples the gateway route
51
- * from the provider name — e.g. provider "anthropic" landing on "/deepseek-anthropic"). It wins
52
- * over the default `/<name>` even if the current provider was also discovered.
53
- */
54
- export declare function buildProviderOverrides(discovered: string[], currentProvider: string | null, gatewayPath?: string | null): ProviderOverride[];
4
+ /** The user's own PI provider catalog: where user-defined providers are declared, shared with the
5
+ * terminal `pi` CLI. Daemon-only — a trial never reads the host PI home (design §13 A1). */
6
+ export declare const USER_PI_MODELS_PATH: string;
55
7
  export interface EnsureAuthVisibleOpts {
56
8
  /** Source: where the user's PI auth.json lives. Defaults to ~/.pi/agent/auth.json. */
57
9
  userAuthPath?: string;
@@ -73,3 +25,18 @@ export interface EnsurePIAgentRolesOpts {
73
25
  }
74
26
  export declare function ensurePIAgentRoles(opts?: EnsurePIAgentRolesOpts): void;
75
27
  export declare function ensurePIAgentDirs(): void;
28
+ export interface EnsureTransportOpts {
29
+ agentDir?: string;
30
+ }
31
+ /**
32
+ * Pin PI's transport to SSE inside the Cortex-private agent dir.
33
+ *
34
+ * PI surfaces provider response headers to extensions only on its SSE path — the WebSocket
35
+ * transport never fires `after_provider_response` — and the quota probe reads the throttle's
36
+ * input from exactly those headers. PI's default (`auto`) tries WebSocket first, so leaving it
37
+ * unset makes quota telemetry contingent on that attempt failing. Pinning turns an observed
38
+ * fallback into a guarantee, and drops one dead handshake per session.
39
+ *
40
+ * Only this private dir is touched; the user's own `~/.pi` keeps whatever they chose.
41
+ */
42
+ export declare function ensureQuotaVisibleTransport(opts?: EnsureTransportOpts): void;
@@ -1,102 +1,25 @@
1
- // input: DATA_DIR, DEFAULTS_DIR, PI auth/provider files
2
- // output: PI paths plus provider, auth, and built-in role setup
1
+ // input: DEFAULTS_DIR, host PI auth file, PI path defaults
2
+ // output: PI auth mirroring, built-in roles and transport pinning
3
3
  // pos: Managed PI agent directory configuration
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import { mkdirSync, writeFileSync, renameSync, existsSync, lstatSync, readlinkSync, unlinkSync, symlinkSync, copyFileSync, constants as fsConstants, } from 'fs';
5
+ import { mkdirSync, existsSync, readFileSync, writeFileSync, lstatSync, readlinkSync, unlinkSync, symlinkSync, copyFileSync, constants as fsConstants, } from 'fs';
6
6
  import * as path from 'path';
7
7
  import * as os from 'os';
8
- import { DATA_DIR, DEFAULTS_DIR } from '../../core/utils.js';
8
+ import { DEFAULTS_DIR } from '../../core/utils.js';
9
9
  import { createLogger } from '../../core/log.js';
10
+ import { PI_AGENT_DIR, PI_SESSIONS_DIR } from './defaults.js';
10
11
  const log = createLogger('pi-agent-dir');
11
- /** PI_CODING_AGENT_DIR: PI reads models.json, auth.json from this dir. */
12
- export const PI_AGENT_DIR = path.join(DATA_DIR, 'data', 'pi');
13
- export const PI_SESSIONS_DIR = path.join(DATA_DIR, 'logs', 'sessions-pi');
14
- export const PI_MODELS_PATH = path.join(PI_AGENT_DIR, 'models.json');
12
+ // The host-path constants and the pure provider-catalog writer moved out so a trial adapter can
13
+ // reach the writer without importing this module's ambient auth mirroring (design §13 A5/A6, T12).
14
+ export { PI_AGENT_DIR, PI_SESSIONS_DIR, PI_MODELS_PATH } from './defaults.js';
15
+ export { buildProviderOverrides, writeProvidersConfig, } from './providers-config.js';
15
16
  export const PI_DEFAULT_AGENTS_DIR = path.join(DEFAULTS_DIR, 'pi', 'agents');
16
17
  const BUILTIN_PI_AGENT_NAMES = ['explore', 'general-purpose', 'plan'];
17
18
  /** Default location of the user's PI OAuth/API-key credentials. */
18
19
  const USER_PI_AUTH_PATH = path.join(os.homedir(), '.pi', 'agent', 'auth.json');
19
- /**
20
- * PI compat flags that PI auto-detects from the provider's *real* endpoint URL but loses once
21
- * cortex rewrites `baseUrl` to the gateway. PI's `detectCompat()` keys `supportsDeveloperRole`
22
- * off `baseUrl.includes("deepseek.com")` ONLY (not the provider name), so routing DeepSeek
23
- * through `http://127.0.0.1:9880/deepseek` makes PI wrongly assume the endpoint accepts the
24
- * OpenAI `developer` system-prompt role — DeepSeek's API rejects it with HTTP 400 (empty output).
25
- * We re-assert the lost flags here, keyed by PI provider name (the override preserves the name).
26
- * Add a row here if another gateway-routed provider exhibits the same URL-detection loss.
27
- */
28
- const PROVIDER_COMPAT_OVERRIDES = {
29
- deepseek: { supportsDeveloperRole: false },
30
- };
31
- /**
32
- * Atomic-write models.json with multi-provider baseUrl overrides. Each provider entry has a
33
- * `baseUrl` pointing to `<gatewayUrl><basePath>`; no apiKey is written so PI resolves credentials
34
- * from auth.json (or environment variables) per PI's auth resolution order.
35
- *
36
- * Called by PIAdapter.spawn() — sole writer of this file, no other code path touches it.
37
- */
38
- export function writeProvidersConfig(providers, gatewayUrl, opts) {
39
- const targetPath = opts?.modelsPath ?? PI_MODELS_PATH;
40
- const providersBlock = {};
41
- for (const p of providers) {
42
- const basePath = p.basePath ?? `/${p.name}`;
43
- const entry = {
44
- baseUrl: `${gatewayUrl}${basePath}`,
45
- };
46
- // Re-assert compat flags PI can no longer auto-detect now that baseUrl is the gateway.
47
- // Static table first, then per-override compat (explicit wins).
48
- const compat = { ...PROVIDER_COMPAT_OVERRIDES[p.name], ...p.compat };
49
- if (Object.keys(compat).length > 0)
50
- entry.compat = compat;
51
- providersBlock[p.name] = entry;
52
- }
53
- const data = { providers: providersBlock };
54
- const content = JSON.stringify(data, null, 2) + '\n';
55
- mkdirSync(path.dirname(targetPath), { recursive: true });
56
- // Atomic write: tmp + rename
57
- const tmp = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
58
- try {
59
- writeFileSync(tmp, content, 'utf8');
60
- renameSync(tmp, targetPath);
61
- }
62
- catch (err) {
63
- // Best-effort cleanup of orphan tmp file (rename failure case)
64
- try {
65
- if (existsSync(tmp))
66
- unlinkSync(tmp);
67
- }
68
- catch { /* ignore */ }
69
- throw err;
70
- }
71
- }
72
- /**
73
- * Compute the set of PI providers whose baseUrl should be overridden to the gateway for a spawn.
74
- *
75
- * Design: "route through gateway" and "PI has credentials" are independent concerns. Discovery
76
- * (`pi --list-models`) only reports providers the user is authenticated to, but a profile may
77
- * legitimately route a provider through the gateway even without direct PI credentials (the
78
- * gateway injects managed keys). So the override set is the union of:
79
- * - `discovered` — providers PI reports creds for (credential passthrough via auth.json)
80
- * - `currentProvider` — the provider THIS spawn uses (`--provider`); it MUST be routed, always
81
- *
82
- * `gatewayPath`, when set, becomes the current provider's `basePath` (decouples the gateway route
83
- * from the provider name — e.g. provider "anthropic" landing on "/deepseek-anthropic"). It wins
84
- * over the default `/<name>` even if the current provider was also discovered.
85
- */
86
- export function buildProviderOverrides(discovered, currentProvider, gatewayPath) {
87
- const byName = new Map();
88
- for (const name of discovered) {
89
- if (!byName.has(name))
90
- byName.set(name, { name });
91
- }
92
- if (currentProvider) {
93
- byName.set(currentProvider, {
94
- name: currentProvider,
95
- ...(gatewayPath ? { basePath: gatewayPath } : {}),
96
- });
97
- }
98
- return Array.from(byName.values());
99
- }
20
+ /** The user's own PI provider catalog: where user-defined providers are declared, shared with the
21
+ * terminal `pi` CLI. Daemon-only — a trial never reads the host PI home (design §13 A1). */
22
+ export const USER_PI_MODELS_PATH = path.join(os.homedir(), '.pi', 'agent', 'models.json');
100
23
  /**
101
24
  * Make the user's PI OAuth/API-key credentials visible to the PI subprocess running under
102
25
  * cortex's PI_CODING_AGENT_DIR. Uses symlink on Linux/macOS so PI's automatic OAuth refresh
@@ -177,4 +100,40 @@ export function ensurePIAgentDirs() {
177
100
  mkdirSync(PI_AGENT_DIR, { recursive: true });
178
101
  mkdirSync(PI_SESSIONS_DIR, { recursive: true });
179
102
  ensurePIAgentRoles();
103
+ ensureQuotaVisibleTransport();
104
+ }
105
+ /**
106
+ * Pin PI's transport to SSE inside the Cortex-private agent dir.
107
+ *
108
+ * PI surfaces provider response headers to extensions only on its SSE path — the WebSocket
109
+ * transport never fires `after_provider_response` — and the quota probe reads the throttle's
110
+ * input from exactly those headers. PI's default (`auto`) tries WebSocket first, so leaving it
111
+ * unset makes quota telemetry contingent on that attempt failing. Pinning turns an observed
112
+ * fallback into a guarantee, and drops one dead handshake per session.
113
+ *
114
+ * Only this private dir is touched; the user's own `~/.pi` keeps whatever they chose.
115
+ */
116
+ export function ensureQuotaVisibleTransport(opts) {
117
+ const settingsPath = path.join(opts?.agentDir ?? PI_AGENT_DIR, 'settings.json');
118
+ const current = readSettings(settingsPath);
119
+ if (current['transport'] === 'sse')
120
+ return;
121
+ try {
122
+ writeFileSync(settingsPath, `${JSON.stringify({ ...current, transport: 'sse' }, null, 2)}\n`);
123
+ }
124
+ catch (err) {
125
+ log.warn(`Failed to pin PI transport in ${settingsPath}: ${err.message}`);
126
+ }
127
+ }
128
+ /** A settings file PI has not written yet, or has written unreadably, is treated as empty. */
129
+ function readSettings(settingsPath) {
130
+ try {
131
+ const parsed = JSON.parse(readFileSync(settingsPath, 'utf-8'));
132
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
133
+ ? parsed
134
+ : {};
135
+ }
136
+ catch {
137
+ return {};
138
+ }
180
139
  }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A models.json provider block is a *definition* (a user-defined provider) when it declares both a
3
+ * protocol and its own models. A bare `baseUrl` (optionally with `compat`) is the override cortex
4
+ * writes to route a PI built-in through the gateway — PI already knows those providers.
5
+ */
6
+ export declare function isCustomProviderEntry(entry: unknown): entry is Record<string, unknown>;
7
+ /** Every `providers.*` block in the catalog, or an empty map when the file is absent or broken. */
8
+ export declare function readProvidersBlock(modelsPath: string): Record<string, unknown>;
9
+ /** Only the user-defined providers, keyed by name. */
10
+ export declare function readCustomProviderEntries(modelsPath: string): Record<string, Record<string, unknown>>;
@@ -0,0 +1,42 @@
1
+ // input: a PI models.json path
2
+ // output: the provider blocks it declares, and which of them are user-defined
3
+ // pos: Reader for PI's provider catalog file format
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { existsSync, readFileSync } from 'fs';
6
+ /**
7
+ * A models.json provider block is a *definition* (a user-defined provider) when it declares both a
8
+ * protocol and its own models. A bare `baseUrl` (optionally with `compat`) is the override cortex
9
+ * writes to route a PI built-in through the gateway — PI already knows those providers.
10
+ */
11
+ export function isCustomProviderEntry(entry) {
12
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
13
+ return false;
14
+ const record = entry;
15
+ return typeof record.api === 'string' && Array.isArray(record.models);
16
+ }
17
+ /** Every `providers.*` block in the catalog, or an empty map when the file is absent or broken. */
18
+ export function readProvidersBlock(modelsPath) {
19
+ if (!existsSync(modelsPath))
20
+ return {};
21
+ try {
22
+ const parsed = JSON.parse(readFileSync(modelsPath, 'utf8'));
23
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
24
+ return {};
25
+ const providers = parsed.providers;
26
+ if (!providers || typeof providers !== 'object' || Array.isArray(providers))
27
+ return {};
28
+ return providers;
29
+ }
30
+ catch {
31
+ return {};
32
+ }
33
+ }
34
+ /** Only the user-defined providers, keyed by name. */
35
+ export function readCustomProviderEntries(modelsPath) {
36
+ const result = {};
37
+ for (const [name, entry] of Object.entries(readProvidersBlock(modelsPath))) {
38
+ if (isCustomProviderEntry(entry))
39
+ result[name] = entry;
40
+ }
41
+ return result;
42
+ }
@@ -1,4 +1,13 @@
1
+ /** PI_CODING_AGENT_DIR: PI reads models.json and auth.json from this dir. Daemon default only —
2
+ * a trial derives its own agent dir from the trial root (design §13 A1). */
3
+ export declare const PI_AGENT_DIR: string;
4
+ export declare const PI_SESSIONS_DIR: string;
5
+ export declare const PI_MODELS_PATH: string;
1
6
  export declare const DEFAULT_SESSION_DIR: string;
2
7
  export declare const MCP_BRIDGE_PATH: string;
3
8
  export declare const TOOL_SHIMS_PATH: string;
4
9
  export declare const HOOK_BRIDGE_PATH: string;
10
+ export declare const QUOTA_PROBE_PATH: string;
11
+ /** PI's models.json always lives beside auth.json inside the agent dir, so one parameter fixes
12
+ * both (design §13 P7 / A3): a trial agent dir implies a trial provider catalog. */
13
+ export declare function piModelsPath(agentDir: string): string;
@@ -1,11 +1,21 @@
1
- // input: install root and PI private session directory
2
- // output: PI adapter session and compiled-extension paths
1
+ // input: install root and the Cortex data directory
2
+ // output: PI adapter path defaults and compiled-extension paths
3
3
  // pos: Static path defaults for PI process spawning
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as path from 'path';
6
- import { INSTALL_ROOT } from '../../core/utils.js';
7
- import { PI_SESSIONS_DIR } from './agent-dir.js';
6
+ import { DATA_DIR, INSTALL_ROOT } from '../../core/utils.js';
7
+ /** PI_CODING_AGENT_DIR: PI reads models.json and auth.json from this dir. Daemon default only —
8
+ * a trial derives its own agent dir from the trial root (design §13 A1). */
9
+ export const PI_AGENT_DIR = path.join(DATA_DIR, 'data', 'pi');
10
+ export const PI_SESSIONS_DIR = path.join(DATA_DIR, 'logs', 'sessions-pi');
11
+ export const PI_MODELS_PATH = path.join(PI_AGENT_DIR, 'models.json');
8
12
  export const DEFAULT_SESSION_DIR = PI_SESSIONS_DIR;
9
13
  export const MCP_BRIDGE_PATH = path.join(INSTALL_ROOT, 'dist/agent-adapter/pi/mcp-bridge.js');
10
14
  export const TOOL_SHIMS_PATH = path.join(INSTALL_ROOT, 'dist/agent-adapter/pi/tool-shims.js');
11
15
  export const HOOK_BRIDGE_PATH = path.join(INSTALL_ROOT, 'dist/agent-adapter/pi/hook-bridge.js');
16
+ export const QUOTA_PROBE_PATH = path.join(INSTALL_ROOT, 'dist/agent-adapter/pi/quota-probe.js');
17
+ /** PI's models.json always lives beside auth.json inside the agent dir, so one parameter fixes
18
+ * both (design §13 P7 / A3): a trial agent dir implies a trial provider catalog. */
19
+ export function piModelsPath(agentDir) {
20
+ return path.join(agentDir, 'models.json');
21
+ }
@@ -1,3 +1,4 @@
1
+ export { findPISessionFilePath } from './session-files.js';
1
2
  export declare const PI_PROVIDER_CACHE_TTL_MS: number;
2
3
  export declare const PI_PROVIDER_RETRY_MS = 30000;
3
4
  type ProviderScan = () => Promise<string[]>;
@@ -15,6 +16,3 @@ export interface PIProviderDiscoveryOptions {
15
16
  export declare function discoverPIProviders(): Promise<string[]>;
16
17
  export declare function createPIProviderDiscovery(options?: PIProviderDiscoveryOptions): PIProviderDiscovery;
17
18
  export declare const piProviderDiscovery: PIProviderDiscovery;
18
- /** Resolve PI's exact id-bearing filename without opening transcript bodies. */
19
- export declare function findPISessionFilePath(sessionDir: string, sessionId: string): string | null;
20
- export {};