crysk 0.0.0 → 0.3.1

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 (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
@@ -0,0 +1,1877 @@
1
+ import { homedir } from "node:os";
2
+ import {
3
+ createFreeModelProbe,
4
+ type FreeModelProbe,
5
+ freeVerdictKey,
6
+ } from "#model/free-discovery";
7
+ import type { ProviderCapabilityReport } from "#model/provider-capabilities";
8
+ import {
9
+ type CapabilityGateDecision,
10
+ exactBindingCapabilityGate,
11
+ } from "#model/provider-capabilities";
12
+ import type {
13
+ ResolvedRoutePlan,
14
+ ResolvedStepRoute,
15
+ RoutingConfig,
16
+ } from "#model/routing";
17
+ import { buildResolvedRoutePlan, freezeRoutePlan } from "#model/routing";
18
+ import {
19
+ ClaudeCodeRunner,
20
+ type StepResult,
21
+ type StepRunner,
22
+ type StepSpec,
23
+ } from "#review/step-runner";
24
+ // Production runtime composition (§2 design): frozen route-keyed bindings admit
25
+ // once; MultiProviderRunner acquires a per-step transport lease, delegates
26
+ // lifecycle to StepExecutionHarness, and disposes stream/client/server before
27
+ // credential projection destroy. Registry caches transports by routeFingerprint.
28
+ import type { AttemptAdmissionGate } from "./execution/admission";
29
+ import { deriveBucketId, loadOrCreateBucketKey } from "./execution/bucket-id";
30
+ import type {
31
+ CredentialKind,
32
+ EnvironmentPolicy,
33
+ ExactBindingCapabilityReport,
34
+ IsolationProjection,
35
+ ProviderTransport,
36
+ ResolvedModelRoute,
37
+ RunnerBackend,
38
+ RuntimeBinding,
39
+ RuntimeBindingCredential,
40
+ TransportLease,
41
+ VerifiedExecutable,
42
+ } from "./execution/contracts";
43
+ import { StepExecutionHarness } from "./execution/harness";
44
+ import {
45
+ InMemorySpendLedger,
46
+ type SpendLedger,
47
+ } from "./execution/spend-limiter";
48
+ import {
49
+ type BindingAuthorityResolution,
50
+ credentialKindBillsMetered,
51
+ credentialKindForRoute,
52
+ openCodeCredentialBrokerForKind,
53
+ prepareProductionRunnerAuthority,
54
+ type ResolvedBindingAuthority,
55
+ type ResolveRunnerAuthorityDeps,
56
+ type RunnerAuthorityOptions,
57
+ resolveBindingAuthority,
58
+ withClaudeDiscoveryAllowlist,
59
+ } from "./runner-authority";
60
+ import {
61
+ validateBindingAdmission,
62
+ validateRouteDrift,
63
+ } from "./security/binding-policy";
64
+ import { OPENCODE_OAUTH_PROVIDER } from "./security/credential-broker";
65
+ import { authorizeWorkspaceCwd } from "./security/execution-authority";
66
+ import {
67
+ type AdmitRoutePlanOptions,
68
+ type AdmittedRoutePlanResult,
69
+ admitRoutePlan,
70
+ createDefaultTransportRegistry,
71
+ type D1_11ReadinessEvidence,
72
+ DefaultTransportRegistry,
73
+ readInstalledOpenCodeSdkVersion,
74
+ type TransportFactoryOptions,
75
+ type TransportRegistry,
76
+ } from "./transport-registry";
77
+ import {
78
+ type OpenCodeIdentityObserver,
79
+ type OpenCodeObservedIdentity,
80
+ observeOpenCodeExecutable,
81
+ } from "./transports/opencode-admission";
82
+ import { zeroUsage } from "./usage";
83
+
84
+ export class ProductionRuntimeError extends Error {
85
+ constructor(message: string) {
86
+ super(message);
87
+ this.name = "ProductionRuntimeError";
88
+ }
89
+ }
90
+
91
+ export interface ProductionRuntimeOptions extends RunnerAuthorityOptions {
92
+ readonly plan: ResolvedRoutePlan;
93
+ readonly registry?: TransportRegistry;
94
+ readonly mode?: AdmitRoutePlanOptions["mode"];
95
+ readonly evidence?: Map<RunnerBackend, D1_11ReadinessEvidence>;
96
+ readonly authorityDeps?: ResolveRunnerAuthorityDeps;
97
+ readonly spawnFn?: typeof Bun.spawn;
98
+ readonly observeOpenCodeIdentity?: OpenCodeIdentityObserver;
99
+ readonly signal?: AbortSignal;
100
+ readonly attemptAdmissionGate?: AttemptAdmissionGate;
101
+ readonly graceMarginMs?: number;
102
+ // #182: live free-model verdicts, injected so `bun test` stays offline.
103
+ // When present and an opencode route resolved to `provider_api_token`,
104
+ // `resolveFrozenBindings` asks it about (provider, modelSnapshot) and — on
105
+ // true — swaps the binding to `provider_free` + the free broker. When
106
+ // absent, behaviour is unchanged (no spawn, no upgrade). The same instance
107
+ // must feed the server credential and the bindings (see
108
+ // prepareProductionAdmissionContext) so the two cannot disagree across a
109
+ // provider flip — use `createFreeModelProbe` (memoised per provider/model).
110
+ readonly freeModelProbe?: FreeModelProbe;
111
+ }
112
+
113
+ export interface ProductionRuntime {
114
+ readonly runner: StepRunner;
115
+ readonly registry: TransportRegistry;
116
+ readonly bindings: ReadonlyMap<string, RuntimeBinding>;
117
+ readonly admitted: AdmittedRoutePlanResult;
118
+ // The D1-11 evidence this runtime was admitted with, echoed back verbatim.
119
+ // admitRoutePlan reads evidence ONLY from its own options and never from the
120
+ // registry, so a later admission (the pipeline's pre-confirm gate) has no way
121
+ // to recover it from `registry` alone — it has to be carried.
122
+ readonly evidence?: Map<RunnerBackend, D1_11ReadinessEvidence>;
123
+ dispose(): Promise<void>;
124
+ }
125
+
126
+ interface ActiveTransportLeaseTracker {
127
+ register(routeKey: string): void;
128
+ /** Returns true when the last active lease for this routeKey was released. */
129
+ unregister(routeKey: string): boolean;
130
+ activeCount(routeKey: string): number;
131
+ teardownTransportIfLast(input: {
132
+ routeKey: string;
133
+ transport: ProviderTransport;
134
+ }): Promise<void>;
135
+ endLease(input: {
136
+ routeKey: string;
137
+ registry: { release?(routeFingerprint: string): void };
138
+ }): Promise<void>;
139
+ releaseAll(registry: { release?(routeFingerprint: string): void }): void;
140
+ }
141
+
142
+ class DefaultActiveTransportLeaseTracker
143
+ implements ActiveTransportLeaseTracker
144
+ {
145
+ private readonly refcounts = new Map<string, number>();
146
+ private readonly gates = new Map<string, Promise<void>>();
147
+
148
+ register(routeKey: string): void {
149
+ this.refcounts.set(routeKey, (this.refcounts.get(routeKey) ?? 0) + 1);
150
+ }
151
+
152
+ unregister(routeKey: string): boolean {
153
+ const current = this.refcounts.get(routeKey) ?? 0;
154
+ if (current <= 1) {
155
+ this.refcounts.delete(routeKey);
156
+ return true;
157
+ }
158
+ this.refcounts.set(routeKey, current - 1);
159
+ return false;
160
+ }
161
+
162
+ activeCount(routeKey: string): number {
163
+ return this.refcounts.get(routeKey) ?? 0;
164
+ }
165
+
166
+ async teardownTransportIfLast(input: {
167
+ routeKey: string;
168
+ transport: ProviderTransport;
169
+ }): Promise<void> {
170
+ await this.exclusive(input.routeKey, async () => {
171
+ if (this.activeCount(input.routeKey) !== 1) {
172
+ return;
173
+ }
174
+ if (
175
+ "dispose" in input.transport &&
176
+ typeof input.transport.dispose === "function"
177
+ ) {
178
+ await (input.transport as { dispose(): Promise<void> }).dispose();
179
+ }
180
+ });
181
+ }
182
+
183
+ async endLease(input: {
184
+ routeKey: string;
185
+ registry: { release?(routeFingerprint: string): void };
186
+ }): Promise<void> {
187
+ await this.exclusive(input.routeKey, async () => {
188
+ if (this.unregister(input.routeKey)) {
189
+ input.registry.release?.(input.routeKey);
190
+ }
191
+ });
192
+ }
193
+
194
+ releaseAll(registry: { release?(routeFingerprint: string): void }): void {
195
+ for (const routeKey of [...this.refcounts.keys()]) {
196
+ registry.release?.(routeKey);
197
+ }
198
+ this.refcounts.clear();
199
+ }
200
+
201
+ private async exclusive<T>(
202
+ routeKey: string,
203
+ fn: () => Promise<T>,
204
+ ): Promise<T> {
205
+ const previous = this.gates.get(routeKey) ?? Promise.resolve();
206
+ let releaseGate!: () => void;
207
+ const gate = new Promise<void>((resolve) => {
208
+ releaseGate = resolve;
209
+ });
210
+ this.gates.set(
211
+ routeKey,
212
+ previous.then(() => gate),
213
+ );
214
+ await previous;
215
+ try {
216
+ return await fn();
217
+ } finally {
218
+ releaseGate();
219
+ }
220
+ }
221
+ }
222
+
223
+ interface FrozenRuntimeBindingOptions {
224
+ readonly observedOpenCodeIdentity?: OpenCodeObservedIdentity;
225
+ readonly key: string;
226
+ readonly route: ResolvedModelRoute;
227
+ readonly authority: ResolvedBindingAuthority;
228
+ readonly executable: VerifiedExecutable;
229
+ readonly credential: RuntimeBindingCredential;
230
+ readonly getCapabilityReport: (
231
+ backend: RunnerBackend,
232
+ ) => Promise<ProviderCapabilityReport>;
233
+ readonly leaseTracker: ActiveTransportLeaseTracker;
234
+ }
235
+
236
+ function minimalIsolationFromExecutable(
237
+ executable: VerifiedExecutable,
238
+ ): IsolationProjection {
239
+ return {
240
+ credentialProjectionId: "production-binding",
241
+ env: {},
242
+ syntheticHome: "",
243
+ syntheticConfigHome: "",
244
+ syntheticTmp: "",
245
+ verifiedBinaryPath: executable.verifiedExecutionPath,
246
+ };
247
+ }
248
+
249
+ class FrozenRuntimeBinding implements RuntimeBinding {
250
+ readonly observedOpenCodeIdentity?: OpenCodeObservedIdentity;
251
+ readonly key: string;
252
+ readonly route: ResolvedModelRoute;
253
+ readonly executable: VerifiedExecutable;
254
+ readonly credential: RuntimeBindingCredential;
255
+ readonly environment: EnvironmentPolicy;
256
+ readonly tools = Object.freeze({
257
+ allowMapOnly: true,
258
+ deniedTools: Object.freeze(["bash", "Write", "Edit", "Task"]),
259
+ });
260
+ readonly mcp = Object.freeze({
261
+ codegraphOnly: true,
262
+ verifiedConfigRequired: true,
263
+ });
264
+
265
+ private readonly authority: ResolvedBindingAuthority;
266
+ private readonly getCapabilityReport: (
267
+ backend: RunnerBackend,
268
+ ) => Promise<ProviderCapabilityReport>;
269
+ private readonly leaseTracker: ActiveTransportLeaseTracker;
270
+
271
+ constructor(options: FrozenRuntimeBindingOptions) {
272
+ this.key = options.key;
273
+ this.observedOpenCodeIdentity =
274
+ options.observedOpenCodeIdentity === undefined
275
+ ? undefined
276
+ : Object.freeze({ ...options.observedOpenCodeIdentity });
277
+ this.route = Object.freeze({ ...options.route });
278
+ this.executable = Object.freeze({ ...options.executable });
279
+ this.credential = Object.freeze({ ...options.credential });
280
+ // `syntheticHome` answers ONE question: "is a credential broker
281
+ // configured for this binding?" — not "did this step's harness run get
282
+ // a fresh per-step projection from it." Those coincided for claude-code
283
+ // (the only consumer, until OpenCode existed). They stopped coinciding
284
+ // for OpenCode: since #149 this broker (`OpenCodeAuthBroker` /
285
+ // `OpenCodeFreeBroker`, runner-authority.ts) protects the SERVER's one
286
+ // lifetime projection, and since #150 `StepExecutionHarness.run`
287
+ // deliberately never calls it per step for this backend
288
+ // (`OpenCodeSdkTransport.credentialProjection === "server-lifetime"`,
289
+ // contracts.ts/opencode-sdk.ts) because nothing downstream would read
290
+ // that per-step result. `syntheticHome: true` stays an accurate claim
291
+ // either way — broker authority IS configured and IS what protects the
292
+ // inference — it just protects it at server scope, not step scope, for
293
+ // this backend.
294
+ this.environment = Object.freeze({
295
+ syntheticHome: options.credential.broker !== undefined,
296
+ workspaceReadBroker: true,
297
+ });
298
+ this.authority = options.authority;
299
+ this.getCapabilityReport = options.getCapabilityReport;
300
+ this.leaseTracker = options.leaseTracker;
301
+ Object.freeze(this);
302
+ }
303
+
304
+ async capabilities(): Promise<ExactBindingCapabilityReport> {
305
+ const report = await this.getCapabilityReport(this.route.backend);
306
+ // "Broker configured", not "per-step projection actually taken" — see
307
+ // the WHY comment on `this.environment` above (#149/#150: for OpenCode
308
+ // this broker protects the server's lifetime projection, and the
309
+ // harness now skips the per-step call this flag used to imply).
310
+ const projectionBrokered = this.credential.broker !== undefined;
311
+ const sdkAvailable =
312
+ this.route.backend === "claude-code" ||
313
+ !report.issues.some(
314
+ (issue) => issue.code === "real_sdk_adapter_deferred_to_d1_11",
315
+ );
316
+ // #133. ONE effective billing mode, computed once and fed to all THREE
317
+ // readers below (`pricingApplicable`, `billingMode`,
318
+ // `cashCostAccountingValid`). They used to read `report.billing.mode`
319
+ // independently, and that is precisely the trap: upgrading only
320
+ // `billingMode` would leave `pricingApplicability` at "not_applicable",
321
+ // the pricing gate would never fire, and a metered route would be
322
+ // admitted as priced-not-required — executing on real spend while
323
+ // reporting `cashCostUsd: 0`. Under-reporting is the failure this whole
324
+ // issue exists to prevent, so the correction has to be applied ONCE,
325
+ // upstream of every consumer, not per-expression.
326
+ //
327
+ // The legacy backend-wide report cannot know this: it is produced before
328
+ // any route resolves, so it cannot see the provider. The credential KIND
329
+ // can — `provider_api_token` IS a metered API token by definition
330
+ // (runner-authority.ts credentialKindForRoute).
331
+ //
332
+ // 2026-09-02: that "by definition" moved into `credentialKindBillsMetered`
333
+ // rather than staying an inline comparison, because a SECOND caller
334
+ // appeared — the OpenCode transport factory, which stamps the same
335
+ // billing mode onto every usage record so the report and the records
336
+ // cannot disagree about one attempt. Two copies of the rule would be two
337
+ // chances for exactly that disagreement.
338
+ //
339
+ // UPGRADE ONLY, never downgrade. An OAuth or subscription kind keeps
340
+ // whatever the transport reported, `unknown` included — which is what
341
+ // keeps the narrowing guarantee below true for every other kind.
342
+ const effectiveBillingMode: ProviderCapabilityReport["billing"]["mode"] =
343
+ credentialKindBillsMetered(this.credential.kind)
344
+ ? "metered"
345
+ : report.billing.mode;
346
+ const pricingApplicable =
347
+ effectiveBillingMode === "metered" ? "required" : "not_applicable";
348
+ // The legacy report carries THREE billing modes (subscription | metered |
349
+ // unknown) and the exact contract carries two, so `unknown` narrows into
350
+ // "subscription" here. WHY that narrowing is not a lie: it is sound ONLY
351
+ // because `cashCostAccountingValid` below reads the three-state
352
+ // `effectiveBillingMode` and independently blocks `unknown` — the design
353
+ // doc makes `billingMode: "unknown"` a blocking preflight result
354
+ // (docs/multi-runtime-model-diversity-design.md:461), and the pricing
355
+ // gate cannot enforce it because `unknown` is not `metered`, leaving
356
+ // pricingApplicability at "not_applicable". Delete or weaken the
357
+ // cash-cost derivation and this narrowing silently starts claiming that
358
+ // an unknown-billing route bills like a subscription.
359
+ //
360
+ // #133 keeps that intact: the effective mode only ever REPLACES `unknown`
361
+ // with `metered`, and a metered route is caught by the pricing gate
362
+ // instead. Nothing reaches "subscription" that did not already.
363
+ const billingMode: ExactBindingCapabilityReport["billing"]["mode"] =
364
+ effectiveBillingMode === "metered" ? "metered" : "subscription";
365
+ // #197. ONE source, and it is the transport's own claim. This used to be
366
+ // a disjunction — the transport's `pricingReady` OR a bundled per-model
367
+ // rate table selected by `this.route.provider` — and the table half is
368
+ // deleted, along with the loader, the 90-day freshness window and the
369
+ // `config/models/*-pricing.json` files behind it.
370
+ //
371
+ // WHY the table lost, given the design line (§8 line 461) names "provider
372
+ // cost or a versioned rate table": our table was a hand-transcribed
373
+ // snapshot of the same published LIST prices the transports report, and
374
+ // it aged on our release cadence rather than the tool's. It expired after
375
+ // 90 days and REFUSED the route it was meant to enable, it covered only
376
+ // what someone remembered to transcribe (the zai table priced 11 of the
377
+ // 16 models `opencode models` reports, five days after it landed), and a
378
+ // new model was absent until noticed. The transports report a live figure
379
+ // for whatever they actually ran.
380
+ //
381
+ // Both backends now answer for themselves: OpenCode reads a non-optional
382
+ // `cost` off every assistant message, and the Claude CLI reports
383
+ // `total_cost_usd` (#197 flipped that flag). A transport that reports NO
384
+ // cost is refused — which is the gate's whole purpose, unchanged: refuse
385
+ // to bill an unknown amount. What moved is where the unknown is answered.
386
+ // A missing figure is now caught at SETTLEMENT, where the answer is
387
+ // actually known (`settlementFromUsage`, spend-limiter.ts: complete usage
388
+ // with no cash cost settles `unresolved`, never 0), instead of being
389
+ // guessed at admission from a table that might be stale.
390
+ const tokenPricingAvailable = report.billing.pricingReady;
391
+ // Spec (same design line): subscription OAuth may truthfully report
392
+ // `cashCostUsd: 0`; metered routes require a cost source; unknown is
393
+ // blocking. Read off `tokenPricingAvailable` rather than the raw flag so
394
+ // the two cannot drift — a metered report claiming
395
+ // priced-but-not-accountable is self-contradictory and would strand the
396
+ // route in a gate that no longer has a reason to refuse it.
397
+ const cashCostAccountingValid =
398
+ effectiveBillingMode === "subscription"
399
+ ? true
400
+ : effectiveBillingMode === "metered"
401
+ ? tokenPricingAvailable
402
+ : false;
403
+ return {
404
+ routeKey: this.key,
405
+ backend: this.route.backend,
406
+ sdk: { available: sdkAvailable },
407
+ binary: {
408
+ resolved: true,
409
+ absolutePath: this.executable.absolutePath,
410
+ sha256: this.executable.sha256,
411
+ },
412
+ auth: {
413
+ // #182 SCOPE NOTE (b): the transport's backend-wide report hardcodes
414
+ // `kind: "opencode_chatgpt_oauth"` (src/transports/opencode-sdk.ts:389)
415
+ // because it is produced before any route resolves and cannot see the
416
+ // provider — let alone the model the free verdict needs. A free route
417
+ // never observes it: the exact binding overwrites kind with
418
+ // `this.credential.kind` here, so backend-wide stays a fallback for
419
+ // kind-less callers and per-route truth lives on the binding.
420
+ kind: this.credential.kind,
421
+ projectionReady: projectionBrokered,
422
+ probe: projectionBrokered ? report.auth.probe : "not_run",
423
+ },
424
+ environment: {
425
+ // Same "broker configured" meaning as `projectionBrokered` above,
426
+ // not "this step got its own projection" — see the #149/#150 WHY
427
+ // comment on `this.environment` in the constructor.
428
+ syntheticHome: projectionBrokered,
429
+ enumeratedPassthrough: !projectionBrokered,
430
+ },
431
+ isolation: {
432
+ workspaceReadBroker: report.isolation.workspaceReadBroker,
433
+ codegraphPolicy: report.isolation.codegraphPolicy,
434
+ },
435
+ toolsMcp: {
436
+ allowMapEnforced: this.tools.allowMapOnly,
437
+ mcpIntegrityChecked: this.mcp.verifiedConfigRequired,
438
+ },
439
+ protocol: {
440
+ terminalProof: report.protocol.terminalProof,
441
+ boundedEvents: report.protocol.boundedEvents,
442
+ usageMode: report.protocol.usageMode,
443
+ },
444
+ usage: { normalized: true },
445
+ billing: {
446
+ mode: billingMode,
447
+ pricingApplicability: pricingApplicable,
448
+ tokenPricingAvailable,
449
+ cashCostAccountingValid,
450
+ },
451
+ };
452
+ }
453
+
454
+ async acquire(
455
+ _isolation: IsolationProjection,
456
+ registry: {
457
+ get(
458
+ backend: RunnerBackend,
459
+ options?: TransportFactoryOptions,
460
+ ): ProviderTransport;
461
+ release?(routeFingerprint: string): void;
462
+ },
463
+ ): Promise<TransportLease> {
464
+ const transport = registry.get(this.route.backend, {
465
+ routeFingerprint: this.key,
466
+ route: this.route,
467
+ // 2026-09-02: the SAME field `capabilities()` derives
468
+ // `effectiveBillingMode` from, handed to the transport factory that
469
+ // derives `usageBillingMode`. One fact, one source — because it was two,
470
+ // and two derivations of one fact diverge in silence (#149's "two
471
+ // brokers", identical shape).
472
+ //
473
+ // `this.credential.kind` is authoritative and the factory's own
474
+ // `merged.credentialKind` is not: this kind was resolved BY THIS ROUTE
475
+ // through `resolveBindingAuthority` -> `credentialKindForRoute(backend,
476
+ // provider)`, while the factory could only ever read a registry-wide
477
+ // default fixed at construction. `productionFallbackRegistry` is the
478
+ // ONLY wiring that sets that default, and it runs only for a caller
479
+ // that supplies no registry — so the public `createProductionRuntime`,
480
+ // which accepts an arbitrary `options.registry`, bypassed it entirely
481
+ // and the factory silently fell back to "subscription" on a metered
482
+ // route. That stamp is what `settlementFromUsage`'s metered-zero rule
483
+ // keys on, so the fallback made the rule DEAD: an unaccountable
484
+ // provider $0 settled as a truthful cost instead of fencing the bucket.
485
+ // (`collectDoctorExactBindingReports` supplies its own kind-less
486
+ // registry too, but it only ever calls `capabilities()` — no attempt,
487
+ // so no usage record, so nothing there could observe the divergence.
488
+ // Being unobservable is what let it ship.)
489
+ //
490
+ // Required on `RuntimeBindingCredential`, so it is forwarded
491
+ // unconditionally rather than through a conditional spread — and
492
+ // `get()` merges `{ ...defaultOptions, ...options }`, so this wins over
493
+ // the construction-time default rather than being shadowed by it. That
494
+ // default survives as the fallback for callers holding no binding.
495
+ credentialKind: this.credential.kind,
496
+ ...(this.route.backend === "opencode"
497
+ ? {
498
+ openCodeBinaryPath: this.executable.absolutePath,
499
+ observedOpenCodeIdentity: this.observedOpenCodeIdentity,
500
+ }
501
+ : {}),
502
+ });
503
+ const routeKey = this.key;
504
+ this.leaseTracker.register(routeKey);
505
+ return {
506
+ transport,
507
+ dispose: async () => {
508
+ await this.leaseTracker.endLease({ routeKey, registry });
509
+ },
510
+ };
511
+ }
512
+ }
513
+
514
+ function toVerifiedExecutable(
515
+ authority: ResolvedBindingAuthority,
516
+ ): VerifiedExecutable {
517
+ const entry = authority.executableAllowlist[0];
518
+ return {
519
+ absolutePath: entry.absolutePath,
520
+ sha256: entry.sha256,
521
+ verifiedExecutionPath: authority.binaryPath,
522
+ };
523
+ }
524
+
525
+ function uniqueRoutesByFingerprint(
526
+ plan: ResolvedRoutePlan,
527
+ ): readonly ResolvedStepRoute[] {
528
+ const seen = new Map<string, ResolvedStepRoute>();
529
+ for (const step of plan.steps) {
530
+ if (!seen.has(step.routeFingerprint)) {
531
+ seen.set(step.routeFingerprint, step);
532
+ }
533
+ }
534
+ return [...seen.values()];
535
+ }
536
+
537
+ function bindingBucketId(
538
+ authority: ResolvedBindingAuthority,
539
+ route: ResolvedModelRoute,
540
+ ): string {
541
+ const localKey = loadOrCreateBucketKey(homedir());
542
+ return deriveBucketId(
543
+ {
544
+ provider: route.provider,
545
+ credentialFingerprint: `${authority.credentialKind}:${authority.credentialRef}`,
546
+ },
547
+ localKey,
548
+ );
549
+ }
550
+
551
+ // #279: the bucket a METERED claude-code binding of this SAME
552
+ // provider+credentialRef would compute — `bindingBucketId` above, with the
553
+ // credential kind hardcoded to `provider_api_token` instead of read off
554
+ // `binding.credential.kind`. Used ONLY to fence the one attempt whose
555
+ // Keychain projection degraded onto an ambient key/token (StepExecution-
556
+ // Harness's `degradedProjectionBucketId`), never as `rateLimitBucketId`
557
+ // itself — that stays the binding's OWN bucket, keyed on its REAL
558
+ // `credentialKind` (subscription), so a normal, non-degraded subscription
559
+ // attempt keeps landing where it always did.
560
+ //
561
+ // WHY a different bucket than the binding's own: the ledger's guarantee is
562
+ // "an unresolved bucket blocks the NEXT paid attempt of the SAME
563
+ // credential" (spend-limiter.ts). The credential that pays for a degraded
564
+ // attempt is the ambient API key/token, not the subscription OAuth record
565
+ // this binding otherwise authenticates with — those are two different
566
+ // credentials that happen to share one route. Fencing the subscription
567
+ // bucket here would block the next NON-degraded subscription attempt on
568
+ // this same route over dollars the OAuth credential never spent (and would
569
+ // widen the harness's own reservesSpend=false invariant: "a subscription
570
+ // binding reserves nothing" — production-runtime.test.ts). Fencing this
571
+ // mirrored bucket instead lands on the SAME identity a real metered
572
+ // claude-code binding of this provider+credentialRef would use (see
573
+ // `credentialKindForRoute`, runner-authority.ts — hasBroker=false is what
574
+ // produces `provider_api_token` for claude-code), so a later real metered
575
+ // attempt on the same credential is correctly refused too.
576
+ //
577
+ // Takes the provider + credentialRef directly rather than a
578
+ // `ResolvedBindingAuthority` (unlike `bindingBucketId` above): the ONE call
579
+ // site (`MultiProviderRunner.run`) only has the public `RuntimeBinding`,
580
+ // whose `credential.ref` already carries the same value `authority.
581
+ // credentialRef` would.
582
+ function degradedMeteredBucketId(
583
+ provider: string,
584
+ credentialRef: string,
585
+ ): string {
586
+ const localKey = loadOrCreateBucketKey(homedir());
587
+ return deriveBucketId(
588
+ {
589
+ provider,
590
+ credentialFingerprint: `provider_api_token:${credentialRef}`,
591
+ },
592
+ localKey,
593
+ );
594
+ }
595
+
596
+ async function resolveFrozenBindings(
597
+ plan: ResolvedRoutePlan,
598
+ options: ProductionRuntimeOptions,
599
+ registry: TransportRegistry,
600
+ leaseTracker: ActiveTransportLeaseTracker,
601
+ ): Promise<Map<string, RuntimeBinding>> {
602
+ const bindings = new Map<string, RuntimeBinding>();
603
+ const deps = options.authorityDeps ?? {};
604
+ // #182: one verdict per (provider, model), shared across every binding in
605
+ // this resolution — the same cache the admission passes down, so the server
606
+ // credential and the bindings cannot disagree across two spawns.
607
+ const observations = new Map<string, Promise<OpenCodeObservedIdentity>>();
608
+ const freeVerdicts = new Map<string, Promise<boolean>>();
609
+ const probeFree = async (
610
+ provider: string,
611
+ model: string,
612
+ ): Promise<boolean> => {
613
+ const probe = options.freeModelProbe;
614
+ if (probe === undefined) return false;
615
+ // WHY freeVerdictKey, not `${provider}/${model}`: model ids may contain
616
+ // "/" (model/free-discovery.ts header test), so the join collides
617
+ // ("a","b/c") vs ("a/b","c") — one verdict for two models.
618
+ const key = freeVerdictKey(provider, model);
619
+ const cached = freeVerdicts.get(key);
620
+ if (cached !== undefined) return cached;
621
+ const verdict = (async () => {
622
+ try {
623
+ return await probe(provider, model);
624
+ } catch {
625
+ // Fail closed: a throwing probe is an unknown price, not a free one.
626
+ return false;
627
+ }
628
+ })();
629
+ freeVerdicts.set(key, verdict);
630
+ return verdict;
631
+ };
632
+
633
+ for (const step of uniqueRoutesByFingerprint(plan)) {
634
+ const authorityResult = await resolveBindingAuthority(
635
+ step.route.backend,
636
+ // #133: the provider was in scope here all along and was dropped. It is
637
+ // what decides the credential kind, and through it the billing mode.
638
+ step.route.provider,
639
+ options,
640
+ deps,
641
+ );
642
+ if (
643
+ authorityResult.error !== undefined ||
644
+ authorityResult.binding === undefined
645
+ ) {
646
+ throw new ProductionRuntimeError(
647
+ `binding authority unavailable for route ${step.routeFingerprint}: ${authorityResult.error}`,
648
+ );
649
+ }
650
+
651
+ // #182: the free verdict needs (provider, modelSnapshot), and this is the
652
+ // one place the route is in scope — `resolveBindingAuthority` only
653
+ // receives the provider. When the authority resolved metered and the
654
+ // live probe says free, swap in kind `provider_free` + the free broker
655
+ // (selected via the kind-based selector, never a second kind derivation).
656
+ // Fail closed: any probe failure keeps the metered kind.
657
+ let authority = authorityResult.binding;
658
+ if (
659
+ step.route.backend === "opencode" &&
660
+ authority.credentialKind === "provider_api_token" &&
661
+ options.freeModelProbe !== undefined
662
+ ) {
663
+ const free = await probeFree(
664
+ step.route.provider,
665
+ step.route.modelSnapshot,
666
+ );
667
+ if (free) {
668
+ const freeBroker =
669
+ options.credentialBrokers?.opencode ??
670
+ openCodeCredentialBrokerForKind("provider_free", step.route.provider);
671
+ authority = {
672
+ ...authority,
673
+ credentialKind: "provider_free",
674
+ credentialBroker: freeBroker,
675
+ };
676
+ }
677
+ }
678
+ const executable = toVerifiedExecutable(authority);
679
+ let observedOpenCodeIdentity: OpenCodeObservedIdentity | undefined;
680
+ if (step.route.backend === "opencode") {
681
+ const key = JSON.stringify([executable.absolutePath, executable.sha256]);
682
+ let observation = observations.get(key);
683
+ if (observation === undefined) {
684
+ observation = options.observeOpenCodeIdentity
685
+ ? options.observeOpenCodeIdentity(executable, options.signal)
686
+ : observeOpenCodeExecutable(executable, options.signal, {
687
+ sdkVersion: readInstalledOpenCodeSdkVersion,
688
+ });
689
+ observations.set(key, observation);
690
+ }
691
+ observedOpenCodeIdentity = await observation;
692
+ if (
693
+ observedOpenCodeIdentity.executablePath !== executable.absolutePath ||
694
+ observedOpenCodeIdentity.executableSha256 !== executable.sha256
695
+ ) {
696
+ throw new ProductionRuntimeError(
697
+ "Observed OpenCode executable identity differs from frozen binding",
698
+ );
699
+ }
700
+ }
701
+ const binding = new FrozenRuntimeBinding({
702
+ observedOpenCodeIdentity,
703
+ key: step.routeFingerprint,
704
+ route: step.route,
705
+ authority,
706
+ executable,
707
+ credential: {
708
+ kind: authority.credentialKind,
709
+ ref: authority.credentialRef,
710
+ ...(authority.credentialBroker
711
+ ? { broker: authority.credentialBroker }
712
+ : {}),
713
+ bucketId: bindingBucketId(authority, step.route),
714
+ },
715
+ getCapabilityReport: (backend) =>
716
+ registry.getCapabilityReport(backend, {
717
+ mode: options.mode,
718
+ evidence: options.evidence,
719
+ binaryPath: authority.binaryPath,
720
+ observedOpenCodeIdentity,
721
+ }),
722
+ leaseTracker,
723
+ });
724
+ bindings.set(step.routeFingerprint, binding);
725
+ Object.freeze(binding);
726
+ }
727
+
728
+ return bindings;
729
+ }
730
+
731
+ export interface BindingsCapabilityGateResult {
732
+ readonly decision: CapabilityGateDecision;
733
+ readonly reports: readonly ExactBindingCapabilityReport[];
734
+ }
735
+
736
+ // SUGGESTION-1: `capabilities()` is deliberately NOT memoised — it re-probes
737
+ // on every call — so the reports gathered here are the expensive artifact,
738
+ // not a by-product to throw away. They are returned so a caller that needs
739
+ // both the gate decision and the facts (doctor) pays ONE probe pass.
740
+ // WHY this no longer short-circuits on the first blocking binding: doctor
741
+ // reports on every binding regardless of the decision, so stopping early
742
+ // would hand it a truncated view of the plan. The extra probes are bounded
743
+ // by plan size and only occur on the already-failing path.
744
+ export async function gateBindingsCapabilities(
745
+ bindings: ReadonlyMap<string, RuntimeBinding>,
746
+ ): Promise<BindingsCapabilityGateResult> {
747
+ const reports: ExactBindingCapabilityReport[] = [];
748
+ for (const binding of bindings.values()) {
749
+ reports.push(await binding.capabilities());
750
+ }
751
+ const failed = reports
752
+ .map((report) => exactBindingCapabilityGate(report))
753
+ .find((gate) => !gate.ok);
754
+ return { decision: failed ?? { ok: true }, reports };
755
+ }
756
+
757
+ export interface ProbeBindingsReadinessResult {
758
+ readonly decision: CapabilityGateDecision;
759
+ // The exact reports the decision was taken on, in binding order. Consumers
760
+ // must reuse these instead of re-calling `capabilities()`.
761
+ readonly reports: readonly ExactBindingCapabilityReport[];
762
+ readonly bindings: ReadonlyMap<string, RuntimeBinding>;
763
+ readonly registry: TransportRegistry;
764
+ dispose(): Promise<void>;
765
+ }
766
+
767
+ export async function probeBindingsReadiness(
768
+ options: ProductionRuntimeOptions,
769
+ ): Promise<ProbeBindingsReadinessResult> {
770
+ const workspaceAuth = authorizeWorkspaceCwd(
771
+ options.workspaceRoot,
772
+ options.workspaceRoot,
773
+ );
774
+ if (!workspaceAuth.approved) {
775
+ throw new ProductionRuntimeError(
776
+ `workspace root denied before binding probe: ${workspaceAuth.reason}`,
777
+ );
778
+ }
779
+
780
+ const plan = freezeRoutePlan(options.plan);
781
+ const registry = options.registry ?? productionFallbackRegistry(options);
782
+ const leaseTracker = new DefaultActiveTransportLeaseTracker();
783
+ const bindings = await resolveFrozenBindings(
784
+ plan,
785
+ options,
786
+ registry,
787
+ leaseTracker,
788
+ );
789
+ const { decision, reports } = await gateBindingsCapabilities(bindings);
790
+ return {
791
+ decision,
792
+ reports,
793
+ bindings,
794
+ registry,
795
+ dispose: async () => {
796
+ leaseTracker.releaseAll(registry);
797
+ },
798
+ };
799
+ }
800
+
801
+ export function buildDoctorRoutePlan(
802
+ routingConfig?: RoutingConfig,
803
+ ): ResolvedRoutePlan {
804
+ return buildResolvedRoutePlan({
805
+ agents: [
806
+ { key: "reliability", role: "hunter", model: "sonnet" },
807
+ { key: "refuter", role: "refuter", model: "opus" },
808
+ ],
809
+ ...(routingConfig === undefined ? {} : { routingConfig }),
810
+ });
811
+ }
812
+
813
+ export async function collectDoctorExactBindingReports(input: {
814
+ readonly workspaceRoot: string;
815
+ readonly routingConfig?: RoutingConfig;
816
+ readonly authorityDeps?: ResolveRunnerAuthorityDeps;
817
+ readonly env?: RunnerAuthorityOptions["env"];
818
+ readonly observeOpenCodeIdentity?: OpenCodeIdentityObserver;
819
+ readonly loadSdk?: () => Promise<
820
+ import("./transports/opencode-client").OpenCodeSdkLike
821
+ >;
822
+ }): Promise<readonly ExactBindingCapabilityReport[]> {
823
+ const plan = buildDoctorRoutePlan(input.routingConfig);
824
+ const authority = await prepareProductionRunnerAuthority(
825
+ input.workspaceRoot,
826
+ plan,
827
+ input.authorityDeps,
828
+ input.env === undefined ? {} : { env: input.env },
829
+ );
830
+ if ("error" in authority) {
831
+ throw new Error(authority.error);
832
+ }
833
+ // WHY the conformance mode is unconditional, and why `mode` is repeated on
834
+ // BOTH the probe options and the registry: this diagnostic is the phase that
835
+ // PRODUCES D1-11 readiness evidence, so gating it on that evidence can only
836
+ // ever fail. It used to be split into two disagreeing branches — a
837
+ // conformance registry when a test injected `loadSdk`, nothing at all
838
+ // otherwise — and the injected branch was the only one any test exercised.
839
+ // The real doctor/wizard path therefore reached the OpenCode transport
840
+ // factory with no mode, which defaults to "production", and every OpenCode
841
+ // route came back blocking. Passing `mode` here too is not redundant:
842
+ // resolveFrozenBindings forwards `mode: options.mode` on every capability
843
+ // call, and an explicit `undefined` key overrides the registry's default
844
+ // through the factory's `{ ...defaultOptions, ...opts }` spread.
845
+ const probe = await probeBindingsReadiness({
846
+ ...authority,
847
+ plan,
848
+ observeOpenCodeIdentity: input.observeOpenCodeIdentity,
849
+ workspaceRoot: input.workspaceRoot,
850
+ authorityDeps: input.authorityDeps,
851
+ mode: "conformance",
852
+ registry: createDefaultTransportRegistry({
853
+ mode: "conformance",
854
+ env: authority.env,
855
+ ...(input.loadSdk === undefined ? {} : { loadSdk: input.loadSdk }),
856
+ }),
857
+ });
858
+ try {
859
+ // SUGGESTION-1: the readiness probe already called capabilities() once
860
+ // per binding to reach its decision. capabilities() re-probes on every
861
+ // call, so re-collecting here would double the probe cost for a doctor
862
+ // run that needs exactly the reports the gate already produced.
863
+ return probe.reports;
864
+ } finally {
865
+ await probe.dispose();
866
+ }
867
+ }
868
+
869
+ export function d1_11EvidenceFromExactBinding(
870
+ report: ExactBindingCapabilityReport,
871
+ sdkAvailable = report.sdk.available,
872
+ ): D1_11ReadinessEvidence {
873
+ return {
874
+ sdkAvailable,
875
+ credentialAuthority:
876
+ report.auth.projectionReady || report.auth.probe === "passed",
877
+ workspaceBroker: report.isolation.workspaceReadBroker,
878
+ pricingReady:
879
+ report.billing.pricingApplicability !== "required" ||
880
+ report.billing.tokenPricingAvailable,
881
+ };
882
+ }
883
+
884
+ export interface ProductionAdmissionContext {
885
+ readonly registry: DefaultTransportRegistry;
886
+ readonly authorityOptions: RunnerAuthorityOptions;
887
+ readonly evidence: Map<RunnerBackend, D1_11ReadinessEvidence>;
888
+ // #182: the memoised probe this admission decided the server credential
889
+ // with. A caller building a runtime from this admission should forward the
890
+ // SAME instance so bindings reuse its verdicts instead of re-spawning.
891
+ readonly freeModelProbe?: FreeModelProbe;
892
+ }
893
+
894
+ // #133. The OpenCode server is ONE per backend and outlives every step, so
895
+ // the credential it launches under is a whole-plan fact, not a per-step one.
896
+ // A plan mixing an `openai` OAuth route with a `zai` API-token route would
897
+ // need two credentials behind one server; until a server-per-credential
898
+ // exists, that plan is REFUSED here by name rather than silently served
899
+ // whichever provider happened to be resolved last.
900
+ //
901
+ // Returns the sole provider and the kind it resolves to. The BROKER is not
902
+ // built here — `openCodeCredentialBrokerForKind` (runner-authority.ts) owns that
903
+ // pairing for both this site and binding resolution, because two copies of it
904
+ // would be two chances to hand a route a broker that refuses its kind.
905
+ //
906
+ // #182: provider-level only — it cannot see modelSnapshot, so a free MODEL
907
+ // verdict is resolved async in prepareProductionAdmissionContext (which has
908
+ // the route in scope) and upgrades this result. See there.
909
+ export function soleOpenCodeCredential(plan: ResolvedRoutePlan):
910
+ | {
911
+ readonly kind: CredentialKind;
912
+ readonly provider: string;
913
+ readonly error?: undefined;
914
+ }
915
+ | {
916
+ readonly error: string;
917
+ readonly kind?: undefined;
918
+ readonly provider?: undefined;
919
+ } {
920
+ const providers = new Set<string>();
921
+ for (const step of plan.steps) {
922
+ if (step.route.backend === "opencode") {
923
+ providers.add(step.route.provider);
924
+ }
925
+ }
926
+ if (providers.size > 1) {
927
+ return {
928
+ error: `plan names ${providers.size} OpenCode providers (${[...providers].sort().join(", ")}); the OpenCode server holds one credential for its whole life, so a mixed-provider plan is not supported yet`,
929
+ };
930
+ }
931
+ // No opencode route: the value is never read, and the OAuth default keeps
932
+ // the pre-#133 shape for every caller that passes a claude-only plan.
933
+ const provider = [...providers][0] ?? OPENCODE_OAUTH_PROVIDER;
934
+ return { kind: credentialKindForRoute("opencode", provider), provider };
935
+ }
936
+
937
+ export async function prepareProductionAdmissionContext(input: {
938
+ readonly workspaceRoot: string;
939
+ readonly plan: ResolvedRoutePlan;
940
+ readonly authorityDeps?: ResolveRunnerAuthorityDeps;
941
+ readonly observeOpenCodeIdentity?: OpenCodeIdentityObserver;
942
+ readonly loadSdk?: () => Promise<
943
+ import("./transports/opencode-client").OpenCodeSdkLike
944
+ >;
945
+ readonly env?: RunnerAuthorityOptions["env"];
946
+ readonly credentialBrokers?: RunnerAuthorityOptions["credentialBrokers"];
947
+ // #182: see ProductionRuntimeOptions.freeModelProbe. When present, the
948
+ // server credential below is upgraded to `provider_free` when EVERY
949
+ // opencode route in the plan probes free, and the plan is REFUSED when free
950
+ // and metered mix behind one server. The memoised wrapper is returned so
951
+ // the runtime built from this admission reuses its verdicts.
952
+ readonly freeModelProbe?: FreeModelProbe;
953
+ }): Promise<ProductionAdmissionContext | { readonly error: string }> {
954
+ // #133: ONE opencode credential per plan, decided here, because the
955
+ // OpenCode SERVER is one per backend and outlives every step — it cannot
956
+ // hold two providers' credentials at once. A plan naming two of them is
957
+ // refused by NAME rather than served the wrong one.
958
+ const baseCredential = soleOpenCodeCredential(input.plan);
959
+ if (baseCredential.error !== undefined) {
960
+ return { error: baseCredential.error };
961
+ }
962
+ // #182: the SAME verdict feeds the server credential here and the bindings
963
+ // in resolveFrozenBindings below — computed once per (provider, model) and
964
+ // shared. The wrapper memoises, so the probe spawns at most once per pair
965
+ // no matter how many steps name it, and the bindings (which receive this
966
+ // same instance) never re-spawn for a verdict already taken.
967
+ let openCodeCredential: {
968
+ readonly kind: CredentialKind;
969
+ readonly provider: string;
970
+ } = { kind: baseCredential.kind, provider: baseCredential.provider };
971
+ // #182 follow-up, CLI threading: the authority is resolved BEFORE probe
972
+ // evaluation (not after) so the probe can be built from the
973
+ // AUTHORITY-RESOLVED openCodeBinaryPath — never a second binary lookup for
974
+ // the probe beside the one the authority already did. Reused below as the
975
+ // final authorityOptions with only the decided broker overlaid, so no
976
+ // second resolution runs either.
977
+ const preliminaryAuthority = await prepareProductionRunnerAuthority(
978
+ input.workspaceRoot,
979
+ input.plan,
980
+ input.authorityDeps,
981
+ {
982
+ ...(input.env === undefined ? {} : { env: input.env }),
983
+ ...(input.credentialBrokers === undefined
984
+ ? {}
985
+ : { credentialBrokers: input.credentialBrokers }),
986
+ },
987
+ );
988
+ if ("error" in preliminaryAuthority) {
989
+ return preliminaryAuthority;
990
+ }
991
+ // When the caller supplied no probe but the plan names opencode routes and
992
+ // the authority resolved a binary, probe for real: without this nothing in
993
+ // src/ ever supplies a freeModelProbe on the CLI path, so real runs never
994
+ // upgrade and the feature is dead in production. Fail-closed (a spawn
995
+ // failure probes false) and time-bounded (the probe's own 30s default), so
996
+ // a missing/broken binary keeps the metered kind instead of hanging
997
+ // admission. OAuth-only and claude-only plans skip it: no opencode route
998
+ // means no model to ask about.
999
+ let probeInput = input.freeModelProbe;
1000
+ if (
1001
+ probeInput === undefined &&
1002
+ preliminaryAuthority.openCodeBinaryPath !== undefined &&
1003
+ input.plan.steps.some((step) => step.route.backend === "opencode")
1004
+ ) {
1005
+ probeInput = createFreeModelProbe({
1006
+ binaryPath: preliminaryAuthority.openCodeBinaryPath,
1007
+ });
1008
+ }
1009
+ let sharedFreeProbe: FreeModelProbe | undefined;
1010
+ if (probeInput !== undefined) {
1011
+ const verdicts = new Map<string, Promise<boolean>>();
1012
+ const rawProbe = probeInput;
1013
+ const memoised: FreeModelProbe = (provider: string, model: string) => {
1014
+ // WHY freeVerdictKey, not `${provider}/${model}`: model ids may contain
1015
+ // "/" (model/free-discovery.ts header test), so the join collides
1016
+ // ("a","b/c") vs ("a/b","c") — one verdict for two models. The display
1017
+ // joins below stay human-readable on purpose: they never key a map.
1018
+ const key = freeVerdictKey(provider, model);
1019
+ const cached = verdicts.get(key);
1020
+ if (cached !== undefined) return cached;
1021
+ const verdict = (async () => {
1022
+ try {
1023
+ return await rawProbe(provider, model);
1024
+ } catch {
1025
+ return false;
1026
+ }
1027
+ })();
1028
+ verdicts.set(key, verdict);
1029
+ return verdict;
1030
+ };
1031
+ sharedFreeProbe = memoised;
1032
+ // Only opencode routes that resolved metered can upgrade; OAuth routes
1033
+ // never probe (a subscription model is not free by declaration).
1034
+ if (openCodeCredential.kind === "provider_api_token") {
1035
+ const pairs = new Map<string, { provider: string; model: string }>();
1036
+ for (const step of input.plan.steps) {
1037
+ if (step.route.backend !== "opencode") continue;
1038
+ pairs.set(
1039
+ freeVerdictKey(step.route.provider, step.route.modelSnapshot),
1040
+ {
1041
+ provider: step.route.provider,
1042
+ model: step.route.modelSnapshot,
1043
+ },
1044
+ );
1045
+ }
1046
+ if (pairs.size > 0) {
1047
+ const results = await Promise.all(
1048
+ [...pairs.values()].map(async ({ provider, model }) => ({
1049
+ provider,
1050
+ model,
1051
+ free: await memoised(provider, model),
1052
+ })),
1053
+ );
1054
+ const freeCount = results.filter((r) => r.free).length;
1055
+ if (freeCount > 0 && freeCount < results.length) {
1056
+ const freeNames = results
1057
+ .filter((r) => r.free)
1058
+ .map((r) => `${r.provider}/${r.model}`)
1059
+ .sort();
1060
+ const paidNames = results
1061
+ .filter((r) => !r.free)
1062
+ .map((r) => `${r.provider}/${r.model}`)
1063
+ .sort();
1064
+ return {
1065
+ error: `plan mixes provider_free (${freeNames.join(", ")}) and metered (${paidNames.join(", ")}) OpenCode routes; the OpenCode server holds one credential for its whole life, so a mixed free/metered plan is not supported yet`,
1066
+ };
1067
+ }
1068
+ if (freeCount === results.length) {
1069
+ openCodeCredential = {
1070
+ kind: "provider_free",
1071
+ provider: openCodeCredential.provider,
1072
+ };
1073
+ }
1074
+ }
1075
+ }
1076
+ }
1077
+ // #149: resolve the opencode broker ONCE, here, and seed it into the
1078
+ // authority so runner-authority.ts binding resolution and the transport
1079
+ // registry that launches the server are handed the SAME object. Each side
1080
+ // defaulting its own `new OpenCodeAuthBroker()` is the "two brokers,
1081
+ // diverging in silence" case: a caller injecting a fake would get the fake
1082
+ // at the binding and a real broker at the server.
1083
+ //
1084
+ // #133 adds the second half: the default must MATCH the plan's provider.
1085
+ // An unconditional `new OpenCodeAuthBroker()` here made the api-token route
1086
+ // unreachable on the default path — it would resolve the right kind at the
1087
+ // authority and then be handed a broker that refuses that kind.
1088
+ //
1089
+ // #182: selected from the already-resolved kind (single derivation) so a
1090
+ // free plan gets the free broker here, at the bindings, and at the server —
1091
+ // never an OAuth broker silently projecting a real record under a free route.
1092
+ const credentialBrokers = {
1093
+ ...input.credentialBrokers,
1094
+ opencode:
1095
+ input.credentialBrokers?.opencode ??
1096
+ openCodeCredentialBrokerForKind(
1097
+ openCodeCredential.kind,
1098
+ openCodeCredential.provider,
1099
+ ),
1100
+ };
1101
+ // The preliminary authority above, with only the decided broker overlaid —
1102
+ // re-resolving here would be a second binary lookup for the same binaries.
1103
+ const authorityOptions: RunnerAuthorityOptions = {
1104
+ ...preliminaryAuthority,
1105
+ credentialBrokers,
1106
+ };
1107
+
1108
+ const probeRegistry = createDefaultTransportRegistry({
1109
+ mode: "conformance",
1110
+ binaryPath: authorityOptions.binaryPath,
1111
+ openCodeBinaryPath: authorityOptions.openCodeBinaryPath,
1112
+ env: authorityOptions.env,
1113
+ // #149: the SAME instance seeded into the binding authority above.
1114
+ credentialBroker: credentialBrokers.opencode,
1115
+ // #133: and the kind it was resolved FOR. The launcher pairs the two;
1116
+ // sending the broker without its kind would leave the launcher defaulting
1117
+ // to the OAuth kind over an api-token broker.
1118
+ credentialKind: openCodeCredential.kind,
1119
+ ...(input.loadSdk !== undefined ? { loadSdk: input.loadSdk } : {}),
1120
+ });
1121
+ const probe = await probeBindingsReadiness({
1122
+ ...authorityOptions,
1123
+ plan: input.plan,
1124
+ workspaceRoot: input.workspaceRoot,
1125
+ registry: probeRegistry,
1126
+ observeOpenCodeIdentity: input.observeOpenCodeIdentity,
1127
+ mode: "conformance",
1128
+ authorityDeps: input.authorityDeps,
1129
+ // #182: the SAME memoised instance the server credential above was
1130
+ // decided with — bindings reuse its verdicts instead of re-spawning.
1131
+ ...(sharedFreeProbe === undefined
1132
+ ? {}
1133
+ : { freeModelProbe: sharedFreeProbe }),
1134
+ });
1135
+ if (!probe.decision.ok) {
1136
+ await probe.dispose();
1137
+ return {
1138
+ error: probe.decision.reason ?? "exact-binding readiness gate failed",
1139
+ };
1140
+ }
1141
+
1142
+ const evidence = new Map<RunnerBackend, D1_11ReadinessEvidence>();
1143
+ const needsOpenCode = [...probe.bindings.values()].some(
1144
+ (binding) => binding.route.backend === "opencode",
1145
+ );
1146
+ if (needsOpenCode) {
1147
+ if (probeRegistry instanceof DefaultTransportRegistry) {
1148
+ try {
1149
+ await probeRegistry.probeOpenCodeSdk();
1150
+ } catch (error) {
1151
+ await probe.dispose();
1152
+ const message = error instanceof Error ? error.message : String(error);
1153
+ return { error: `OpenCode SDK pre-confirm failed: ${message}` };
1154
+ }
1155
+ }
1156
+ for (const binding of probe.bindings.values()) {
1157
+ if (binding.route.backend !== "opencode") continue;
1158
+ const report = await binding.capabilities();
1159
+ evidence.set("opencode", d1_11EvidenceFromExactBinding(report, true));
1160
+ }
1161
+ }
1162
+ await probe.dispose();
1163
+
1164
+ const observedBinding = [...probe.bindings.values()].find(
1165
+ (binding): binding is FrozenRuntimeBinding =>
1166
+ binding instanceof FrozenRuntimeBinding &&
1167
+ binding.route.backend === "opencode",
1168
+ );
1169
+ const registry = createDefaultTransportRegistry({
1170
+ mode: "production",
1171
+ observedOpenCodeIdentity: observedBinding?.observedOpenCodeIdentity,
1172
+ evidence,
1173
+ binaryPath: authorityOptions.binaryPath,
1174
+ openCodeBinaryPath: authorityOptions.openCodeBinaryPath,
1175
+ env: authorityOptions.env,
1176
+ // #149: the SAME instance seeded into the binding authority above.
1177
+ credentialBroker: credentialBrokers.opencode,
1178
+ // #133: and the kind it was resolved FOR. The launcher pairs the two;
1179
+ credentialKind: openCodeCredential.kind,
1180
+ ...(input.loadSdk !== undefined ? { loadSdk: input.loadSdk } : {}),
1181
+ }) as DefaultTransportRegistry;
1182
+
1183
+ return {
1184
+ registry,
1185
+ authorityOptions,
1186
+ evidence,
1187
+ ...(sharedFreeProbe === undefined
1188
+ ? {}
1189
+ : { freeModelProbe: sharedFreeProbe }),
1190
+ };
1191
+ }
1192
+
1193
+ function createImmutableBindingsMap(
1194
+ bindings: Map<string, RuntimeBinding>,
1195
+ ): ReadonlyMap<string, RuntimeBinding> {
1196
+ const frozen = new Map(bindings);
1197
+ return new Proxy(frozen, {
1198
+ get(target, prop) {
1199
+ if (prop === "set" || prop === "delete" || prop === "clear") {
1200
+ return () => {
1201
+ throw new ProductionRuntimeError("runtime bindings are immutable");
1202
+ };
1203
+ }
1204
+ const value = Reflect.get(target, prop);
1205
+ if (typeof value === "function") {
1206
+ return value.bind(target);
1207
+ }
1208
+ return value;
1209
+ },
1210
+ }) as ReadonlyMap<string, RuntimeBinding>;
1211
+ }
1212
+
1213
+ export class MultiProviderRunner implements StepRunner {
1214
+ private readonly workspaceRoot: string;
1215
+ private readonly bindings: ReadonlyMap<string, RuntimeBinding>;
1216
+ private readonly registry: TransportRegistry;
1217
+ private readonly defaultBindingKey?: string;
1218
+ private readonly spawnFn?: typeof Bun.spawn;
1219
+ private readonly signal?: AbortSignal;
1220
+ private readonly attemptAdmissionGate?: AttemptAdmissionGate;
1221
+ private readonly graceMarginMs?: number;
1222
+ private readonly leaseTracker?: ActiveTransportLeaseTracker;
1223
+ // 2026-09-02: ONE ledger for the whole run, and note the shape — it is
1224
+ // injectable but NOT optional-off, unlike `attemptAdmissionGate` beside it.
1225
+ // That difference is the point: the concurrency gate is an opt-in policy, a
1226
+ // spend ledger is a GUARANTEE. Before 2026-09-02 nothing in src/ built one,
1227
+ // and that absence made `settlementFromUsage` unreachable on every real run
1228
+ // — it is only ever called from `finalizeReservation`, which returns early
1229
+ // when no ledger is configured. An opt-in default would reintroduce exactly
1230
+ // that, one forgetful caller at a time.
1231
+ //
1232
+ // Run-scoped because this runner is: `createProductionRuntime` builds
1233
+ // exactly one `MultiProviderRunner` per run, while `run()` below builds a
1234
+ // FRESH `StepExecutionHarness` per step. A ledger constructed down there
1235
+ // would carry a `fencedBuckets` set that dies with the step — it would look
1236
+ // wired and fence nothing, which is worse than none because it reads as
1237
+ // covered. Holding it here is what makes the fence span the run.
1238
+ private readonly spendLedger: SpendLedger;
1239
+
1240
+ constructor(options: {
1241
+ readonly workspaceRoot: string;
1242
+ readonly bindings: ReadonlyMap<string, RuntimeBinding>;
1243
+ readonly registry: TransportRegistry;
1244
+ readonly defaultBindingKey?: string;
1245
+ readonly spawnFn?: typeof Bun.spawn;
1246
+ readonly signal?: AbortSignal;
1247
+ readonly attemptAdmissionGate?: AttemptAdmissionGate;
1248
+ readonly graceMarginMs?: number;
1249
+ readonly leaseTracker?: ActiveTransportLeaseTracker;
1250
+ // Injected only by tests that need to observe the CAS calls; production
1251
+ // takes the default, which is the whole point of defaulting rather than
1252
+ // requiring a caller to remember.
1253
+ readonly spendLedger?: SpendLedger;
1254
+ }) {
1255
+ this.workspaceRoot = options.workspaceRoot;
1256
+ this.bindings = options.bindings;
1257
+ this.registry = options.registry;
1258
+ this.defaultBindingKey = options.defaultBindingKey;
1259
+ this.spawnFn = options.spawnFn;
1260
+ this.signal = options.signal;
1261
+ this.attemptAdmissionGate = options.attemptAdmissionGate;
1262
+ this.graceMarginMs = options.graceMarginMs;
1263
+ this.leaseTracker = options.leaseTracker;
1264
+ this.spendLedger = options.spendLedger ?? new InMemorySpendLedger();
1265
+ }
1266
+
1267
+ resolveBinding(step: StepSpec): RuntimeBinding | undefined {
1268
+ if (step.routeKey !== undefined) {
1269
+ return this.bindings.get(step.routeKey);
1270
+ }
1271
+ if (step.route !== undefined) {
1272
+ for (const binding of this.bindings.values()) {
1273
+ if (
1274
+ binding.route.backend === step.route.backend &&
1275
+ binding.route.provider === step.route.provider &&
1276
+ binding.route.modelFamily === step.route.modelFamily &&
1277
+ binding.route.modelSnapshot === step.route.modelSnapshot &&
1278
+ binding.route.modelVariant === step.route.modelVariant &&
1279
+ (binding.route.gateway ?? "") === (step.route.gateway ?? "")
1280
+ ) {
1281
+ return binding;
1282
+ }
1283
+ }
1284
+ return undefined;
1285
+ }
1286
+ if (this.defaultBindingKey !== undefined) {
1287
+ return this.bindings.get(this.defaultBindingKey);
1288
+ }
1289
+ if (this.bindings.size === 1) {
1290
+ return [...this.bindings.values()][0];
1291
+ }
1292
+ return undefined;
1293
+ }
1294
+
1295
+ async run(step: StepSpec): Promise<StepResult> {
1296
+ const binding = this.resolveBinding(step);
1297
+ if (binding === undefined) {
1298
+ return {
1299
+ name: step.name,
1300
+ status: "failed",
1301
+ usage: zeroUsage(),
1302
+ attempts: 0,
1303
+ stderrTail:
1304
+ step.routeKey !== undefined
1305
+ ? `No admitted binding for routeKey ${step.routeKey}`
1306
+ : "No admitted binding for step route",
1307
+ resultText: "",
1308
+ };
1309
+ }
1310
+
1311
+ const cwdAuth = authorizeWorkspaceCwd(this.workspaceRoot, step.cwd);
1312
+ if (!cwdAuth.approved) {
1313
+ return {
1314
+ name: step.name,
1315
+ status: "failed",
1316
+ denialCode: "path_not_approved",
1317
+ usage: zeroUsage(),
1318
+ attempts: 0,
1319
+ stderrTail: `Workspace denied: ${cwdAuth.reason}`,
1320
+ resultText: "",
1321
+ };
1322
+ }
1323
+
1324
+ if (step.routeKey !== undefined && step.route !== undefined) {
1325
+ const driftError = validateRouteDrift(binding.route, step.route);
1326
+ if (driftError !== undefined) {
1327
+ return {
1328
+ name: step.name,
1329
+ status: "failed",
1330
+ usage: zeroUsage(),
1331
+ attempts: 0,
1332
+ stderrTail: driftError,
1333
+ resultText: "",
1334
+ };
1335
+ }
1336
+ }
1337
+
1338
+ const policyError = await validateBindingAdmission(step, binding);
1339
+ if (policyError !== undefined) {
1340
+ return {
1341
+ name: step.name,
1342
+ status: "failed",
1343
+ usage: zeroUsage(),
1344
+ attempts: 0,
1345
+ stderrTail: policyError,
1346
+ resultText: "",
1347
+ };
1348
+ }
1349
+
1350
+ if (
1351
+ binding.route.backend === "opencode" &&
1352
+ this.registry instanceof DefaultTransportRegistry &&
1353
+ this.registry.needsOpenCodeSdkProbe()
1354
+ ) {
1355
+ try {
1356
+ await this.registry.probeOpenCodeSdk();
1357
+ } catch (error) {
1358
+ const message = error instanceof Error ? error.message : String(error);
1359
+ return {
1360
+ name: step.name,
1361
+ status: "failed",
1362
+ usage: zeroUsage(),
1363
+ attempts: 0,
1364
+ stderrTail: `OpenCode SDK pre-confirm failed: ${message}`,
1365
+ resultText: "",
1366
+ };
1367
+ }
1368
+ }
1369
+
1370
+ const capabilityReport = await binding.capabilities();
1371
+ const capabilityGate = exactBindingCapabilityGate(capabilityReport);
1372
+ if (!capabilityGate.ok) {
1373
+ return {
1374
+ name: step.name,
1375
+ status: "failed",
1376
+ usage: zeroUsage(),
1377
+ attempts: 0,
1378
+ stderrTail: `Exact-binding capability gate failed: ${capabilityGate.reason}`,
1379
+ resultText: "",
1380
+ };
1381
+ }
1382
+
1383
+ // 2026-09-02. WHICH steps reserve into the run's ledger: metered ones
1384
+ // only, read off the report the gate above just admitted rather than
1385
+ // re-derived from `binding.credential.kind`. One derivation of one fact —
1386
+ // the same `effectiveBillingMode` #133 computes once and feeds to all
1387
+ // three billing readers — so the fact that decided admission is the fact
1388
+ // that decides reservation.
1389
+ //
1390
+ // WHY not every step. The ledger's guarantee is "an unresolved bucket
1391
+ // blocks the next paid attempt", and `finalizeReservation` reaches it on
1392
+ // more than the metered-zero rule: partial usage, unavailable usage (an
1393
+ // OpenCode attempt where no usage event ever arrived, and ANY backend's
1394
+ // harness watchdog timeout, which normalizes to unavailable), and an
1395
+ // attempt that comes back `cancelled`. Any one of those fences the bucket
1396
+ // for the rest of the ledger's life.
1397
+ //
1398
+ // On a metered bucket that is exactly right and fail-closed: we do not
1399
+ // know what we spent, so we stop spending. On a SUBSCRIPTION bucket it
1400
+ // would refuse later steps over dollars that cannot be spent — and it
1401
+ // would do so against a pipeline built to survive exactly this. Hunters
1402
+ // run under `Promise.allSettled` and `runPipeline` tolerates a lost
1403
+ // hunter (`hunterFailures`, failing the run only when ALL of them fail),
1404
+ // so one hunter whose stdout would not parse would fence the credential
1405
+ // and take the refuter down with it. That trades a degraded run for a
1406
+ // dead one, buying nothing, on the one backend that demonstrably works
1407
+ // today.
1408
+ //
1409
+ // Same reasoning keeps `ClaudeCodeRunner` (step-runner.ts) ledger-free:
1410
+ // claude-code resolves to `claude_subscription_oauth` for every provider
1411
+ // (`credentialKindForRoute`), so the metered-zero rule structurally cannot
1412
+ // fire there. A ledger on that path is a state machine with no guarantee
1413
+ // to enforce. The known limitation, deliberately not addressed here: a
1414
+ // claude-code run under a real `ANTHROPIC_API_KEY` does spend money, but
1415
+ // the engine models that backend as subscription on purpose — ci/gates.ts
1416
+ // documents why deriving it instead is an ADMISSION hazard, and
1417
+ // `resolveCiBudgetCeiling` is where that case is handled.
1418
+ //
1419
+ // 2026-09-02, #177: one clause of that paragraph is no longer true and the
1420
+ // correction matters. Its usage RECORDS are no longer "truthfully
1421
+ // subscription" on every route — the Claude CLI transport now stamps
1422
+ // `metered` when the projected child env carries ANTHROPIC_API_KEY or
1423
+ // ANTHROPIC_AUTH_TOKEN, so the run's real spend reaches `cashCostUsd`
1424
+ // instead of being filed as an uncharged list price. This line is
1425
+ // deliberately unchanged: it reads the CAPABILITY REPORT, not the usage
1426
+ // record, so no reservation is opened, nothing is fenced, and no API-key
1427
+ // route loses admission. The record is honest; the gate stays where #161
1428
+ // must move it.
1429
+ //
1430
+ // A claude-only run therefore records no reservations at all, and the
1431
+ // absent `reservations` key on those steps is the truthful signal — not a
1432
+ // gap.
1433
+ //
1434
+ // #182 follow-up: free OpenCode bindings reserve too — read off the
1435
+ // credential KIND, not the report (which still says subscription for free
1436
+ // routes: capability `BillingMode` stays binary on purpose). Without a
1437
+ // reservation `finalizeReservation` never runs, the free-nonzero rule
1438
+ // (spend-limiter.ts) would be dead in production, and a flipped model
1439
+ // would keep spending attempts instead of fencing the bucket and failing
1440
+ // closed. A free step that stays free settles 0 and never fences, so the
1441
+ // subscription reasoning above ("refusing later steps over dollars that
1442
+ // cannot be spent") does not apply: only a priced flip, partial usage, or
1443
+ // unavailable usage fences a free bucket.
1444
+ const reservesSpend =
1445
+ capabilityReport.billing.mode === "metered" ||
1446
+ binding.credential.kind === "provider_free";
1447
+
1448
+ // #279, 2026-09-24: the harness itself decides whether a SINGLE attempt
1449
+ // whose Keychain projection degraded onto an ambient key/token still
1450
+ // needs to reserve — a fact only it can see, per `run()`, not per
1451
+ // binding (see harness.ts's `reservesSpend`/`degradedProjectionBucketId`
1452
+ // options and their WHY). That requires the ledger to be REACHABLE from
1453
+ // every binding, subscription included, so `spendLedger` below is now
1454
+ // unconditional; `reservesSpend` still gates the binding's OWN
1455
+ // unconditional-per-attempt reservation exactly as it always has.
1456
+ const isolation = minimalIsolationFromExecutable(binding.executable);
1457
+ const lease = await binding.acquire(isolation, this.registry);
1458
+ const routeKey = binding.key;
1459
+ try {
1460
+ const harness = new StepExecutionHarness({
1461
+ workspaceRoot: this.workspaceRoot,
1462
+ executableAllowlist: [
1463
+ {
1464
+ absolutePath: binding.executable.absolutePath,
1465
+ sha256: binding.executable.sha256,
1466
+ },
1467
+ ],
1468
+ binaryPath: binding.executable.absolutePath,
1469
+ credentialBroker: binding.credential.broker,
1470
+ transport: lease.transport,
1471
+ spawnFn: this.spawnFn,
1472
+ signal: this.signal,
1473
+ ...(this.attemptAdmissionGate !== undefined
1474
+ ? { attemptAdmissionGate: this.attemptAdmissionGate }
1475
+ : {}),
1476
+ rateLimitBucketId: binding.credential.bucketId,
1477
+ // The bucket id is per provider+credential (`bindingBucketId`), so a
1478
+ // fence lands on the credential that could not account for its spend
1479
+ // and leaves every other route admissible.
1480
+ //
1481
+ // `reservedUsdPerAttempt` is deliberately left at the harness default
1482
+ // of 0 rather than given an invented number: `reservedUsd` is
1483
+ // RECORDED on the reservation and read by no gate anywhere — the
1484
+ // fence keys on `fencedBuckets`, never on an amount — so a figure
1485
+ // here would be a budget nobody has decided, dressed as one that was.
1486
+ //
1487
+ // #279: `spendLedger` is now handed to EVERY binding — see the WHY
1488
+ // just above `isolation` — with `reservesSpend` carrying the
1489
+ // per-binding decision the conditional spread used to encode. A
1490
+ // subscription binding (`reservesSpend: false`) still reserves
1491
+ // nothing on its own; only its harness's own degraded-projection
1492
+ // check (envBillsMetered on the actual child env) can open a
1493
+ // reservation now, and only into `degradedProjectionBucketId` —
1494
+ // the bucket a metered claude-code binding of this SAME
1495
+ // provider+credential would compute, never this binding's own
1496
+ // subscription bucket (see `degradedMeteredBucketId`'s WHY above).
1497
+ spendLedger: this.spendLedger,
1498
+ reservesSpend,
1499
+ degradedProjectionBucketId: degradedMeteredBucketId(
1500
+ binding.route.provider,
1501
+ binding.credential.ref,
1502
+ ),
1503
+ ...(this.graceMarginMs !== undefined
1504
+ ? { graceMarginMs: this.graceMarginMs }
1505
+ : {}),
1506
+ onBeforeCredentialProjectionDestroy: async () => {
1507
+ if (this.leaseTracker === undefined) {
1508
+ return;
1509
+ }
1510
+ await this.leaseTracker.teardownTransportIfLast({
1511
+ routeKey,
1512
+ transport: lease.transport,
1513
+ });
1514
+ },
1515
+ });
1516
+
1517
+ return await harness.run({
1518
+ ...step,
1519
+ cwd: cwdAuth.canonicalCwd,
1520
+ route: binding.route,
1521
+ routeKey: binding.key,
1522
+ credentialKind: binding.credential.kind,
1523
+ credentialRef: binding.credential.ref,
1524
+ });
1525
+ } finally {
1526
+ await lease.dispose();
1527
+ }
1528
+ }
1529
+ }
1530
+
1531
+ export async function createProductionRuntime(
1532
+ options: ProductionRuntimeOptions,
1533
+ ): Promise<ProductionRuntime> {
1534
+ const workspaceAuth = authorizeWorkspaceCwd(
1535
+ options.workspaceRoot,
1536
+ options.workspaceRoot,
1537
+ );
1538
+ if (!workspaceAuth.approved) {
1539
+ throw new ProductionRuntimeError(
1540
+ `workspace root denied before admission: ${workspaceAuth.reason}`,
1541
+ );
1542
+ }
1543
+
1544
+ const plan = freezeRoutePlan(options.plan);
1545
+ // #182: when a probe is supplied but no registry is, decide the free
1546
+ // verdict BEFORE building the fallback so the server and the bindings share
1547
+ // one verdict. The memoised wrapper is what bindings resolve with below —
1548
+ // one spawn per (provider, model), never two that could disagree.
1549
+ let effectiveOptions = options;
1550
+ let soleOverride:
1551
+ | { readonly kind: CredentialKind; readonly provider: string }
1552
+ | undefined;
1553
+ if (options.freeModelProbe !== undefined && options.registry === undefined) {
1554
+ const rawProbe = options.freeModelProbe;
1555
+ const verdicts = new Map<string, Promise<boolean>>();
1556
+ const memoised: FreeModelProbe = (provider, model) => {
1557
+ // WHY freeVerdictKey, not `${provider}/${model}`: model ids may contain
1558
+ // "/" (model/free-discovery.ts header test), so the join collides
1559
+ // ("a","b/c") vs ("a/b","c") — one verdict for two models. The display
1560
+ // joins below stay human-readable on purpose: they never key a map.
1561
+ const key = freeVerdictKey(provider, model);
1562
+ const cached = verdicts.get(key);
1563
+ if (cached !== undefined) return cached;
1564
+ const verdict = (async () => {
1565
+ try {
1566
+ return await rawProbe(provider, model);
1567
+ } catch {
1568
+ return false;
1569
+ }
1570
+ })();
1571
+ verdicts.set(key, verdict);
1572
+ return verdict;
1573
+ };
1574
+ effectiveOptions = { ...options, freeModelProbe: memoised };
1575
+ const base = soleOpenCodeCredential(plan);
1576
+ if (base.error !== undefined) {
1577
+ throw new ProductionRuntimeError(base.error);
1578
+ }
1579
+ if (base.kind === "provider_api_token" && base.provider !== undefined) {
1580
+ const pairs = new Map<string, { provider: string; model: string }>();
1581
+ for (const step of plan.steps) {
1582
+ if (step.route.backend !== "opencode") continue;
1583
+ pairs.set(
1584
+ freeVerdictKey(step.route.provider, step.route.modelSnapshot),
1585
+ {
1586
+ provider: step.route.provider,
1587
+ model: step.route.modelSnapshot,
1588
+ },
1589
+ );
1590
+ }
1591
+ if (pairs.size > 0) {
1592
+ const results = await Promise.all(
1593
+ [...pairs.values()].map(async ({ provider, model }) => ({
1594
+ provider,
1595
+ model,
1596
+ free: await memoised(provider, model),
1597
+ })),
1598
+ );
1599
+ const freeCount = results.filter((r) => r.free).length;
1600
+ if (freeCount > 0 && freeCount < results.length) {
1601
+ const freeNames = results
1602
+ .filter((r) => r.free)
1603
+ .map((r) => `${r.provider}/${r.model}`)
1604
+ .sort();
1605
+ const paidNames = results
1606
+ .filter((r) => !r.free)
1607
+ .map((r) => `${r.provider}/${r.model}`)
1608
+ .sort();
1609
+ throw new ProductionRuntimeError(
1610
+ `plan mixes provider_free (${freeNames.join(", ")}) and metered (${paidNames.join(", ")}) OpenCode routes; the OpenCode server holds one credential for its whole life, so a mixed free/metered plan is not supported yet`,
1611
+ );
1612
+ }
1613
+ if (freeCount === results.length) {
1614
+ soleOverride = {
1615
+ kind: "provider_free",
1616
+ provider: base.provider,
1617
+ };
1618
+ }
1619
+ }
1620
+ }
1621
+ }
1622
+ const registry =
1623
+ effectiveOptions.registry ??
1624
+ productionFallbackRegistry({
1625
+ mode: effectiveOptions.mode,
1626
+ evidence: effectiveOptions.evidence,
1627
+ binaryPath: effectiveOptions.binaryPath,
1628
+ env: effectiveOptions.env,
1629
+ credentialBrokers: effectiveOptions.credentialBrokers,
1630
+ plan,
1631
+ ...(soleOverride === undefined
1632
+ ? {}
1633
+ : { soleCredentialOverride: soleOverride }),
1634
+ });
1635
+
1636
+ const leaseTracker = new DefaultActiveTransportLeaseTracker();
1637
+ const bindings = await resolveFrozenBindings(
1638
+ plan,
1639
+ effectiveOptions,
1640
+ registry,
1641
+ leaseTracker,
1642
+ );
1643
+ // #182: never silently project OAuth for a free route. A free binding behind
1644
+ // a non-free server (or a free server with no free binding) is a wiring
1645
+ // divergence, not a fallback — refuse loudly. The precedent is the existing
1646
+ // mixed-provider refusal above: one server, one credential, no silent pick.
1647
+ if (registry instanceof DefaultTransportRegistry) {
1648
+ const serverKind = registry.openCodeCredentialKind;
1649
+ const hasFreeBinding = [...bindings.values()].some(
1650
+ (b) => b.credential.kind === "provider_free",
1651
+ );
1652
+ const hasOpenCodeBinding = [...bindings.values()].some(
1653
+ (b) => b.route.backend === "opencode",
1654
+ );
1655
+ if (hasFreeBinding && serverKind !== "provider_free") {
1656
+ throw new ProductionRuntimeError(
1657
+ `free OpenCode binding resolved but the server credential is ${serverKind ?? "unset"}; refusing to project a non-free credential under a free route (forward the admission's freeModelProbe so both share one verdict)`,
1658
+ );
1659
+ }
1660
+ if (
1661
+ serverKind === "provider_free" &&
1662
+ hasOpenCodeBinding &&
1663
+ !hasFreeBinding
1664
+ ) {
1665
+ throw new ProductionRuntimeError(
1666
+ `OpenCode server holds a free credential but no binding resolved free; refusing to serve metered routes from an empty projection (forward the admission's freeModelProbe so both share one verdict)`,
1667
+ );
1668
+ }
1669
+ // #182 follow-up: the partial mix — a free server with SOME free and SOME
1670
+ // metered opencode bindings, reachable when the runtime probes with a
1671
+ // different instance than the admission (or none). Without this branch the
1672
+ // slipped metered binding fails closed LATER at projection with
1673
+ // missing_provider_record, and the harness fails the step pre-spawn — a
1674
+ // confusing failure for a wiring divergence. This branch upgrades it into
1675
+ // the actionable refusal the guard exists for, in the same shape as its
1676
+ // neighbors.
1677
+ if (serverKind === "provider_free" && hasFreeBinding) {
1678
+ const meteredNames = [...bindings.values()]
1679
+ .filter(
1680
+ (b) =>
1681
+ b.route.backend === "opencode" &&
1682
+ b.credential.kind !== "provider_free",
1683
+ )
1684
+ .map((b) => `${b.route.provider}/${b.route.modelSnapshot}`)
1685
+ .sort();
1686
+ if (meteredNames.length > 0) {
1687
+ throw new ProductionRuntimeError(
1688
+ `OpenCode server holds a free credential but ${meteredNames.length} binding(s) resolved metered (${meteredNames.join(", ")}); refusing to serve metered routes from an empty projection (forward the admission's freeModelProbe so both share one verdict)`,
1689
+ );
1690
+ }
1691
+ }
1692
+ }
1693
+ // Backend-wide compatibility admission must consume the same observations
1694
+ // as exact bindings, not reconstruct an unobserved factory beside them.
1695
+ const compatibilityReports = new Map<
1696
+ RunnerBackend,
1697
+ ProviderCapabilityReport
1698
+ >();
1699
+ for (const binding of bindings.values()) {
1700
+ if (compatibilityReports.has(binding.route.backend)) continue;
1701
+ compatibilityReports.set(
1702
+ binding.route.backend,
1703
+ await registry.getCapabilityReport(binding.route.backend, {
1704
+ mode: options.mode,
1705
+ evidence: options.evidence,
1706
+ observedOpenCodeIdentity:
1707
+ binding instanceof FrozenRuntimeBinding
1708
+ ? binding.observedOpenCodeIdentity
1709
+ : undefined,
1710
+ }),
1711
+ );
1712
+ }
1713
+ const admitted = await admitRoutePlan(plan, registry, {
1714
+ capabilities: compatibilityReports,
1715
+ mode: options.mode,
1716
+ evidence: options.evidence,
1717
+ });
1718
+
1719
+ const defaultClaude = [...bindings.values()].find(
1720
+ (binding) => binding.route.backend === "claude-code",
1721
+ );
1722
+ const runnerBindings = createImmutableBindingsMap(bindings);
1723
+ const runner = new MultiProviderRunner({
1724
+ workspaceRoot: options.workspaceRoot,
1725
+ bindings: runnerBindings,
1726
+ registry,
1727
+ defaultBindingKey: defaultClaude?.key,
1728
+ spawnFn: options.spawnFn,
1729
+ signal: options.signal,
1730
+ attemptAdmissionGate: options.attemptAdmissionGate,
1731
+ graceMarginMs: options.graceMarginMs,
1732
+ leaseTracker,
1733
+ });
1734
+
1735
+ return {
1736
+ runner,
1737
+ registry,
1738
+ bindings: createImmutableBindingsMap(bindings),
1739
+ admitted,
1740
+ evidence: options.evidence,
1741
+ dispose: async () => {
1742
+ leaseTracker.releaseAll(registry);
1743
+ },
1744
+ };
1745
+ }
1746
+
1747
+ export function createClaudeCompatibilityRunner(
1748
+ options: RunnerAuthorityOptions,
1749
+ deps: ResolveRunnerAuthorityDeps = {},
1750
+ ): Promise<StepRunner> {
1751
+ return withClaudeDiscoveryAllowlist(options, deps).then((resolvedOptions) => {
1752
+ if ("error" in resolvedOptions) {
1753
+ throw new ProductionRuntimeError(resolvedOptions.error);
1754
+ }
1755
+ // Claude-only by construction; credentialKindForRoute ignores the
1756
+ // provider for this backend.
1757
+ return resolveBindingAuthority(
1758
+ "claude-code",
1759
+ "anthropic",
1760
+ resolvedOptions,
1761
+ deps,
1762
+ ).then((result) => {
1763
+ if (result.error !== undefined || result.binding === undefined) {
1764
+ throw new ProductionRuntimeError(
1765
+ result.error ?? "claude authority unavailable",
1766
+ );
1767
+ }
1768
+ const binding = result.binding;
1769
+ return new ClaudeCodeRunner({
1770
+ workspaceRoot: binding.workspaceRoot,
1771
+ binaryPath: binding.binaryPath,
1772
+ executableAllowlist: binding.executableAllowlist,
1773
+ ...(binding.credentialBroker
1774
+ ? { credentialBroker: binding.credentialBroker }
1775
+ : {}),
1776
+ });
1777
+ });
1778
+ });
1779
+ }
1780
+
1781
+ export type { BindingAuthorityResolution, ResolvedBindingAuthority };
1782
+
1783
+ // #149, second round: the registry a caller gets when it supplies none. Shared
1784
+ // by both fallbacks because they had drifted into the same defect twice — the
1785
+ // caller supplied `credentialBrokers` and the registry dropped it, so the
1786
+ // binding authority got the caller broker (runner-authority.ts:335) and the
1787
+ // server that actually runs the inference got a fresh real one. Found by
1788
+ // pr-hero own review of the first fix, which patched only the third site.
1789
+ export function productionFallbackRegistry(options: {
1790
+ readonly mode?: "production" | "conformance";
1791
+ readonly evidence?: Map<RunnerBackend, D1_11ReadinessEvidence>;
1792
+ readonly binaryPath?: string;
1793
+ readonly openCodeBinaryPath?: string;
1794
+ // #161: matches `RunnerAuthorityOptions.env`'s widened shape — this
1795
+ // function is fed `options`/`authorityOptions` (both that type) directly.
1796
+ readonly env?: Readonly<Record<string, string | undefined>>;
1797
+ readonly credentialBrokers?: RunnerAuthorityOptions["credentialBrokers"];
1798
+ // #133: optional because this function is also called with a bare
1799
+ // `{ mode }` by callers that never reach an opencode route. When it IS
1800
+ // present it decides the credential KIND, and dropping it here is how this
1801
+ // fallback drifts from the binding authority for the THIRD time — the two
1802
+ // earlier rounds are recorded in the comment above, both found by pr-hero
1803
+ // reviewing its own fix.
1804
+ readonly plan?: ResolvedRoutePlan;
1805
+ // #182: async callers (createProductionRuntime with a freeModelProbe) decide
1806
+ // the free verdict BEFORE building the fallback — this sync function cannot
1807
+ // spawn — and hand the decided credential here so the server and the
1808
+ // bindings share one verdict instead of two spawns that could disagree.
1809
+ readonly soleCredentialOverride?: {
1810
+ readonly kind: CredentialKind;
1811
+ readonly provider: string;
1812
+ };
1813
+ }): TransportRegistry {
1814
+ const credential =
1815
+ options.soleCredentialOverride !== undefined
1816
+ ? options.soleCredentialOverride
1817
+ : options.plan === undefined
1818
+ ? undefined
1819
+ : soleOpenCodeCredential(options.plan);
1820
+ if (
1821
+ credential !== undefined &&
1822
+ "error" in credential &&
1823
+ (credential as { error?: string }).error !== undefined
1824
+ ) {
1825
+ throw new ProductionRuntimeError((credential as { error: string }).error);
1826
+ }
1827
+ const kind =
1828
+ credential === undefined
1829
+ ? undefined
1830
+ : (credential as { kind: CredentialKind }).kind;
1831
+ // #182: when the decided kind is free and no broker was supplied, default to
1832
+ // the free broker — NOT the OAuth default in openCodeLaunchServerFor. That
1833
+ // default pairs an OAuth broker with whatever kind travels, and pairing it
1834
+ // with `provider_free` would refuse by name (loud but useless).
1835
+ //
1836
+ // #280 changed what this substitution costs. The free broker used to read
1837
+ // nothing, so a fresh instance here was indistinguishable from the caller's.
1838
+ // It now reads the provider's own `api` record from auth.json when one
1839
+ // exists, so a fresh instance here and another at the binding would be two
1840
+ // independent reads of the same mutable store — the "two brokers, diverging
1841
+ // in silence" class #149 closed. The production path never reaches this:
1842
+ // prepareProductionAdmissionContext resolves ONE broker and seeds it into
1843
+ // `credentialBrokers.opencode`, which both the bindings and this registry
1844
+ // receive. This default only serves callers that build a runtime without
1845
+ // that context (tests, probes); pass `credentialBrokers.opencode` to share.
1846
+ const needsFreeDefault =
1847
+ kind === "provider_free" &&
1848
+ options.credentialBrokers?.opencode === undefined;
1849
+ return createDefaultTransportRegistry({
1850
+ mode: options.mode,
1851
+ evidence: options.evidence,
1852
+ binaryPath: options.binaryPath,
1853
+ openCodeBinaryPath: options.openCodeBinaryPath,
1854
+ env: options.env,
1855
+ // Forwarded only when the caller actually supplied one. Substituting a
1856
+ // fresh broker here would erase the difference between "no preference"
1857
+ // and "use THIS one", which is the whole defect.
1858
+ ...(options.credentialBrokers?.opencode === undefined
1859
+ ? needsFreeDefault
1860
+ ? {
1861
+ credentialBroker: openCodeCredentialBrokerForKind(
1862
+ "provider_free",
1863
+ (credential as { provider: string }).provider,
1864
+ ),
1865
+ }
1866
+ : {}
1867
+ : { credentialBroker: options.credentialBrokers.opencode }),
1868
+ // The KIND travels even when the broker does not: the registry's own
1869
+ // default broker (openCodeLaunchServerFor) must be built for the plan's
1870
+ // provider, and its default kind must match whatever broker it ends up
1871
+ // with. Without this, a `zai` plan gave the binding an
1872
+ // OpenCodeApiTokenBroker and the server an OAuth broker asking for the
1873
+ // OAuth kind — which would project the operator's OpenAI record under a
1874
+ // zai route. Wrong, not loud, and the worse of the two failure shapes.
1875
+ ...(credential === undefined ? {} : { credentialKind: kind }),
1876
+ });
1877
+ }