@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
@@ -10,6 +10,10 @@ export interface ModelExecutionIdentityInput {
10
10
  providerProtocol: string | null;
11
11
  configuredRouteBaseHost: string | null;
12
12
  claudeCliVersion: string | null;
13
+ /** Backend-neutral CLI identity; `claudeCliVersion` keeps its Claude-only meaning so every
14
+ * hash frozen before the neutral pair existed stays reproducible from its own inputs. */
15
+ cliName: ResolvedProfileConfig['backend'] | null;
16
+ cliVersion: string | null;
13
17
  reasoningEffort: string | null;
14
18
  fallbackEmpty: true;
15
19
  }
@@ -29,6 +33,7 @@ export interface RoleToolSurfaceInput {
29
33
  skills: SkillIdentityInput[];
30
34
  mcpComposition: McpComposition;
31
35
  hookPolicy: IdentityJsonValue;
36
+ benchmarkPolicyGuard?: IdentityJsonValue;
32
37
  }
33
38
  export interface BundleManifestInput {
34
39
  runConfig: IdentityJsonValue;
@@ -1,5 +1,5 @@
1
1
  // input: resolved profiles and caller-supplied manifests
2
- // output: canonical JSON and three run identity SHA-256 hashes
2
+ // output: canonical JSON and guarded run identity SHA-256 hashes
3
3
  // pos: Pure identity freezer for one-shot agent runs
4
4
  // >>> If I am updated, update my header and folder CORTEX.md <<<
5
5
  import { createHash } from 'node:crypto';
@@ -64,6 +64,8 @@ export function computeModelExecutionIdentityHash(input) {
64
64
  provider_protocol: input.providerProtocol,
65
65
  configured_route_base_host: input.configuredRouteBaseHost,
66
66
  claude_cli_version: input.claudeCliVersion,
67
+ cli_name: input.cliName,
68
+ cli_version: input.cliVersion,
67
69
  reasoning_effort: input.reasoningEffort,
68
70
  fallback_empty: input.fallbackEmpty,
69
71
  });
@@ -84,6 +86,7 @@ export function computeRoleToolSurfaceHash(input) {
84
86
  skills: [...input.skills].sort((a, b) => compareText(a.name, b.name)),
85
87
  mcp_composition: input.mcpComposition,
86
88
  hook_policy: input.hookPolicy,
89
+ benchmark_policy_guard: input.benchmarkPolicyGuard,
87
90
  });
88
91
  }
