@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
@@ -0,0 +1,110 @@
1
+ import type { Backend } from '../../agent-adapter/types.js';
2
+ import type { IdentityJsonValue, RoleToolSurfaceInput } from '../agent-run/identity.js';
3
+ import type { ResolvedAgentRunRole } from '../agent-run/run-config.js';
4
+ import type { ArmDefinition, ArmLimits } from './arm-schema.js';
5
+ import type { BenchmarkBrokerCapability } from './capabilities.js';
6
+ declare const FAILURE_ROWS: readonly [readonly [1, "arm_schema_invalid"], readonly [2, "arm_field_conflict"], readonly [3, "coder_review_variant_invalid"], readonly [4, "ask_manager_unsupported_mode"], readonly [5, "limit_out_of_range"], readonly [6, "deadline_nonpositive"], readonly [7, "capacity_rule_violated"], readonly [8, "credential_capability_unknown"], readonly [9, "credential_capability_unsupported"], readonly [10, "credential_capability_state_insufficient"], readonly [11, "profile_unresolvable"], readonly [12, "profile_has_fallbacks"], readonly [13, "profile_extra_option_unsupported"], readonly [14, "backend_unsupported_for_kind"], readonly [15, "asset_missing"], readonly [16, "asset_unreadable"], readonly [17, "asset_hash_mismatch"], readonly [18, "duplicate_skill_name"], readonly [19, "mcp_composition_invalid"], readonly [20, "template_not_whitelisted"], readonly [21, "image_digest_unpinned"], readonly [22, "policy_freeze_failed"], readonly [23, "policy_reresolution_attempted"], readonly [24, "coordinator_start_failed"], readonly [25, "parent_detached"], readonly [26, "finalization_incomplete"], readonly [27, "sidecar_unauthenticated"], readonly [28, "backend_lacks_long_mcp_call"], readonly [29, "cli_version_unsupported_for_long_mcp_call"], readonly [30, "policy_guard_absent"], readonly [31, "runtime_port_unbound"], readonly [32, "port_scope_escaped"], readonly [33, "capability_denied"], readonly [34, "stale_generation"], readonly [35, "cross_branch_mutation"], readonly [36, "out_of_trial_path"], readonly [37, "proposal_invalidated"], readonly [38, "seal_precondition_unmet"], readonly [39, "attempt_unaccounted"], readonly [40, "composite_manifest_invalid"], readonly [41, "terminal_predicate_unmet"], readonly [42, "ledger_unreadable"], readonly [43, "arm_profile_value_mismatch"], readonly [44, "run_config_schema_unknown"]];
7
+ export type BenchmarkFailureReason = typeof FAILURE_ROWS[number][1];
8
+ export type BenchmarkFailureClass = 'P' | 'R';
9
+ export interface BenchmarkFailureSpec {
10
+ code: number;
11
+ reason: BenchmarkFailureReason;
12
+ failureClass: BenchmarkFailureClass;
13
+ }
14
+ export declare const BENCHMARK_FAILURES: readonly BenchmarkFailureSpec[];
15
+ export declare const BENCHMARK_FAILURE_INVARIANTS: Readonly<{
16
+ P: readonly string[];
17
+ R: readonly string[];
18
+ }>;
19
+ export interface FailureStderr {
20
+ write(chunk: string): unknown;
21
+ }
22
+ export declare class PolicyCompilationError extends Error {
23
+ readonly reason: BenchmarkFailureReason;
24
+ readonly payload?: Readonly<Record<string, string | null>>;
25
+ readonly code: number;
26
+ readonly failureClass: BenchmarkFailureClass;
27
+ constructor(reason: BenchmarkFailureReason, detail?: string, payload?: Readonly<Record<string, string | null>>);
28
+ record(): Record<string, string | number | null>;
29
+ }
30
+ export declare function reportBenchmarkFailure(error: PolicyCompilationError, stderr?: FailureStderr): void;
31
+ export type AssetKind = 'arm' | 'credential_capability' | 'profile' | 'cli_artifact' | 'provider_route' | 'prompt' | 'tool_set' | 'plugin_dir' | 'skill' | 'mcp_server' | 'thread_template' | 'thread_agent' | 'limits';
32
+ export interface PolicyAssetInventoryEntry {
33
+ ordinal: number;
34
+ kind: AssetKind;
35
+ logical_name: string;
36
+ resolved_path: string;
37
+ content_sha256: string;
38
+ }
39
+ export interface ResolvedPolicyModelExecution {
40
+ backend: Backend;
41
+ requested_model: string;
42
+ model_alias_policy: IdentityJsonValue;
43
+ provider_protocol: string | null;
44
+ configured_route_base_host: string | null;
45
+ claude_cli_version: string | null;
46
+ cli_name: Backend | null;
47
+ cli_version: string | null;
48
+ reasoning_effort: string | null;
49
+ fallback_empty: true;
50
+ }
51
+ export type CredentialCapabilityState = 'unsupported' | 'offline-contract-passed' | 'live-handshake-passed';
52
+ export interface ResolvedTrialPolicy {
53
+ schema_version: 'cortex-benchmark-resolved-policy/2';
54
+ arm: ArmDefinition;
55
+ arm_canonical_sha256: string;
56
+ trial_id: string;
57
+ root_run_id: string;
58
+ task: {
59
+ task_id: string;
60
+ image_ref: string;
61
+ image_digest: string;
62
+ };
63
+ deadline: {
64
+ compiled_at_epoch_ms: number;
65
+ absolute_epoch_ms: number;
66
+ monotonic_origin_ns: bigint;
67
+ };
68
+ asset_inventory: PolicyAssetInventoryEntry[];
69
+ asset_inventory_sha256: string;
70
+ model_execution: ResolvedPolicyModelExecution;
71
+ roles: Record<string, ResolvedAgentRunRole>;
72
+ /** Compiled benchmark policy guard per slot. A slot without a guard has no key. */
73
+ role_policy_guard: Record<string, IdentityJsonValue>;
74
+ /** Gate condition for constructing a PI trial adapter; false refuses the arm at construction. */
75
+ pi_benchmark_capability_proven: boolean;
76
+ identity: {
77
+ model_execution_identity_hash: Record<string, string>;
78
+ role_tool_surface_hash: Record<string, string>;
79
+ bundle_manifest_hash: string;
80
+ };
81
+ child_template_whitelist: string[];
82
+ capability_whitelist: BenchmarkBrokerCapability[];
83
+ credential: {
84
+ capability_key: string;
85
+ capability_state: CredentialCapabilityState;
86
+ upstream_base_url: string;
87
+ route_identity_host: string;
88
+ proxy_base_url: string;
89
+ dummy_token_ref: string;
90
+ };
91
+ limits: ArmLimits;
92
+ derived: {
93
+ effective_admission_budget: number;
94
+ };
95
+ artifact_inventory_spec: IdentityJsonValue;
96
+ }
97
+ /**
98
+ * The role surface the phase-B compiler hashed for a slot, read back out of the frozen policy. The
99
+ * compiler's own `roleSurface` is not exported and its working value is gone by the time a thread
100
+ * runs, so this reconstructs the same members from what the policy publishes: the prompt and
101
+ * directive digests and the plugin and skill content hashes from the asset inventory, and the tool
102
+ * list, MCP composition and the hard-coded empty hook policy from the resolved role. The compiled
103
+ * guard is deliberately NOT included — a caller that wants the full eight-member surface adds
104
+ * `role_policy_guard[slot]`, which is the difference between the two byte sources.
105
+ * Returns null for a slot the policy does not compile.
106
+ */
107
+ export declare function compiledRoleSurface(policy: ResolvedTrialPolicy, slot: string): RoleToolSurfaceInput | null;
108
+ export declare function deepFreezePolicy(policy: ResolvedTrialPolicy): ResolvedTrialPolicy;
109
+ export declare function remainingDeadlineMs(policy: ResolvedTrialPolicy, monotonicNowNs: bigint): number;
110
+ export {};
@@ -0,0 +1,195 @@
1
+ // input: validated arms, resolved assets, benchmark failures 1-44
2
+ // output: frozen policy types, failure classes, deadline accessor
3
+ // pos: Authoritative in-memory benchmark policy value object
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ const FAILURE_ROWS = [
6
+ [1, 'arm_schema_invalid'],
7
+ [2, 'arm_field_conflict'],
8
+ [3, 'coder_review_variant_invalid'],
9
+ [4, 'ask_manager_unsupported_mode'],
10
+ [5, 'limit_out_of_range'],
11
+ [6, 'deadline_nonpositive'],
12
+ [7, 'capacity_rule_violated'],
13
+ [8, 'credential_capability_unknown'],
14
+ [9, 'credential_capability_unsupported'],
15
+ [10, 'credential_capability_state_insufficient'],
16
+ [11, 'profile_unresolvable'],
17
+ [12, 'profile_has_fallbacks'],
18
+ [13, 'profile_extra_option_unsupported'],
19
+ [14, 'backend_unsupported_for_kind'],
20
+ [15, 'asset_missing'],
21
+ [16, 'asset_unreadable'],
22
+ [17, 'asset_hash_mismatch'],
23
+ [18, 'duplicate_skill_name'],
24
+ [19, 'mcp_composition_invalid'],
25
+ [20, 'template_not_whitelisted'],
26
+ [21, 'image_digest_unpinned'],
27
+ [22, 'policy_freeze_failed'],
28
+ [23, 'policy_reresolution_attempted'],
29
+ [24, 'coordinator_start_failed'],
30
+ [25, 'parent_detached'],
31
+ [26, 'finalization_incomplete'],
32
+ [27, 'sidecar_unauthenticated'],
33
+ [28, 'backend_lacks_long_mcp_call'],
34
+ [29, 'cli_version_unsupported_for_long_mcp_call'],
35
+ [30, 'policy_guard_absent'],
36
+ [31, 'runtime_port_unbound'],
37
+ [32, 'port_scope_escaped'],
38
+ [33, 'capability_denied'],
39
+ [34, 'stale_generation'],
40
+ [35, 'cross_branch_mutation'],
41
+ [36, 'out_of_trial_path'],
42
+ [37, 'proposal_invalidated'],
43
+ [38, 'seal_precondition_unmet'],
44
+ [39, 'attempt_unaccounted'],
45
+ [40, 'composite_manifest_invalid'],
46
+ [41, 'terminal_predicate_unmet'],
47
+ [42, 'ledger_unreadable'],
48
+ [43, 'arm_profile_value_mismatch'],
49
+ [44, 'run_config_schema_unknown'],
50
+ ];
51
+ const CLASS_P_CODES = new Set([
52
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
53
+ 24, 28, 29, 30, 43, 44,
54
+ ]);
55
+ export const BENCHMARK_FAILURES = Object.freeze(FAILURE_ROWS.map(([code, reason]) => Object.freeze({
56
+ code,
57
+ reason,
58
+ failureClass: CLASS_P_CODES.has(code) ? 'P' : 'R',
59
+ })));
60
+ export const BENCHMARK_FAILURE_INVARIANTS = Object.freeze({
61
+ P: Object.freeze([
62
+ 'nonzero_exit', 'no_partial_policy_or_process_admitted', 'json_reason_stderr',
63
+ ]),
64
+ R: Object.freeze([
65
+ 'nonzero_exit', 'strict_finalization', 'json_reason_stderr',
66
+ ]),
67
+ });
68
+ function failureByReason(reason) {
69
+ const failure = BENCHMARK_FAILURES.find(candidate => candidate.reason === reason);
70
+ if (!failure)
71
+ throw new Error(`Unknown benchmark failure reason: ${reason}`);
72
+ return failure;
73
+ }
74
+ export class PolicyCompilationError extends Error {
75
+ reason;
76
+ payload;
77
+ code;
78
+ failureClass;
79
+ constructor(reason, detail, payload) {
80
+ super(detail ? `${reason}: ${detail}` : reason);
81
+ this.reason = reason;
82
+ this.payload = payload;
83
+ this.name = 'PolicyCompilationError';
84
+ const failure = failureByReason(reason);
85
+ this.code = failure.code;
86
+ this.failureClass = failure.failureClass;
87
+ }
88
+ record() {
89
+ return {
90
+ code: this.code,
91
+ failure_class: this.failureClass,
92
+ reason: this.reason,
93
+ ...this.payload,
94
+ };
95
+ }
96
+ }
97
+ export function reportBenchmarkFailure(error, stderr = process.stderr) {
98
+ stderr.write(`${JSON.stringify(error.record())}\n`);
99
+ }
100
+ /** The inventory keys every per-role asset as `<slot>:<rest>`; a slot is the part before the first
101
+ * separator, so `benchmark-coder` never matches `benchmark-coder-x`. */
102
+ function inventoryFor(policy, kind, slot) {
103
+ return policy.asset_inventory.filter(entry => (entry.kind === kind && entry.logical_name.slice(0, entry.logical_name.indexOf(':')) === slot));
104
+ }
105
+ function inventoryNamed(policy, kind, logicalName) {
106
+ return policy.asset_inventory.find(entry => (entry.kind === kind && entry.logical_name === logicalName));
107
+ }
108
+ /**
109
+ * The role surface the phase-B compiler hashed for a slot, read back out of the frozen policy. The
110
+ * compiler's own `roleSurface` is not exported and its working value is gone by the time a thread
111
+ * runs, so this reconstructs the same members from what the policy publishes: the prompt and
112
+ * directive digests and the plugin and skill content hashes from the asset inventory, and the tool
113
+ * list, MCP composition and the hard-coded empty hook policy from the resolved role. The compiled
114
+ * guard is deliberately NOT included — a caller that wants the full eight-member surface adds
115
+ * `role_policy_guard[slot]`, which is the difference between the two byte sources.
116
+ * Returns null for a slot the policy does not compile.
117
+ */
118
+ export function compiledRoleSurface(policy, slot) {
119
+ const role = policy.roles[slot];
120
+ const systemPrompt = inventoryNamed(policy, 'prompt', `${slot}:system_prompt`);
121
+ const directive = inventoryNamed(policy, 'prompt', `${slot}:directive`);
122
+ if (role === undefined || systemPrompt === undefined || directive === undefined)
123
+ return null;
124
+ const pluginDirs = inventoryFor(policy, 'plugin_dir', slot)
125
+ .map(entry => ({ path: entry.resolved_path, content_sha256: entry.content_sha256 }));
126
+ const skills = inventoryFor(policy, 'skill', slot).map(entry => ({
127
+ name: entry.logical_name.slice(entry.logical_name.indexOf(':') + 1),
128
+ content_sha256: entry.content_sha256,
129
+ }));
130
+ return {
131
+ systemPromptSha256: systemPrompt.content_sha256,
132
+ directiveSha256: directive.content_sha256,
133
+ tools: [...role.tools],
134
+ pluginDirs,
135
+ skills,
136
+ mcpComposition: role.mcpComposition,
137
+ hookPolicy: {},
138
+ };
139
+ }
140
+ function cloneArray(value, seen) {
141
+ return value.map(item => cloneFreezable(item, seen));
142
+ }
143
+ function cloneRecord(value, seen) {
144
+ const descriptors = Object.getOwnPropertyDescriptors(value);
145
+ const result = {};
146
+ for (const [key, descriptor] of Object.entries(descriptors)) {
147
+ if (descriptor.get || descriptor.set)
148
+ throw new TypeError(`Accessor is not freezable: ${key}`);
149
+ if (descriptor.enumerable)
150
+ result[key] = cloneFreezable(descriptor.value, seen);
151
+ }
152
+ return result;
153
+ }
154
+ function cloneScalar(value) {
155
+ if (typeof value === 'function' || typeof value === 'symbol') {
156
+ throw new TypeError('Non-data value is not freezable');
157
+ }
158
+ return value;
159
+ }
160
+ function assertFreezableContainer(value, seen) {
161
+ if (seen.has(value))
162
+ throw new TypeError('Circular policy value');
163
+ const valid = Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype;
164
+ if (!valid)
165
+ throw new TypeError('Mutable container is not allowed in policy');
166
+ seen.add(value);
167
+ }
168
+ function cloneFreezable(value, seen) {
169
+ if (value === null || typeof value !== 'object')
170
+ return cloneScalar(value);
171
+ assertFreezableContainer(value, seen);
172
+ const result = Array.isArray(value) ? cloneArray(value, seen) : cloneRecord(value, seen);
173
+ seen.delete(value);
174
+ return result;
175
+ }
176
+ function freezeValue(value) {
177
+ if (value === null || typeof value !== 'object')
178
+ return;
179
+ for (const child of Object.values(value))
180
+ freezeValue(child);
181
+ Object.freeze(value);
182
+ }
183
+ export function deepFreezePolicy(policy) {
184
+ const clone = cloneFreezable(policy, new Set());
185
+ freezeValue(clone);
186
+ return clone;
187
+ }
188
+ export function remainingDeadlineMs(policy, monotonicNowNs) {
189
+ const elapsedNs = monotonicNowNs > policy.deadline.monotonic_origin_ns
190
+ ? monotonicNowNs - policy.deadline.monotonic_origin_ns
191
+ : 0n;
192
+ const elapsedMs = Number(elapsedNs / 1000000n);
193
+ const budgetMs = policy.deadline.absolute_epoch_ms - policy.deadline.compiled_at_epoch_ms;
194
+ return Math.max(0, budgetMs - elapsedMs);
195
+ }
@@ -0,0 +1,38 @@
1
+ import type { AgentAdapter, AgentSpawnConfig, Backend } from '../../agent-adapter/types.js';
2
+ import type { RoleToolSurfaceInput } from '../agent-run/identity.js';
3
+ import type { AgentSlot } from '../agent-run/journal.js';
4
+ import { type PinnedTrialPaths } from '../agent-run/pinned-node-process.js';
5
+ import type { ResolvedAgentRunConfig } from '../agent-run/run-config.js';
6
+ import { type AgentConfig, type RunAgentOptions } from '../agents/spawn-config.js';
7
+ import { type ResolvedTrialPolicy } from './resolved-policy.js';
8
+ /** S1: the closed input list. It carries no spawner — S6.1 makes `spawnConfig.processSpawner` the
9
+ * single supervisor injection point, applied by the caller after construction. */
10
+ export interface TrialAdapterSpec {
11
+ policy: ResolvedTrialPolicy;
12
+ slot: AgentSlot;
13
+ /** Retained only because the legacy non-benchmark path already builds from it (S2). */
14
+ config: ResolvedAgentRunConfig;
15
+ paths: PinnedTrialPaths;
16
+ supervisor: {
17
+ binary: string;
18
+ graceMs: number;
19
+ deadlineMs?: number;
20
+ };
21
+ cwd: string;
22
+ }
23
+ export interface TrialAdapter {
24
+ adapter: AgentAdapter;
25
+ spawnConfig: AgentSpawnConfig;
26
+ roleSurface: RoleToolSurfaceInput;
27
+ backend: Backend;
28
+ close(): Promise<void>;
29
+ }
30
+ export declare function trialSessionKey(policy: ResolvedTrialPolicy): string;
31
+ /** The directive bytes the role was compiled from, located through the inventory the compiler
32
+ * wrote: `ResolvedAgentRunRole` carries no directive and GT3 forbids widening it. A directive
33
+ * that no longer matches its compiled bytes moves the role hash, which R4 then refuses. */
34
+ export declare function trialDirective(policy: ResolvedTrialPolicy, slot: AgentSlot): string;
35
+ /** C4: role composition is sourced from the policy, never from the disposable projection. */
36
+ export declare function trialRunOptions(spec: TrialAdapterSpec): RunAgentOptions;
37
+ export declare function trialAgentConfig(policy: ResolvedTrialPolicy, backend: Backend): AgentConfig;
38
+ export declare function createTrialAdapter(spec: TrialAdapterSpec): TrialAdapter;
@@ -0,0 +1,165 @@
1
+ // input: a frozen trial policy, its slot, pinned trial paths and the trial cwd
2
+ // output: a per-trial adapter, spawn surface and role surface built from the policy alone
3
+ // pos: Backend-neutral per-trial adapter construction seam
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { ClaudeAdapter } from '../../agent-adapter/claude/adapter.js';
8
+ import { PIAdapter } from '../../agent-adapter/pi/adapter.js';
9
+ import { pinnedTrialEnvironment } from '../agent-run/pinned-node-process.js';
10
+ import { roleSurfaceFromSpawnConfig } from '../agent-run/role-surface.js';
11
+ import { buildAgentSpawnConfig, } from '../agents/spawn-config.js';
12
+ import { PolicyCompilationError } from './resolved-policy.js';
13
+ /** P8/A7: the trial's provider catalog is the arm's one provider, fixed. `refresh()` is a no-op —
14
+ * a rescan is both a host reach (A8) and a cross-trial cache leak. */
15
+ function fixedProviderDiscovery(provider) {
16
+ const providers = provider === null ? [] : [provider];
17
+ return { getProviders: () => [...providers], refresh: () => { } };
18
+ }
19
+ /**
20
+ * P6/A5/A6: the trial's PI credential is the policy's dummy token, written as a real file into the
21
+ * trial-local agent dir. The shipped daemon path symlinks the host's `~/.pi/agent/auth.json` here,
22
+ * which would make a "trial-local" directory a window onto the host — §3.3's invariant is that a
23
+ * real credential never enters a trial.
24
+ */
25
+ function writeTrialAuth(agentDir, policy) {
26
+ const provider = policy.arm.provider;
27
+ if (provider === null || provider === undefined)
28
+ return;
29
+ fs.mkdirSync(agentDir, { recursive: true });
30
+ fs.writeFileSync(path.join(agentDir, 'auth.json'), `${JSON.stringify({ [provider]: { type: 'api', key: policy.credential.dummy_token_ref } }, null, 2)}\n`, { mode: 0o600 });
31
+ }
32
+ /** P4/P5: every PI state directory the trial needs, under `spec.paths.root` and nowhere else. */
33
+ function piTrialAdapter(spec) {
34
+ const agentDir = path.join(spec.paths.root, 'pi-agent');
35
+ const sessionDir = path.join(spec.paths.root, 'pi-sessions');
36
+ fs.mkdirSync(agentDir, { recursive: true });
37
+ fs.mkdirSync(sessionDir, { recursive: true });
38
+ return new PIAdapter(
39
+ // S6.1: no spawner here. The supervisor is injected onto the spawn config after the factory
40
+ // returns, and `assertBenchmarkSpawn` refuses the spawn if it never arrives.
41
+ undefined, sessionDir, fixedProviderDiscovery(spec.policy.arm.provider ?? null), { agentDir, prepareAgentDir: dir => writeTrialAuth(dir, spec.policy) });
42
+ }
43
+ /** S8: backend dispatch is a closed table, so an unlisted backend refuses rather than falling back. */
44
+ const ADAPTER_CONSTRUCTORS = {
45
+ claude: () => new ClaudeAdapter(),
46
+ pi: piTrialAdapter,
47
+ };
48
+ export function trialSessionKey(policy) {
49
+ return `agent-run:${policy.root_run_id}`;
50
+ }
51
+ function refuse(detail) {
52
+ throw new PolicyCompilationError('backend_unsupported_for_kind', detail);
53
+ }
54
+ function trialBackend(policy) {
55
+ const backend = policy.arm.backend;
56
+ if (!backend)
57
+ refuse(`arm '${policy.arm.name}' declares no backend`);
58
+ if (backend === 'pi' && policy.pi_benchmark_capability_proven !== true) {
59
+ refuse('PI benchmark capability is unproven');
60
+ }
61
+ if (ADAPTER_CONSTRUCTORS[backend] === undefined) {
62
+ refuse(`no trial adapter constructor for backend '${backend}'`);
63
+ }
64
+ return backend;
65
+ }
66
+ // GT2: a slot the compiler admitted always has a key, so an absent guard on the benchmark path is a
67
+ // defect. It fails closed here rather than spawning a model process with the ambient hook surface.
68
+ function trialGuard(policy, slot) {
69
+ const guard = policy.role_policy_guard[slot];
70
+ if (guard === undefined)
71
+ throw new PolicyCompilationError('policy_guard_absent', `role://${slot}`);
72
+ return guard;
73
+ }
74
+ function trialRole(policy, slot) {
75
+ const role = policy.roles[slot];
76
+ if (role === undefined)
77
+ throw new PolicyCompilationError('asset_missing', `role://${slot}`);
78
+ return role;
79
+ }
80
+ function inventoryPath(policy, kind, logicalName) {
81
+ const entry = policy.asset_inventory.find(asset => (asset.kind === kind && (logicalName === undefined || asset.logical_name === logicalName)));
82
+ if (entry === undefined) {
83
+ throw new PolicyCompilationError('asset_missing', `${kind}:${logicalName ?? ''}`);
84
+ }
85
+ return entry.resolved_path;
86
+ }
87
+ /** The directive bytes the role was compiled from, located through the inventory the compiler
88
+ * wrote: `ResolvedAgentRunRole` carries no directive and GT3 forbids widening it. A directive
89
+ * that no longer matches its compiled bytes moves the role hash, which R4 then refuses. */
90
+ export function trialDirective(policy, slot) {
91
+ return fs.readFileSync(inventoryPath(policy, 'prompt', `${slot}:directive`), 'utf8');
92
+ }
93
+ /** C4: role composition is sourced from the policy, never from the disposable projection. */
94
+ export function trialRunOptions(spec) {
95
+ const role = trialRole(spec.policy, spec.slot);
96
+ const key = trialSessionKey(spec.policy);
97
+ return {
98
+ sessionKey: key,
99
+ channel: key,
100
+ profileName: null,
101
+ cwd: spec.cwd,
102
+ awaitBackground: true,
103
+ backgroundWaitPolicy: 'completion-only',
104
+ mcpComposition: role.mcpComposition,
105
+ mcpConfigPaths: role.mcpConfigPaths,
106
+ disableHooks: role.disableHooks,
107
+ streamDeltas: false,
108
+ captureTranscriptLogs: false,
109
+ loadCortexRules: false,
110
+ recordCost: false,
111
+ systemPrompt: role.systemPrompt,
112
+ pluginDirs: role.pluginDirs,
113
+ tools: role.tools.join(','),
114
+ // C2 — one resolved CLI path for both spawn branches.
115
+ cliPath: inventoryPath(spec.policy, 'cli_artifact'),
116
+ // GT4 — the compiled guard travels on the spawn config, never through the projection.
117
+ benchmarkPolicyGuard: trialGuard(spec.policy, spec.slot),
118
+ // C5/C7 and A13 — the child environment is pinned and factory-pure; no ambient parent values enter.
119
+ pinnedEnv: pinnedTrialEnvironment(spec.paths, {}),
120
+ // §5.6 P5 — the instant, not a duration: the child derives its remaining budget when it calls.
121
+ benchmarkDeadlineEpochMs: spec.policy.deadline.absolute_epoch_ms,
122
+ };
123
+ }
124
+ // C6 with §1.7: the child is routed at the per-trial proxy authority, while the identity host stays
125
+ // `model_execution.configured_route_base_host` — the proxy authority feeds no identity hash. No
126
+ // member is taken from the host profile, so the profile's own ANTHROPIC_BASE_URL cannot reach here.
127
+ export function trialAgentConfig(policy, backend) {
128
+ return {
129
+ model: policy.model_execution.requested_model,
130
+ backend,
131
+ mode: null,
132
+ provider: policy.model_execution.provider_protocol,
133
+ // Gate 2 runs one supervised print-mode turn; TUI has no trial surface.
134
+ claudeBackend: 'print',
135
+ thinking: policy.model_execution.reasoning_effort,
136
+ };
137
+ }
138
+ export function createTrialAdapter(spec) {
139
+ const backend = trialBackend(spec.policy);
140
+ const runOptions = trialRunOptions(spec);
141
+ const directive = trialDirective(spec.policy, spec.slot);
142
+ const adapter = ADAPTER_CONSTRUCTORS[backend](spec);
143
+ const spawnConfig = buildAgentSpawnConfig(runOptions, trialAgentConfig(spec.policy, backend), spec.policy.credential.proxy_base_url);
144
+ // P12: the trial is routed at the policy proxy authority with no sub-path, never at the host gateway.
145
+ if (backend === 'pi') {
146
+ spawnConfig.piGatewayPath = '';
147
+ spawnConfig.piGatewayBaseUrl = spec.policy.credential.proxy_base_url;
148
+ }
149
+ spawnConfig.preserveUnreportedAccounting = true;
150
+ const sessionKey = spawnConfig.sessionKey;
151
+ let closed = false;
152
+ return {
153
+ adapter,
154
+ spawnConfig,
155
+ // S7 — all three arguments, so the directive and the guard reach the role hash.
156
+ roleSurface: roleSurfaceFromSpawnConfig(spawnConfig, directive, spawnConfig.benchmarkPolicyGuard),
157
+ backend,
158
+ close: async () => {
159
+ if (closed)
160
+ return;
161
+ closed = true;
162
+ await adapter.close(sessionKey);
163
+ },
164
+ };
165
+ }
@@ -0,0 +1,25 @@
1
+ import type { AgentHandle } from '../../core/types/agent-types.js';
2
+ import type { PinnedTrialPaths } from '../agent-run/pinned-node-process.js';
3
+ import type { ResolvedAgentRunConfig } from '../agent-run/run-config.js';
4
+ import type { RunAgentOptions } from '../agents/spawn-config.js';
5
+ import type { ResolvedTrialPolicy } from './resolved-policy.js';
6
+ import type { LeaseState } from './workspace-lease.js';
7
+ /** Everything a trial fixes for its whole lifetime. What varies per step — the role, the workspace,
8
+ * the resume target and the admission boundary — is read from that step's own run options. */
9
+ export interface TrialThreadAdapterInput {
10
+ policy: ResolvedTrialPolicy;
11
+ config: ResolvedAgentRunConfig;
12
+ paths: PinnedTrialPaths;
13
+ supervisor: {
14
+ binary: string;
15
+ graceMs: number;
16
+ deadlineMs?: number;
17
+ };
18
+ /** The live lease, as a reader. This factory runs once per trial while the closure it returns
19
+ * runs once per step, so a `LeaseState` value member would be read at construction and frozen
20
+ * for the whole thread — the staleness the rule exists to forbid (design section 16 (16.1) LS3). */
21
+ leaseState: () => LeaseState;
22
+ }
23
+ /** The thread runtime's `runAgent`, replaced for the duration of one trial. Each step builds its own
24
+ * adapter in the workspace it was armed in and closes it before the next step is armed. */
25
+ export declare function createBenchmarkTrialRunAgent(input: TrialThreadAdapterInput): (message: string, options?: RunAgentOptions) => AgentHandle;
@@ -0,0 +1,106 @@
1
+ // input: a frozen trial policy, its pinned paths and one thread step's run options
2
+ // output: a per-step trial adapter run whose spawn config is the trial's own
3
+ // pos: Per-step trial adapter route for an in-trial benchmark thread
4
+ // >>> If I am updated, update my header and folder CORTEX.md <<<
5
+ import { runWithAdapter } from '../agents/facade.js';
6
+ import { createTrialAdapter, trialAgentConfig, } from './trial-adapter-factory.js';
7
+ function requireSlot(options) {
8
+ const slot = options.benchmarkAgentSlot;
9
+ if (typeof slot !== 'string' || slot.length === 0) {
10
+ throw new Error('A benchmark thread step names no trial role');
11
+ }
12
+ return slot;
13
+ }
14
+ /** The workspace the step was armed in. The trial adapter fixes its cwd at construction, which is
15
+ * why a step gets its own adapter rather than reusing the previous step's. */
16
+ function requireWorkspace(options) {
17
+ const cwd = options.cwd;
18
+ if (typeof cwd !== 'string' || cwd.length === 0) {
19
+ throw new Error('A benchmark thread step names no workspace');
20
+ }
21
+ return cwd;
22
+ }
23
+ /** One process boundary, so containment and the single-writer rule are enforced by the same check.
24
+ * A step that arrives without one would spawn outside both. */
25
+ function requireSpawner(options) {
26
+ const spawner = options.processSpawner;
27
+ if (typeof spawner !== 'function') {
28
+ throw new Error('A benchmark thread step carries no admission-checking process spawner');
29
+ }
30
+ return spawner;
31
+ }
32
+ /**
33
+ * Take the trial's own prepared spawn config and overlay only what the policy cannot know: the
34
+ * step's resume target and its admission boundary. The alternative — letting the step's options
35
+ * build the config — silently drops every field that exists only inside the trial (its pinned CLI,
36
+ * its pinned environment, its compiled policy guard, its absolute deadline, its MCP config paths)
37
+ * and routes the child at the host gateway instead of the trial's own proxy authority. Neither the
38
+ * type checker nor a green suite reports that, so the direction is chosen to fail loudly instead:
39
+ * a field added to the trial reaches the step by construction, while the overlay stays a closed,
40
+ * enumerable set.
41
+ */
42
+ function stepSpawnConfig(trial, options, leaseState) {
43
+ const spawnConfig = trial.spawnConfig;
44
+ spawnConfig.processSpawner = requireSpawner(options);
45
+ spawnConfig.sessionId = options.sessionId ?? null;
46
+ spawnConfig.resume = !!options.sessionId;
47
+ // Read here and nowhere earlier: the step has been armed, so this is the state it executes under
48
+ // rather than the state the trial started in (design section 16 (16.1) LS3/LS4).
49
+ spawnConfig.benchmarkLeaseState = leaseState();
50
+ return spawnConfig;
51
+ }
52
+ /** A close failure is settlement, not the step's outcome: it may never replace the step's own
53
+ * failure, and it is only surfaced when the step itself succeeded. */
54
+ async function settleAndClose(promise, trial) {
55
+ let result;
56
+ let failed = false;
57
+ let failure;
58
+ try {
59
+ result = await promise;
60
+ }
61
+ catch (error) {
62
+ failed = true;
63
+ failure = error;
64
+ }
65
+ try {
66
+ await trial.close();
67
+ }
68
+ catch (error) {
69
+ if (!failed)
70
+ throw error;
71
+ }
72
+ if (failed)
73
+ throw failure;
74
+ return result;
75
+ }
76
+ function closingHandle(handle, trial) {
77
+ return {
78
+ promise: settleAndClose(handle.promise, trial),
79
+ kill: () => handle.kill(),
80
+ get sessionId() { return handle.sessionId; },
81
+ agentProcess: handle.agentProcess,
82
+ };
83
+ }
84
+ /** The thread runtime's `runAgent`, replaced for the duration of one trial. Each step builds its own
85
+ * adapter in the workspace it was armed in and closes it before the next step is armed. */
86
+ export function createBenchmarkTrialRunAgent(input) {
87
+ return (message, options = {}) => {
88
+ const slot = requireSlot(options);
89
+ const trial = createTrialAdapter({
90
+ policy: input.policy,
91
+ slot,
92
+ config: input.config,
93
+ paths: input.paths,
94
+ supervisor: input.supervisor,
95
+ cwd: requireWorkspace(options),
96
+ });
97
+ try {
98
+ const handle = runWithAdapter(trial.adapter, message, { ...options, preparedSpawnConfig: stepSpawnConfig(trial, options, input.leaseState) }, trialAgentConfig(input.policy, trial.backend), undefined);
99
+ return closingHandle(handle, trial);
100
+ }
101
+ catch (error) {
102
+ void trial.close().catch(() => { });
103
+ throw error;
104
+ }
105
+ };
106
+ }