89
92
  export function computeBundleManifestHash(input) {
@@ -1,5 +1,6 @@
1
1
  import type { NormalizedEvent } from '../../agent-adapter/normalize/event-types.js';
2
- export type AgentSlot = 'parent' | 'benchmark-coder' | 'benchmark-reviewer';
2
+ import type { Backend } from '../../agent-adapter/types.js';
3
+ export type AgentSlot = 'parent' | 'benchmark-coder' | 'benchmark-reviewer' | 'benchmark-fixer';
3
4
  export declare class TrajectoryWriteFailedError extends Error {
4
5
  readonly reason: "trajectory_write_failed";
5
6
  constructor(message?: string, options?: {
@@ -29,7 +30,7 @@ export interface JournalEventInput {
29
30
  threadId: string | null;
30
31
  step: number | null;
31
32
  agentSlot: AgentSlot;
32
- backend: 'claude';
33
+ backend: Backend;
33
34
  provider: string | null;
34
35
  requestedModel: string;
35
36
  reportedModel: string | null;
@@ -362,7 +362,11 @@ function isNullableInteger(value) {
362
362
  return value === null || Number.isInteger(value);
363
363
  }
364
364
  function isAgentSlot(value) {
365
- return value === 'parent' || value === 'benchmark-coder' || value === 'benchmark-reviewer';
365
+ return value === 'parent' || value === 'benchmark-coder' || value === 'benchmark-reviewer'
366
+ || value === 'benchmark-fixer';
367
+ }
368
+ function isBackend(value) {
369
+ return value === 'claude' || value === 'pi';
366
370
  }
367
371
  function isTimestamp(value) {
368
372
  if (typeof value !== 'string' || !TIMESTAMP_PATTERN.test(value))
@@ -441,7 +445,7 @@ function validEventRecord(value, expectedSeq, header) {
441
445
  isNullableInteger(value.step),
442
446
  isAgentSlot(value.agent_slot),
443
447
  isTimestamp(value.ts),
444
- value.backend === 'claude',
448
+ isBackend(value.backend),
445
449
  isNullableString(value.provider),
446
450
  isNonEmptyString(value.requested_model),
447
451
  isNullableString(value.reported_model),
@@ -504,8 +508,11 @@ function trackRoleIdentity(state, value) {
504
508
  return false;
505
509
  const expected = state.roleIdentities.get(slot);
506
510
  if (!expected) {
507
- const reused = [...state.roleIdentities.values()].some(identity => (identity.roleToolSurfaceHash === observed.roleToolSurfaceHash
508
- || identity.bundleManifestHash === observed.bundleManifestHash));
511
+ // Distinctness is asked of the role hash only. A compiled trial policy carries one
512
+ // `bundle_manifest_hash` for the whole arm, so every slot of a policy-backed run legitimately
513
+ // presents the same one (design section 16 (16.2) ID2); and a slot that presents another slot's
514
+ // whole identity still shares its role hash, which this clause catches on its own.
515
+ const reused = [...state.roleIdentities.values()].some(identity => (identity.roleToolSurfaceHash === observed.roleToolSurfaceHash));
509
516
  if (reused)
510
517
  return false;
511
518
  state.roleIdentities.set(slot, observed);
@@ -30,6 +30,10 @@ export interface PinnedNodeLaunchSpec {
30
30
  stdio: StdioOptions;
31
31
  paths: PinnedTrialPaths;
32
32
  }
33
+ /** Exact child environment for a trial process: the allowlisted runtime keys plus the pinned
34
+ * trial paths, with nothing else inherited from the host. Callers add only the keys the
35
+ * backend genuinely needs on top. */
36
+ export declare function pinnedTrialEnvironment(paths: PinnedTrialPaths, parentEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
33
37
  export declare function preparePinnedTrialPaths(trialRoot: string): PinnedTrialPaths;
34
38
  export declare function preparePinnedNodeLaunch(options: PinnedNodeLaunchOptions): PinnedNodeLaunchSpec;
35
39
  export declare function spawnPinnedNode(options: PinnedNodeLaunchOptions): ChildProcess;
@@ -139,6 +139,15 @@ function pinnedEnvironment(paths) {
139
139
  TEMP: paths.tempDir,
140
140
  };
141
141
  }
142
+ /** Exact child environment for a trial process: the allowlisted runtime keys plus the pinned
143
+ * trial paths, with nothing else inherited from the host. Callers add only the keys the
144
+ * backend genuinely needs on top. */
145
+ export function pinnedTrialEnvironment(paths, parentEnv = process.env) {
146
+ return {
147
+ ...inheritedEnvironment(parentEnv, paths, [], paths.root),
148
+ ...pinnedEnvironment(paths),
149
+ };
150
+ }
142
151
  function assertEmptyProjectsDir(projectsDir) {
143
152
  if (fs.existsSync(projectsDir) && fs.readdirSync(projectsDir).length > 0) {
144
153
  throw new Error(`CORTEX_PROJECTS_DIR must be empty: ${projectsDir}`);
@@ -1,4 +1,4 @@
1
1
  import type { AgentSpawnConfig } from '../../agent-adapter/types.js';
2
- import { type RoleToolSurfaceInput } from './identity.js';
2
+ import { type IdentityJsonValue, type RoleToolSurfaceInput } from './identity.js';
3
3
  export declare function directoryContentSha256(directory: string): string;
4
- export declare function roleSurfaceFromSpawnConfig(config: AgentSpawnConfig, directive?: string): RoleToolSurfaceInput;
4
+ export declare function roleSurfaceFromSpawnConfig(config: AgentSpawnConfig, directive?: string, benchmarkPolicyGuard?: IdentityJsonValue): RoleToolSurfaceInput;
@@ -1,5 +1,5 @@
1
1
  // input: resolved AgentSpawnConfig and plugin directory trees
2
- // output: content-addressed role/tool identity surface
2
+ // output: content-addressed role, tool, and guard surface
3
3
  // pos: Anti-divergence identity projection for one-shot spawns
4
4
  // >>> If I am updated, update my header and folder CORTEX.md <<<
5
5
  import { createHash } from 'node:crypto';
@@ -85,9 +85,9 @@ function hookPolicy(config) {
85
85
  const tools = spawnedTools(config).join(',');
86
86
  return buildHooksSettings(tools);
87
87
  }
88
- export function roleSurfaceFromSpawnConfig(config, directive = '') {
88
+ export function roleSurfaceFromSpawnConfig(config, directive = '', benchmarkPolicyGuard) {
89
89
  const pluginDirs = config.pluginDirs ?? [];
90
- return {
90
+ const surface = {
91
91
  systemPromptSha256: sha256(config.systemPrompt ?? ''),
92
92
  directiveSha256: sha256(directive),
93
93
  tools: spawnedTools(config),
@@ -96,4 +96,8 @@ export function roleSurfaceFromSpawnConfig(config, directive = '') {
96
96
  mcpComposition: config.mcpComposition ?? 'direct',
97
97
  hookPolicy: hookPolicy(config),
98
98
  };
99
+ if (benchmarkPolicyGuard !== undefined) {
100
+ surface.benchmarkPolicyGuard = benchmarkPolicyGuard;
101
+ }
102
+ return surface;
99
103
  }
@@ -1,5 +1,6 @@
1
1
  import type { McpComposition } from '../../agent-adapter/types.js';
2
- import type { ResolvedProfileConfig } from '../agents/profile-manager.js';
2
+ import { type ResolvedProfileConfig } from '../agents/profile-manager.js';
3
+ import { type ResolvedTrialPolicy } from '../benchmark/resolved-policy.js';
3
4
  import type { FrozenIdentityInput, IdentityJsonValue } from './identity.js';
4
5
  export { resolvedRouteHost } from './identity.js';
5
6
  export interface ResolvedAgentRunRole {
@@ -18,5 +19,13 @@ export interface ResolvedAgentRunConfig {
18
19
  adapterHashes: IdentityJsonValue;
19
20
  harnessHashes: IdentityJsonValue;
20
21
  }
22
+ export interface LoadedAgentRunConfig {
23
+ config: ResolvedAgentRunConfig;
24
+ policy?: ResolvedTrialPolicy;
25
+ }
21
26
  export declare function loadAgentRunConfig(file?: string): ResolvedAgentRunConfig;
27
+ export declare function loadAgentRunConfigWithPolicy(options: {
28
+ runConfigFile?: string;
29
+ agentSlot: string;
30
+ }): LoadedAgentRunConfig;
22
31
  export declare function validateResolvedExecution(profile: ResolvedProfileConfig, _config: ResolvedAgentRunConfig): void;
@@ -1,13 +1,16 @@
1
- // input: file/stdin run-config JSON, resolved profile, defaults
2
- // output: argv-closed frozen inputs and one non-empty spawn role
1
+ // input: file/stdin run config, profile resolver, policy compiler
2
+ // output: resolved config with optional frozen benchmark policy
3
3
  // pos: Configuration boundary for daemon-free one-shot runs
4
- // >>> If I am updated, update my header and folder CORTEX.md <<<
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { z } from 'zod';
8
8
  import { DEFAULT_TOOLS } from '../../agent-adapter/claude/defaults.js';
9
9
  import { readStdinSync } from '../../core/cli-utils.js';
10
10
  import { DEFAULTS_DIR } from '../../core/paths.js';
11
+ import { resolveProfileConfig, } from '../agents/profile-manager.js';
12
+ import { compileResolvedTrialPolicy, projectAgentRunConfig, } from '../benchmark/policy-compiler.js';
13
+ import { PolicyCompilationError, reportBenchmarkFailure, } from '../benchmark/resolved-policy.js';
11
14
  export { resolvedRouteHost } from './identity.js';
12
15
  const roleSchema = z.object({
13
16
  system_prompt: z.string(),
@@ -46,6 +49,14 @@ function readJson(file) {
46
49
  throw new Error(`Failed to read JSON file '${file}': ${error.message}`);
47
50
  }
48
51
  }
52
+ function readRunConfigDocument(file) {
53
+ if (file === '-') {
54
+ return {
55
+ value: parseJson(readStdinSync(), 'stdin'), base: process.cwd(), source: 'stdin',
56
+ };
57
+ }
58
+ return { value: readJson(file), base: path.dirname(file), source: 'file' };
59
+ }
49
60
  function resolveConfigPaths(base, values) {
50
61
  return values.map(value => path.resolve(base, value));
51
62
  }
@@ -98,6 +109,8 @@ function defaultConfig() {
98
109
  modelAliasPolicy: null,
99
110
  configuredRouteBaseHost: null,
100
111
  claudeCliVersion: null,
112
+ cliName: null,
113
+ cliVersion: null,
101
114
  },
102
115
  role,
103
116
  runConfig: null,
@@ -113,6 +126,8 @@ function resolvedRunConfig(value, base) {
113
126
  modelAliasPolicy: parsed.model_execution.model_alias_policy,
114
127
  configuredRouteBaseHost: null,
115
128
  claudeCliVersion: null,
129
+ cliName: null,
130
+ cliVersion: null,
116
131
  },
117
132
  role: roleConfig(base, parsed.role),
118
133
  runConfig: parsed.bundle.run_config,
@@ -121,12 +136,48 @@ function resolvedRunConfig(value, base) {
121
136
  harnessHashes: parsed.bundle.harness_hashes,
122
137
  };
123
138
  }
139
+ function topLevelSchemaVersion(value) {
140
+ if (value === null || typeof value !== 'object')
141
+ return undefined;
142
+ return value.schema_version;
143
+ }
144
+ function policyCompilerDependencies() {
145
+ return {
146
+ wall_clock_ms: Date.now,
147
+ monotonic_ns: () => process.hrtime.bigint(),
148
+ resolve_profile: resolveProfileConfig,
149
+ };
150
+ }
151
+ function unknownRunConfigSchema() {
152
+ const error = new PolicyCompilationError('run_config_schema_unknown');
153
+ reportBenchmarkFailure(error);
154
+ throw error;
155
+ }
156
+ function dispatchRunConfig(document, agentSlot) {
157
+ const schemaVersion = topLevelSchemaVersion(document.value);
158
+ if (schemaVersion === 'cortex-agent-run-config/1') {
159
+ return { config: resolvedRunConfig(document.value, document.base) };
160
+ }
161
+ if (schemaVersion === 'cortex-benchmark-arm-resolution/1') {
162
+ if (document.source === 'stdin') {
163
+ throw new Error('Benchmark arm resolution requires --run-config to be a file path');
164
+ }
165
+ const policy = compileResolvedTrialPolicy(document.value, policyCompilerDependencies());
166
+ const projection = projectAgentRunConfig(policy, agentSlot);
167
+ return { config: resolvedRunConfig(projection, process.cwd()), policy };
168
+ }
169
+ return unknownRunConfigSchema();
170
+ }
124
171
  export function loadAgentRunConfig(file) {
125
172
  if (file === undefined)
126
173
  return defaultConfig();
127
- if (file === '-')
128
- return resolvedRunConfig(parseJson(readStdinSync(), 'stdin'), process.cwd());
129
- return resolvedRunConfig(readJson(file), path.dirname(file));
174
+ const document = readRunConfigDocument(file);
175
+ return resolvedRunConfig(document.value, document.base);
176
+ }
177
+ export function loadAgentRunConfigWithPolicy(options) {
178
+ if (options.runConfigFile === undefined)
179
+ return { config: defaultConfig() };
180
+ return dispatchRunConfig(readRunConfigDocument(options.runConfigFile), options.agentSlot);
130
181
  }
131
182
  export function validateResolvedExecution(profile, _config) {
132
183
  const extra = Object.keys(profile.extraOption)[0];
@@ -1,20 +1,25 @@
1
- // input: parsed options, frozen config, reported-cost metadata
1
+ // input: parsed options, resolved config/policy, cost metadata
2
2
  // output: supervised turn, journal, nullable accounting, manifest
3
3
  // pos: Agent-run lifecycle coordinator
4
- // >>> If I am updated, update my header and folder CORTEX.md <<<
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
6
  import { spawnSync } from 'node:child_process';
7
7
  import fs from 'node:fs';
8
+ import path from 'node:path';
8
9
  import { readStdinBufferSync } from '../../core/cli-utils.js';
9
10
  import { setProcessLogPolicy } from '../../core/log.js';
10
11
  import { ClaudeAdapter } from '../../agent-adapter/claude/adapter.js';
11
12
  import { buildAgentSpawnConfig, runWithAdapter, } from '../agents/facade.js';
12
13
  import { listProfiles, resolveProfileConfig } from '../agents/profile-manager.js';
14
+ import { createTrialAdapter, trialAgentConfig, trialRunOptions, } from '../benchmark/trial-adapter-factory.js';
15
+ import { publishLeaseEcho } from '../benchmark/lease-echo.js';
16
+ import { PolicyCompilationError, reportBenchmarkFailure } from '../benchmark/resolved-policy.js';
17
+ import { preparePinnedTrialPaths } from './pinned-node-process.js';
13
18
  import { canonicalJsonSha256, freezeIdentity, IdentityProfileFallbackError, } from './identity.js';
14
19
  import { openJournal, TrajectoryWriteFailedError, } from './journal.js';
15
20
  import { resolveLifecyclePaths, writeStartedMarker, writeTerminalManifest, } from './manifest.js';
16
21
  import { buildTerminalManifest } from './manifest-contract.js';
17
- import { loadAgentRunConfig, resolvedRouteHost, validateResolvedExecution, } from './run-config.js';
22
+ import { loadAgentRunConfigWithPolicy, resolvedRouteHost, validateResolvedExecution, } from './run-config.js';
18
23
  import { roleSurfaceFromSpawnConfig } from './role-surface.js';
19
24
  import { attachSupervisor, exitCodeFor, } from './supervisor.js';
20
25
  function sha256(value) {
@@ -75,9 +80,18 @@ function bundleIdentity(options, config) {
75
80
  harnessHashes: config.harnessHashes,
76
81
  };
77
82
  }
78
- function freezeRunIdentity(options, profile, config, roleSurface) {
83
+ function freezeRunIdentity(options, profile, config, roleSurface, policy) {
84
+ const execution = policy?.model_execution;
85
+ const resolvedProfile = execution ? {
86
+ ...profile,
87
+ model: execution.requested_model,
88
+ backend: execution.backend,
89
+ provider: execution.provider_protocol,
90
+ thinking: execution.reasoning_effort,
91
+ fallback: [],
92
+ } : profile;
79
93
  return freezeIdentity({
80
- resolvedProfile: profile,
94
+ resolvedProfile,
81
95
  modelExecution: config.modelExecution,
82
96
  roleToolSurface: roleSurface,
83
97
  bundleManifest: bundleIdentity(options, config),
@@ -128,15 +142,23 @@ function probeClaudeVersion(profile, cwd) {
128
142
  }
129
143
  return version;
130
144
  }
131
- function observedRunConfig(config, profile, cwd) {
132
- return {
133
- ...config,
134
- modelExecution: {
135
- ...config.modelExecution,
145
+ // C3/C6: with a policy in hand the CLI version and the identity route host are frozen values, so
146
+ // re-probing the CLI or reading the host profile's route would be the runtime re-resolution §2.7
147
+ // forbids. §1.7 keeps the identity host distinct from the per-trial proxy authority the child is
148
+ // actually routed at, which is why the proxy URL is not read back here.
149
+ function observedRunConfig(config, profile, cwd, policy) {
150
+ const execution = policy
151
+ ? {
152
+ configuredRouteBaseHost: policy.model_execution.configured_route_base_host,
153
+ claudeCliVersion: policy.model_execution.claude_cli_version,
154
+ cliName: policy.model_execution.cli_name,
155
+ cliVersion: policy.model_execution.cli_version,
156
+ }
157
+ : {
136
158
  configuredRouteBaseHost: resolvedRouteHost(profile),
137
159
  claudeCliVersion: probeClaudeVersion(profile, cwd),
138
- },
139
- };
160
+ };
161
+ return { ...config, modelExecution: { ...config.modelExecution, ...execution } };
140
162
  }
141
163
  function assertFreshTrajectory(options, rootRunId) {
142
164
  const lifecycle = resolveLifecyclePaths({
@@ -181,29 +203,88 @@ function baseRunOptions(options, profile, config, key) {
181
203
  tools: config.role.tools.join(','),
182
204
  };
183
205
  }
184
- function resolveRunConfig(options, profile) {
185
- const configured = loadAgentRunConfig(options.runConfigFile);
186
- validateResolvedExecution(profile, configured);
187
- assertMcpFiles(configured);
188
- return observedRunConfig(configured, profile, options.cwd);
206
+ function assertBenchmarkInvocation(loaded, options, rootRunId) {
207
+ if (!loaded.policy)
208
+ return;
209
+ if (loaded.policy.root_run_id !== rootRunId) {
210
+ throw new Error(`Benchmark root_run_id mismatch: expected '${rootRunId}', `
211
+ + `received '${loaded.policy.root_run_id}'`);
212
+ }
213
+ const profileName = loaded.policy.asset_inventory
214
+ .find(asset => asset.kind === 'profile').logical_name;
215
+ if (profileName !== options.profile) {
216
+ throw new Error(`Benchmark profile_name mismatch: expected '${options.profile}', received '${profileName}'`);
217
+ }
218
+ }
219
+ function resolveRunInputs(options, profile, rootRunId) {
220
+ const loaded = loadAgentRunConfigWithPolicy({
221
+ runConfigFile: options.runConfigFile,
222
+ agentSlot: options.agentSlot,
223
+ });
224
+ assertBenchmarkInvocation(loaded, options, rootRunId);
225
+ if (!loaded.policy) {
226
+ assertClaudeProfile(profile);
227
+ validateResolvedExecution(profile, loaded.config);
228
+ }
229
+ assertMcpFiles(loaded.config);
230
+ return { ...loaded, config: observedRunConfig(loaded.config, profile, options.cwd, loaded.policy) };
231
+ }
232
+ // No CLI flag names the trial root, and adding a required one would break the shipped harness
233
+ // invocation. The harness places the trajectory inside the per-trial agent directory, so the trial
234
+ // root is a sibling of the trajectory root rather than the trajectory root itself.
235
+ function trialAdapterSpec(options, policy, config) {
236
+ const trialRoot = path.join(path.dirname(path.resolve(options.trajectoryRoot)), 'trial-home');
237
+ return {
238
+ policy,
239
+ slot: options.agentSlot,
240
+ config,
241
+ paths: preparePinnedTrialPaths(trialRoot),
242
+ supervisor: {
243
+ binary: options.supervisorBinary,
244
+ graceMs: options.graceMs,
245
+ deadlineMs: options.deadlineMs,
246
+ },
247
+ cwd: options.cwd,
248
+ };
249
+ }
250
+ // R4: the surface the process is actually spawned with must be the surface phase B hashed. A
251
+ // divergence means the run would be attributed to a role it is not running.
252
+ function assertPolicyRoleSurface(run) {
253
+ if (!run.policy)
254
+ return;
255
+ const expected = run.policy.identity.role_tool_surface_hash[run.options.agentSlot];
256
+ if (expected !== run.identity.roleToolSurfaceHash) {
257
+ throw new Error(`Role surface hash mismatch for slot '${run.options.agentSlot}': `
258
+ + `policy ${expected}, spawned ${run.identity.roleToolSurfaceHash}`);
259
+ }
189
260
  }
190
261
  function prepareRun(options, rootRunId) {
191
262
  assertFreshTrajectory(options, rootRunId);
192
263
  const prompt = readPrompt(options.promptFile);
193
264
  const profile = resolveProfile(options.profile);
194
- assertClaudeProfile(profile);
195
- const config = resolveRunConfig(options, profile);
196
- const baseOptions = baseRunOptions(options, profile, config, `agent-run:${rootRunId}`);
197
- const spawnConfig = buildAgentSpawnConfig(baseOptions, agentConfig(profile), undefined);
265
+ const loaded = resolveRunInputs(options, profile, rootRunId);
266
+ const config = loaded.config;
267
+ const spec = loaded.policy ? trialAdapterSpec(options, loaded.policy, config) : null;
268
+ const trial = spec ? createTrialAdapter(spec) : null;
269
+ const baseOptions = spec
270
+ ? trialRunOptions(spec)
271
+ : baseRunOptions(options, profile, config, `agent-run:${rootRunId}`);
272
+ const spawnConfig = trial?.spawnConfig
273
+ ?? buildAgentSpawnConfig(baseOptions, agentConfig(profile), undefined);
198
274
  spawnConfig.preserveUnreportedAccounting = true;
199
- const roleSurface = roleSurfaceFromSpawnConfig(spawnConfig);
200
- return {
201
- options, rootRunId, profile, config, spawnConfig, baseOptions,
275
+ // S7: the benchmark surface carries the directive and the guard; the legacy path carries neither.
276
+ const roleSurface = trial?.roleSurface ?? roleSurfaceFromSpawnConfig(spawnConfig);
277
+ const run = {
278
+ options, rootRunId, profile, config, policy: loaded.policy, spawnConfig, baseOptions,
279
+ trial,
280
+ backend: trial?.backend ?? profile.backend,
202
281
  modelPrompt: prompt.modelVisible,
203
- identity: freezeRunIdentity(options, profile, config, roleSurface),
282
+ identity: freezeRunIdentity(options, profile, config, roleSurface, loaded.policy),
204
283
  hashes: promptHashes(prompt, roleSurface),
205
284
  startedAt: new Date().toISOString(),
206
285
  };
286
+ assertPolicyRoleSurface(run);
287
+ return run;
207
288
  }
208
289
  const protectedWriters = new WeakSet();
209
290
  function protectDiagnosticWriter(writer) {
@@ -239,6 +320,12 @@ function collectStats(stats, event) {
239
320
  stats.output += event.tokens_out;
240
321
  }
241
322
  }
323
+ function runProvider(run) {
324
+ return run.policy?.model_execution.provider_protocol ?? run.profile.provider;
325
+ }
326
+ function runRequestedModel(run) {
327
+ return run.policy?.model_execution.requested_model ?? run.profile.model;
328
+ }
242
329
  function trajectorySink(run, journal, stats, io) {
243
330
  return {
244
331
  onEvent(event) {
@@ -246,9 +333,9 @@ function trajectorySink(run, journal, stats, io) {
246
333
  threadId: null,
247
334
  step: null,
248
335
  agentSlot: run.options.agentSlot,
249
- backend: 'claude',
250
- provider: run.profile.provider,
251
- requestedModel: run.profile.model,
336
+ backend: run.backend,
337
+ provider: runProvider(run),
338
+ requestedModel: runRequestedModel(run),
252
339
  reportedModel: reportedModel(event),
253
340
  event,
254
341
  };
@@ -336,7 +423,11 @@ function executionError(runError, supervisorError) {
336
423
  }
337
424
  async function settledOutcome(adapter, run, handle, supervision, cancelled) {
338
425
  const handleOutcome = await settleHandle(handle);
339
- await adapter.close(`agent-run:${run.rootRunId}`);
426
+ // S5: the trial owns its adapter instance and closes it exactly once.
427
+ if (run.trial)
428
+ await run.trial.close();
429
+ else
430
+ await adapter.close(`agent-run:${run.rootRunId}`);
340
431
  const settled = await settleSupervisor(supervision);
341
432
  return {
342
433
  ...handleOutcome,
@@ -348,7 +439,7 @@ async function settledOutcome(adapter, run, handle, supervision, cancelled) {
348
439
  };
349
440
  }
350
441
  async function executeTurn(run, journal, io, stats) {
351
- const adapter = new ClaudeAdapter();
442
+ const adapter = run.trial?.adapter ?? new ClaudeAdapter();
352
443
  let supervision = null;
353
444
  let handle = null;
354
445
  let cancelled = false;
@@ -363,7 +454,8 @@ async function executeTurn(run, journal, io, stats) {
363
454
  const spawner = supervisedSpawner(run, value => { supervision = value; }, () => cancelled);
364
455
  try {
365
456
  const options = oneShotOptions(run, trajectorySink(run, journal, stats, io), spawner);
366
- handle = runWithAdapter(adapter, run.modelPrompt, options, agentConfig(run.profile), undefined);
457
+ const config = run.policy ? trialAgentConfig(run.policy, run.backend) : agentConfig(run.profile);
458
+ handle = runWithAdapter(adapter, run.modelPrompt, options, config, undefined);
367
459
  if (cancelled)
368
460
  handle.kill();
369
461
  return await settledOutcome(adapter, run, handle, supervision, () => cancelled);
@@ -480,6 +572,27 @@ function writeTerminalOutput(io, rootRunId, manifest, classified) {
480
572
  terminal_reason: classified.reason,
481
573
  });
482
574
  }
575
+ /**
576
+ * The trial proxy's credential lease was armed from the host clock before this container existed,
577
+ * so it is a provisional bound rather than the trial's own deadline. Hand the proxy the remaining
578
+ * budget — a duration, derived from the frozen policy and the container's monotonic clock — so it
579
+ * can shorten that bound to the trial the container actually compiled.
580
+ *
581
+ * An undelivered echo is deliberately not fatal. The lease then simply stays at its bound, which is
582
+ * finite by construction, and the absence is recorded on the host and fails the trial's terminal
583
+ * predicate there. Killing the run here would kill a live trial for a plumbing fault — the exact
584
+ * failure mode the echo exists to remove.
585
+ */
586
+ async function echoTrialLease(run, io) {
587
+ if (!run.policy)
588
+ return;
589
+ try {
590
+ await publishLeaseEcho(run.policy, { monotonic_ns: () => process.hrtime.bigint() });
591
+ }
592
+ catch (error) {
593
+ io.stderr.write(`lease echo unavailable: ${error?.message ?? String(error)}\n`);
594
+ }
595
+ }
483
596
  function classifyStartupFailure(error) {
484
597
  const reason = errorReason(error);
485
598
  if (reason === 'trajectory_write_failed')
@@ -498,6 +611,8 @@ export async function runOneShotAgent(options, io) {
498
611
  journal = openRunJournal(run);
499
612
  writeJsonLine(io, journal.header);
500
613
  writeStart(run);
614
+ // Before any model process is admitted.
615
+ await echoTrialLease(run, io);
501
616
  const stats = { input: 0, output: 0, sawInput: false, sawOutput: false };
502
617
  const outcome = await executeTurn(run, journal, io, stats);
503
618
  const classified = classify(outcome);
@@ -508,6 +623,9 @@ export async function runOneShotAgent(options, io) {
508
623
  catch (error) {
509
624
  await journal?.close().catch(() => { });
510
625
  const classified = classifyStartupFailure(error);
626
+ // §2.6 P-class invariant: a refused policy leaves its coded reason on stderr as JSON.
627
+ if (error instanceof PolicyCompilationError)
628
+ reportBenchmarkFailure(error, io.stderr);
511
629
  io.stderr.write(`${error?.message ?? String(error)}\n`);
512
630
  writeTerminalOutput(io, rootRunId, null, classified);
513
631
  return classified.exitCode;