crysk 0.0.0-stage → 0.3.0

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 (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  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/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,1124 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { capabilityGateDecision } from "#model/provider-capabilities";
6
+ import type { ResolvedRoutePlan, ResolvedStepRoute } from "#model/routing";
7
+ import { type AssetMode, detectAssetMode } from "./assets";
8
+ // Route-keyed transport factory/cache: one ProviderTransport instance per
9
+ // `${backend}:${routeFingerprint}`. `release()` drops a lease; teardown order
10
+ // inside OpenCodeSdkTransport is stream → client.close → server (harness owns
11
+ // step timeout and calls destroy on credential projection after transport returns).
12
+ import type {
13
+ CredentialKind,
14
+ ProviderCapabilityReport,
15
+ ProviderTransport,
16
+ ResolvedModelRoute,
17
+ RunnerBackend,
18
+ } from "./execution/contracts";
19
+ import type { UsageBillingMode } from "./execution/usage-normalized";
20
+ import { prheroLayout } from "./home-preflight";
21
+ import { credentialKindBillsMetered } from "./runner-authority";
22
+ import {
23
+ type CredentialBroker,
24
+ OpenCodeAuthBroker,
25
+ } from "./security/credential-broker";
26
+ import { redactDiagnostic } from "./security/redact";
27
+ import { ClaudeCodeCliTransport } from "./transports/claude-code-cli";
28
+ import {
29
+ type OpenCodeObservedIdentity,
30
+ OpenCodeSdkUnavailableError,
31
+ openCodeSdkLoadFailedMessage,
32
+ openCodeSdkUnavailableMessage,
33
+ qualifyOpenCodeServer,
34
+ } from "./transports/opencode-admission";
35
+ import {
36
+ assertOpenCodeSdk,
37
+ createOpenCodeClient,
38
+ type OpenCodeSdkLike,
39
+ } from "./transports/opencode-client";
40
+ import type { OpenCodeMcpConfig } from "./transports/opencode-mcp";
41
+ import {
42
+ type OpenCodeClientLike,
43
+ OpenCodeSdkTransport,
44
+ } from "./transports/opencode-sdk";
45
+ import {
46
+ launchProjectedOpenCodeServer,
47
+ type OpenCodeServerHandle,
48
+ } from "./transports/opencode-server";
49
+
50
+ const OPENCODE_SDK_PACKAGE_SPECIFIER = "@opencode-ai/sdk/package.json";
51
+ // The CLIENT entry, not the full `/v2` index. `/v2` re-exports
52
+ // `dist/v2/server.js`, which imports `cross-spawn`, whose nested
53
+ // `require("which")` Bun's `--compile` runtime does not resolve for a package
54
+ // living outside the binary (under ~/.prhero/node_modules). Why the compiled
55
+ // runtime fails there is not established; that it fails is. pr-hero never
56
+ // launches the SDK's own server (see
57
+ // src/transports/opencode-server.ts's WHY-NOT header) — it only ever needs
58
+ // `createOpencodeClient` (assertOpenCodeSdk) — so `/v2/client` is both
59
+ // sufficient and the only one of the two that loads inside a compiled binary.
60
+ // Confirmed by a discriminating repro compiled with `bun build --compile`:
61
+ // `dist/v2/index.js` throws `Cannot find package 'which'`, `dist/v2/client.js`
62
+ // exports `createOpencodeClient` cleanly, and its relative import graph
63
+ // (gen/client/client.gen.js, gen/sdk.gen.js, ../error-interceptor.js) carries
64
+ // no bare imports.
65
+ const OPENCODE_SDK_V2_SPECIFIER = "@opencode-ai/sdk/v2/client";
66
+
67
+ function openCodeSdkPackageJsonPath(nodeModulesDir: string): string {
68
+ return path.join(nodeModulesDir, "@opencode-ai", "sdk", "package.json");
69
+ }
70
+
71
+ export interface OpenCodeSdkPackageMetadata {
72
+ version?: string;
73
+ exports?: unknown;
74
+ }
75
+
76
+ export interface OpenCodeSdkLoadOptions {
77
+ importPackage?: () => Promise<OpenCodeSdkPackageMetadata>;
78
+ importSdk?: () => Promise<unknown>;
79
+ // Injected so a test can fail the bare specifier and serve the home tree.
80
+ importSpecifier?: (specifier: string) => Promise<unknown>;
81
+ // Injected so `bun test` (always `dev`) can exercise the compiled branch.
82
+ // Absent mode is the only path that calls detectAssetMode().
83
+ mode?: AssetMode;
84
+ nodeModulesDir?: string;
85
+ }
86
+
87
+ export interface OpenCodeSdkImportPlan {
88
+ readonly packageSpecifier: string;
89
+ readonly v2Specifier: string | undefined;
90
+ readonly packageJsonPath: string | undefined;
91
+ }
92
+
93
+ type DynamicImport = (specifier: string) => Promise<unknown>;
94
+
95
+ function createDynamicImport(): DynamicImport {
96
+ return new Function("specifier", "return import(specifier)") as DynamicImport;
97
+ }
98
+
99
+ function resolveOpenCodeSdkLocation(options?: {
100
+ mode?: AssetMode;
101
+ nodeModulesDir?: string;
102
+ }): { mode: AssetMode; nodeModulesDir: string } {
103
+ return {
104
+ mode: options?.mode ?? detectAssetMode(),
105
+ nodeModulesDir:
106
+ options?.nodeModulesDir ?? prheroLayout(os.homedir()).nodeModulesDir,
107
+ };
108
+ }
109
+
110
+ // Dev and npm keep bare specifiers. A compiled binary has no node_modules
111
+ // inside /$bunfs, so the package.json path is the product home and the v2
112
+ // entry is read from that file's exports — never a hardcoded dist path.
113
+ export function planOpenCodeSdkImport(input: {
114
+ mode: AssetMode;
115
+ nodeModulesDir: string;
116
+ }): OpenCodeSdkImportPlan {
117
+ if (input.mode !== "compiled") {
118
+ return {
119
+ packageSpecifier: OPENCODE_SDK_PACKAGE_SPECIFIER,
120
+ v2Specifier: OPENCODE_SDK_V2_SPECIFIER,
121
+ packageJsonPath: undefined,
122
+ };
123
+ }
124
+ const packageJsonPath = openCodeSdkPackageJsonPath(input.nodeModulesDir);
125
+ return {
126
+ packageSpecifier: pathToFileURL(packageJsonPath).href,
127
+ v2Specifier: undefined,
128
+ packageJsonPath,
129
+ };
130
+ }
131
+
132
+ function asPackageJson(module: unknown): OpenCodeSdkPackageMetadata {
133
+ if (typeof module !== "object" || module === null) return {};
134
+ const record = module as OpenCodeSdkPackageMetadata & { default?: unknown };
135
+ if (typeof record.version === "string" || record.exports !== undefined) {
136
+ return record;
137
+ }
138
+ if (typeof record.default === "object" && record.default !== null) {
139
+ return record.default as OpenCodeSdkPackageMetadata;
140
+ }
141
+ return record;
142
+ }
143
+
144
+ function normalizeSdkVersion(version: unknown): string | undefined {
145
+ if (typeof version !== "string") return undefined;
146
+ const trimmed = version.trim();
147
+ return trimmed === "" ? undefined : trimmed;
148
+ }
149
+
150
+ // `exports["./v2/client"]` is either a relative string or `{ import:
151
+ // relative }`. Resolved against the package directory, then imported as a
152
+ // file URL. Reading the CLIENT sub-path, not `"./v2"` — see the WHY comment
153
+ // on OPENCODE_SDK_V2_SPECIFIER above; the full index pulls in cross-spawn,
154
+ // which does not resolve inside a compiled binary.
155
+ export function resolveOpenCodeSdkV2Entry(
156
+ packageJson: { exports?: unknown },
157
+ packageDir: string,
158
+ ): string {
159
+ const relative = readOpenCodeV2Export(packageJson.exports);
160
+ if (relative === undefined) {
161
+ throw new OpenCodeSdkUnavailableError(openCodeSdkUnavailableMessage());
162
+ }
163
+ return pathToFileURL(path.resolve(packageDir, relative)).href;
164
+ }
165
+
166
+ function readOpenCodeV2Export(exportsField: unknown): string | undefined {
167
+ if (
168
+ typeof exportsField !== "object" ||
169
+ exportsField === null ||
170
+ Array.isArray(exportsField)
171
+ ) {
172
+ return undefined;
173
+ }
174
+ const v2Client = (exportsField as Record<string, unknown>)["./v2/client"];
175
+ if (typeof v2Client === "string" && v2Client.trim() !== "") return v2Client;
176
+ if (
177
+ typeof v2Client === "object" &&
178
+ v2Client !== null &&
179
+ !Array.isArray(v2Client)
180
+ ) {
181
+ const entry = (v2Client as Record<string, unknown>).import;
182
+ if (typeof entry === "string" && entry.trim() !== "") return entry;
183
+ }
184
+ return undefined;
185
+ }
186
+
187
+ interface LoadedOpenCodeSdkPackage {
188
+ version: unknown;
189
+ packageJson: OpenCodeSdkPackageMetadata;
190
+ packageDir: string;
191
+ plan: OpenCodeSdkImportPlan;
192
+ }
193
+
194
+ async function readPackageJsonAt(packageJsonPath: string): Promise<unknown> {
195
+ let text: string;
196
+ try {
197
+ text = await readFile(packageJsonPath, "utf8");
198
+ } catch (error) {
199
+ if (error instanceof OpenCodeSdkUnavailableError) throw error;
200
+ throw new OpenCodeSdkUnavailableError(openCodeSdkUnavailableMessage());
201
+ }
202
+ try {
203
+ return JSON.parse(text) as unknown;
204
+ } catch {
205
+ throw new OpenCodeSdkUnavailableError(openCodeSdkUnavailableMessage());
206
+ }
207
+ }
208
+
209
+ // Shared by the loader and the version reader so a compiled binary and
210
+ // doctor observe the same install.
211
+ async function readOpenCodeSdkPackage(
212
+ options: OpenCodeSdkLoadOptions | undefined,
213
+ dynamicImport: DynamicImport,
214
+ ): Promise<LoadedOpenCodeSdkPackage> {
215
+ const location = resolveOpenCodeSdkLocation(options);
216
+ let plan = planOpenCodeSdkImport(location);
217
+ const importSpecifier = options?.importSpecifier ?? dynamicImport;
218
+ let raw: unknown;
219
+ // Reconcile writes the pin under the product home in every asset mode.
220
+ // Dev and npm still try the bare specifier first, so a checkout or a
221
+ // global install wins. A known package.json is read from disk: import()
222
+ // caches a file URL for the process, so the post-install read would keep
223
+ // the pre-install version after npm overwrites the file.
224
+ if (options?.importPackage) {
225
+ try {
226
+ raw = await options.importPackage();
227
+ } catch (error) {
228
+ if (error instanceof OpenCodeSdkUnavailableError) throw error;
229
+ throw new OpenCodeSdkUnavailableError(openCodeSdkUnavailableMessage());
230
+ }
231
+ } else if (plan.packageJsonPath !== undefined) {
232
+ raw = await readPackageJsonAt(plan.packageJsonPath);
233
+ } else {
234
+ try {
235
+ raw = await importSpecifier(plan.packageSpecifier);
236
+ } catch (error) {
237
+ if (error instanceof OpenCodeSdkUnavailableError) throw error;
238
+ const packageJsonPath = openCodeSdkPackageJsonPath(
239
+ location.nodeModulesDir,
240
+ );
241
+ raw = await readPackageJsonAt(packageJsonPath);
242
+ plan = {
243
+ packageSpecifier: pathToFileURL(packageJsonPath).href,
244
+ v2Specifier: undefined,
245
+ packageJsonPath,
246
+ };
247
+ }
248
+ }
249
+ const packageJson = asPackageJson(raw);
250
+ return {
251
+ version: packageJson.version,
252
+ packageJson,
253
+ packageDir:
254
+ plan.packageJsonPath !== undefined
255
+ ? path.dirname(plan.packageJsonPath)
256
+ : "",
257
+ plan,
258
+ };
259
+ }
260
+
261
+ // ONE loader for both consumers (the transport factory and probeOpenCodeSdk),
262
+ // so the probe proves exactly what the factory will get. `new Function` keeps
263
+ // the import out of the static graph — the SDK is an OPTIONAL dependency and
264
+ // a Claude-only install must never be asked to resolve it — but the RESULT is
265
+ // now validated instead of `as unknown as OpenCodeSdkLike`-cast. That cast was
266
+ // the root cause of issue #121: it silenced the only compiler check that could
267
+ // have noticed the local interface named a factory the SDK does not export.
268
+ export async function loadOpenCodeSdk(
269
+ options?: OpenCodeSdkLoadOptions,
270
+ ): Promise<OpenCodeSdkLike> {
271
+ const dynamicImport = createDynamicImport();
272
+ const loaded = await readOpenCodeSdkPackage(options, dynamicImport);
273
+ const installedVersion = normalizeSdkVersion(loaded.version);
274
+ if (installedVersion === undefined) {
275
+ throw new OpenCodeSdkUnavailableError(openCodeSdkUnavailableMessage());
276
+ }
277
+ if (installedVersion !== SUPPORTED_OPENCODE_SDK_VERSION) {
278
+ throw new OpenCodeVersionAdmissionError(
279
+ `Unsupported OpenCode SDK version "${installedVersion}". Expected exact version "${SUPPORTED_OPENCODE_SDK_VERSION}".`,
280
+ );
281
+ }
282
+ if (options?.importSdk) {
283
+ return assertOpenCodeSdk(await options.importSdk());
284
+ }
285
+ const v2Specifier =
286
+ loaded.plan.v2Specifier ??
287
+ resolveOpenCodeSdkV2Entry(loaded.packageJson, loaded.packageDir);
288
+ let sdkModule: unknown;
289
+ try {
290
+ sdkModule = await dynamicImport(v2Specifier);
291
+ } catch (error) {
292
+ if (error instanceof OpenCodeSdkUnavailableError) throw error;
293
+ // The version check above already passed: the package IS installed, so
294
+ // this catch is a genuine IMPORT failure (e.g. a compiled binary unable
295
+ // to resolve cross-spawn's nested `require("which")`), never "not
296
+ // installed". openCodeSdkLoadFailedMessage keeps the real cause instead
297
+ // of collapsing it into the absence message below.
298
+ throw new OpenCodeSdkUnavailableError(
299
+ openCodeSdkLoadFailedMessage(v2Specifier, error),
300
+ );
301
+ }
302
+ return assertOpenCodeSdk(sdkModule);
303
+ }
304
+
305
+ export async function readInstalledOpenCodeSdkVersion(options?: {
306
+ mode?: AssetMode;
307
+ nodeModulesDir?: string;
308
+ importPackage?: OpenCodeSdkLoadOptions["importPackage"];
309
+ importSpecifier?: OpenCodeSdkLoadOptions["importSpecifier"];
310
+ }): Promise<string | undefined> {
311
+ try {
312
+ const loaded = await readOpenCodeSdkPackage(options, createDynamicImport());
313
+ return normalizeSdkVersion(loaded.version);
314
+ } catch {
315
+ return undefined;
316
+ }
317
+ }
318
+
319
+ export class RouteAdmissionError extends Error {}
320
+
321
+ export const SUPPORTED_OPENCODE_SDK_VERSION = "1.18.25" as const;
322
+ export const SUPPORTED_OPENCODE_SERVER_VERSION = "1.18.30" as const;
323
+
324
+ // WHY a reason: this one class covers two refusals with different causes. "version"
325
+ // is a pinned pair the runtime does not match, and it is the default. "identity" is an
326
+ // observed runtime identity that production cannot establish, or one the declared
327
+ // versions contradict. Naming that a version mismatch would point at the wrong cause,
328
+ // so the CLI's classifier reads the reason (src/ci/classify-error.ts).
329
+ export class OpenCodeVersionAdmissionError extends RouteAdmissionError {
330
+ readonly reason: "version" | "identity";
331
+
332
+ constructor(message: string, reason: "version" | "identity" = "version") {
333
+ super(message);
334
+ this.name = "OpenCodeVersionAdmissionError";
335
+ this.reason = reason;
336
+ }
337
+ }
338
+
339
+ export function admitOpenCodeVersionPair(pair: {
340
+ readonly sdkVersion?: unknown;
341
+ readonly serverVersion?: unknown;
342
+ }): {
343
+ readonly sdkVersion: typeof SUPPORTED_OPENCODE_SDK_VERSION;
344
+ readonly serverVersion: typeof SUPPORTED_OPENCODE_SERVER_VERSION;
345
+ } {
346
+ const { sdkVersion, serverVersion } = pair;
347
+ if (typeof sdkVersion !== "string" || sdkVersion.trim() === "") {
348
+ throw new OpenCodeVersionAdmissionError(
349
+ `OpenCode SDK version is malformed or missing (got ${JSON.stringify(sdkVersion)}). Required exact version is "${SUPPORTED_OPENCODE_SDK_VERSION}".`,
350
+ );
351
+ }
352
+ if (typeof serverVersion !== "string" || serverVersion.trim() === "") {
353
+ throw new OpenCodeVersionAdmissionError(
354
+ `OpenCode server version is malformed or missing (got ${JSON.stringify(serverVersion)}). Required exact version is "${SUPPORTED_OPENCODE_SERVER_VERSION}".`,
355
+ );
356
+ }
357
+ if (
358
+ sdkVersion !== SUPPORTED_OPENCODE_SDK_VERSION ||
359
+ serverVersion !== SUPPORTED_OPENCODE_SERVER_VERSION
360
+ ) {
361
+ throw new OpenCodeVersionAdmissionError(
362
+ `Unsupported OpenCode version pair: SDK "${sdkVersion}" and server "${serverVersion}". ` +
363
+ `Only SDK "${SUPPORTED_OPENCODE_SDK_VERSION}" and server "${SUPPORTED_OPENCODE_SERVER_VERSION}" are admitted. ` +
364
+ "Auto-upgrade, fallback, and version inference are denied.",
365
+ );
366
+ }
367
+ return {
368
+ sdkVersion: SUPPORTED_OPENCODE_SDK_VERSION,
369
+ serverVersion: SUPPORTED_OPENCODE_SERVER_VERSION,
370
+ };
371
+ }
372
+
373
+ export class OpenCodeProductionGatedError extends RouteAdmissionError {
374
+ readonly missingPrerequisites: readonly string[];
375
+
376
+ constructor(missingPrerequisites: readonly string[] = []) {
377
+ const details =
378
+ missingPrerequisites.length > 0
379
+ ? `: missing D1-11 prerequisites: ${missingPrerequisites.join(", ")}`
380
+ : "";
381
+ super(
382
+ `OpenCode runner backend is gated in production mode until all D1-11 readiness evidence is met${details}.`,
383
+ );
384
+ this.name = "OpenCodeProductionGatedError";
385
+ this.missingPrerequisites = missingPrerequisites;
386
+ }
387
+ }
388
+
389
+ export interface D1_11ReadinessEvidence {
390
+ readonly sdkAvailable: boolean;
391
+ readonly credentialAuthority: boolean;
392
+ readonly workspaceBroker: boolean;
393
+ readonly pricingReady: boolean;
394
+ readonly issues?: readonly {
395
+ code: string;
396
+ message: string;
397
+ blocking: boolean;
398
+ }[];
399
+ }
400
+
401
+ export interface D1_11ReadinessResult {
402
+ readonly ready: boolean;
403
+ readonly missing: readonly string[];
404
+ }
405
+
406
+ export function checkD1_11Readiness(
407
+ evidence?: D1_11ReadinessEvidence | ProviderCapabilityReport,
408
+ ): D1_11ReadinessResult {
409
+ if (!evidence) {
410
+ return {
411
+ ready: false,
412
+ missing: [
413
+ "sdkAvailable",
414
+ "credentialAuthority",
415
+ "workspaceBroker",
416
+ "pricingReady",
417
+ ],
418
+ };
419
+ }
420
+
421
+ const missing: string[] = [];
422
+
423
+ // Check if evidence is a ProviderCapabilityReport
424
+ if ("auth" in evidence && "isolation" in evidence && "billing" in evidence) {
425
+ const report = evidence as ProviderCapabilityReport;
426
+ if (!report.auth.projectionReady) {
427
+ missing.push("credentialAuthority");
428
+ }
429
+ if (!report.isolation.workspaceReadBroker) {
430
+ missing.push("workspaceBroker");
431
+ }
432
+ if (!report.billing.pricingReady) {
433
+ missing.push("pricingReady");
434
+ }
435
+ const hasDeferredSdkIssue = (report.issues ?? []).some(
436
+ (i) => i.code === "real_sdk_adapter_deferred_to_d1_11",
437
+ );
438
+ if (hasDeferredSdkIssue) {
439
+ missing.push("sdkAvailable");
440
+ }
441
+ } else {
442
+ const d1Evidence = evidence as D1_11ReadinessEvidence;
443
+ if (!d1Evidence.sdkAvailable) {
444
+ missing.push("sdkAvailable");
445
+ }
446
+ if (!d1Evidence.credentialAuthority) {
447
+ missing.push("credentialAuthority");
448
+ }
449
+ if (!d1Evidence.workspaceBroker) {
450
+ missing.push("workspaceBroker");
451
+ }
452
+ if (!d1Evidence.pricingReady) {
453
+ missing.push("pricingReady");
454
+ }
455
+ }
456
+
457
+ return {
458
+ ready: missing.length === 0,
459
+ missing,
460
+ };
461
+ }
462
+
463
+ export interface TransportFactoryOptions {
464
+ readonly spawnFn?: typeof Bun.spawn;
465
+ readonly openCodeClient?: OpenCodeClientLike;
466
+ readonly loadSdk?: () => Promise<OpenCodeSdkLike>;
467
+ // Free-tier gateway fix: widened to the same two-parameter signature as
468
+ // `CreateOpenCodeClientOptions.launchServer` (opencode-client.ts) so an
469
+ // injector here sees the second parameter exists — an injected launcher
470
+ // that ignores it entirely still type-checks (fewer declared parameters
471
+ // is a valid JS callback shape), which is exactly why createSession's own
472
+ // attestation check exists: the type alone cannot force a launcher to
473
+ // honour this argument, only createSession's runtime check can.
474
+ readonly launchServer?: (
475
+ mcp?: OpenCodeMcpConfig,
476
+ freeTierGatewayAsk?: readonly string[],
477
+ ) => Promise<OpenCodeServerHandle>;
478
+ readonly readSystemPrompt?: (path: string) => Promise<string>;
479
+ readonly readMcpConfig?: (path: string) => Promise<string>;
480
+ readonly binaryPath?: string;
481
+ readonly openCodeBinaryPath?: string;
482
+ // #141: absolute, and resolved HERE rather than inside the client. The
483
+ // client is the wrong place for a PATH lookup — the same rule
484
+ // opencode-server.ts states for the opencode binary itself — and the
485
+ // launcher-side default below keeps the operator's override on the same
486
+ // option path as every other binary this registry hands out.
487
+ readonly codegraphBinaryPath?: string;
488
+ // #161: matches `RunnerAuthorityOptions.env`'s widened shape (it flows in
489
+ // from there) and `baseEnv` below, which already accepted `string |
490
+ // undefined` values — `process.env` itself is typed this way, and this
491
+ // was the narrower link in that chain.
492
+ readonly env?: Readonly<Record<string, string | undefined>>;
493
+ // #149: the credential broker the authority resolved for the opencode
494
+ // backend. The server runs under its projection for the servers whole life.
495
+ readonly credentialBroker?: CredentialBroker;
496
+ // #133: the KIND that broker was resolved for. Travels beside it and is
497
+ // only ever meaningful as a pair — see openCodeLaunchServerFor.
498
+ readonly credentialKind?: CredentialKind;
499
+ readonly evidence?: Map<RunnerBackend, D1_11ReadinessEvidence>;
500
+ readonly mode?: "production" | "conformance";
501
+ readonly routeFingerprint?: string;
502
+ readonly route?: ResolvedModelRoute;
503
+ readonly observedOpenCodeIdentity?: OpenCodeObservedIdentity;
504
+ readonly sdkVersion?: string;
505
+ readonly serverVersion?: string;
506
+ readonly openCodeServerVersion?: string;
507
+ [key: string]: unknown;
508
+ }
509
+
510
+ export type TransportFactory = (
511
+ options?: TransportFactoryOptions,
512
+ ) => ProviderTransport | Promise<ProviderTransport>;
513
+
514
+ export interface TransportRegistry {
515
+ register(
516
+ backend: RunnerBackend,
517
+ factoryOrInstance: ProviderTransport | TransportFactory,
518
+ ): void;
519
+ get(
520
+ backend: RunnerBackend,
521
+ options?: TransportFactoryOptions,
522
+ ): ProviderTransport;
523
+ has(backend: RunnerBackend): boolean;
524
+ getCapabilityReport(
525
+ backend: RunnerBackend,
526
+ options?: TransportFactoryOptions,
527
+ ): Promise<ProviderCapabilityReport>;
528
+ getAllCapabilityReports(
529
+ options?: TransportFactoryOptions,
530
+ ): Promise<Map<RunnerBackend, ProviderCapabilityReport>>;
531
+ release?(routeFingerprint: string): void;
532
+ }
533
+
534
+ export interface CreateTransportRegistryOptions
535
+ extends TransportFactoryOptions {
536
+ readonly mode?: "production" | "conformance";
537
+ }
538
+
539
+ export class DefaultTransportRegistry implements TransportRegistry {
540
+ private readonly factories = new Map<
541
+ RunnerBackend,
542
+ ProviderTransport | TransportFactory
543
+ >();
544
+ private readonly instances = new Map<RunnerBackend, ProviderTransport>();
545
+ private readonly routeInstances = new Map<string, ProviderTransport>();
546
+ private readonly userOverriddenBackends = new Set<RunnerBackend>();
547
+ private readonly defaultOptions: TransportFactoryOptions;
548
+
549
+ // #149: read-only, and it exists for exactly one reason — the invariant that
550
+ // the server launcher and the binding authority share ONE broker instance
551
+ // was unobservable from outside, which is how the forwarding that claimed to
552
+ // guarantee it shipped dead. Identity here is the assertion.
553
+ get openCodeCredentialBroker(): CredentialBroker | undefined {
554
+ return this.defaultOptions.credentialBroker;
555
+ }
556
+
557
+ // #133: the same reason, for the other half of the pair. The kind travels
558
+ // beside the broker and decides which credential the server projects; a
559
+ // fallback that silently dropped it would be unobservable from outside, and
560
+ // an unobservable invariant is how the #149 forwarding shipped dead twice.
561
+ get openCodeCredentialKind(): CredentialKind | undefined {
562
+ return this.defaultOptions.credentialKind;
563
+ }
564
+
565
+ constructor(options: CreateTransportRegistryOptions = {}) {
566
+ this.defaultOptions = { ...options };
567
+
568
+ // Register Claude CLI transport factory
569
+ this.register("claude-code", (opts) => {
570
+ const merged = { ...this.defaultOptions, ...opts };
571
+ return new ClaudeCodeCliTransport({
572
+ spawnFn: merged.spawnFn,
573
+ });
574
+ });
575
+
576
+ // Register OpenCode transport factory with D1-11 gate
577
+ this.register("opencode", (opts) => {
578
+ const merged = { ...this.defaultOptions, ...opts };
579
+ const mode = merged.mode ?? "production";
580
+ const evidence = merged.evidence?.get("opencode");
581
+
582
+ // Check D1-11 readiness in production mode
583
+ if (mode === "production") {
584
+ const readiness = checkD1_11Readiness(evidence);
585
+ if (!readiness.ready) {
586
+ throw new OpenCodeProductionGatedError(readiness.missing);
587
+ }
588
+ }
589
+
590
+ // Check bounded version admission policy (OA1b / U1-C1)
591
+ const observed = merged.observedOpenCodeIdentity;
592
+ if (mode === "production" && observed === undefined) {
593
+ throw new OpenCodeVersionAdmissionError(
594
+ "Observed OpenCode identity is required in production",
595
+ "identity",
596
+ );
597
+ }
598
+ admitOpenCodeVersionPair(
599
+ observed ?? {
600
+ sdkVersion: merged.sdkVersion,
601
+ serverVersion: merged.serverVersion ?? merged.openCodeServerVersion,
602
+ },
603
+ );
604
+ if (
605
+ observed !== undefined &&
606
+ ((merged.sdkVersion !== undefined &&
607
+ merged.sdkVersion !== observed.sdkVersion) ||
608
+ (merged.serverVersion !== undefined &&
609
+ merged.serverVersion !== observed.serverVersion))
610
+ ) {
611
+ throw new OpenCodeVersionAdmissionError(
612
+ "Declared OpenCode versions contradict observed identity",
613
+ "identity",
614
+ );
615
+ }
616
+
617
+ // 2026-09-02: the billing mode stamped on every usage record this
618
+ // transport emits, derived from the credential kind the authority
619
+ // resolved.
620
+ //
621
+ // WHY it cannot disagree with the exact-binding report, stated as the
622
+ // mechanism rather than as a hope — because the first version of this
623
+ // comment claimed the guarantee and the code did not make it. The
624
+ // report's `effectiveBillingMode` reads `binding.credential.kind`
625
+ // (production-runtime.ts), and `FrozenRuntimeBinding.acquire()` now
626
+ // forwards THAT SAME field into `options.credentialKind` on the `get()`
627
+ // that builds this transport. One fact, one source, and
628
+ // `credentialKindBillsMetered` is the single predicate both sides apply
629
+ // to it (#133) — so the two are structurally incapable of diverging.
630
+ //
631
+ // What the old wording got wrong: "THE factory is the only place that
632
+ // holds both the kind and the transport" was true, and irrelevant, when
633
+ // the kind could only arrive from construction-time `defaultOptions`.
634
+ // Every caller of the public `createProductionRuntime` that supplies
635
+ // its own registry bypasses the only wiring that sets it
636
+ // (`productionFallbackRegistry`), so a metered route's records were
637
+ // stamped "subscription" — which makes `settlementFromUsage`'s
638
+ // metered-zero rule dead and lets an unaccountable provider $0 settle
639
+ // as a truthful cost. `defaultOptions.credentialKind` is now the
640
+ // FALLBACK for callers holding no binding; `get()`'s merge order
641
+ // (`{ ...defaultOptions, ...options }`) lets the per-binding value win.
642
+ //
643
+ // Computed once, above both construction branches — wiring only the
644
+ // second is how the injected-client path (every test and every doctor
645
+ // probe) would keep the pre-#133 default.
646
+ //
647
+ // #182 follow-up: a `provider_free` kind stamps "free", checked BEFORE
648
+ // the metered test (`credentialKindBillsMetered` is false for free, so
649
+ // order is what keeps the stamp exact). Everything downstream passes the
650
+ // mode through generically — the transport stamps it onto every usage
651
+ // record (incl. `noSessionUsage`, which stays settleable at 0 with empty
652
+ // tokens) and `settlementFromUsage`'s free-nonzero rule reads it.
653
+ const usageBillingMode: UsageBillingMode =
654
+ merged.credentialKind === "provider_free"
655
+ ? "free"
656
+ : merged.credentialKind !== undefined &&
657
+ credentialKindBillsMetered(merged.credentialKind)
658
+ ? "metered"
659
+ : "subscription";
660
+
661
+ const route = merged.route;
662
+ const admissionIdentity = {
663
+ executable: "opencode",
664
+ provider: route?.provider ?? "opencode",
665
+ };
666
+ const defaultRoute: ResolvedModelRoute | undefined = route;
667
+
668
+ if (merged.openCodeClient) {
669
+ return new OpenCodeSdkTransport({
670
+ client: merged.openCodeClient,
671
+ billingMode: usageBillingMode,
672
+ admissionIdentity,
673
+ defaultRoute,
674
+ });
675
+ }
676
+
677
+ // Resolved ONCE per client, before the options object is built: the
678
+ // lookup hits the filesystem, and a spread that called it twice would
679
+ // pay for it twice for one value.
680
+ const codegraphBinaryPath =
681
+ merged.codegraphBinaryPath ?? Bun.which("codegraph") ?? undefined;
682
+ const client = createOpenCodeClient({
683
+ // Free-tier gateway fix: the ONLY thing createSession reads this for
684
+ // is gating FREE_TIER_GATEWAY_TOOLS (opencode-client.ts) — the same
685
+ // per-route value `usageBillingMode` above and `openCodeLaunchServerFor`
686
+ // below already read, so all three agree by construction.
687
+ ...(merged.credentialKind === undefined
688
+ ? {}
689
+ : { credentialKind: merged.credentialKind }),
690
+ ...(observed ? { observedIdentity: observed } : {}),
691
+ ...(observed === undefined
692
+ ? {}
693
+ : {
694
+ qualifyServer: (url: string, signal?: AbortSignal) =>
695
+ qualifyOpenCodeServer(url, observed, signal),
696
+ }),
697
+ model: route
698
+ ? {
699
+ providerID: route.provider,
700
+ modelID: route.modelSnapshot,
701
+ ...(route.modelVariant !== undefined
702
+ ? { variant: route.modelVariant }
703
+ : {}),
704
+ }
705
+ : {
706
+ providerID: "openai",
707
+ modelID: "gpt-4o",
708
+ },
709
+ ...(route?.modelVariant !== undefined
710
+ ? { variant: route.modelVariant }
711
+ : {}),
712
+ loadSdk: merged.loadSdk ?? loadOpenCodeSdk,
713
+ launchServer: merged.launchServer ?? openCodeLaunchServerFor(merged),
714
+ readSystemPrompt:
715
+ merged.readSystemPrompt ??
716
+ (async (filePath: string) => {
717
+ return await readFile(filePath, "utf8");
718
+ }),
719
+ // #141: the SAME mcp.json `binding-policy.ts` already validates —
720
+ // not a second, OpenCode-shaped registry the integrity gate would
721
+ // never see. The path arrives on the request; this only reads it.
722
+ readMcpConfig:
723
+ merged.readMcpConfig ??
724
+ (async (filePath: string) => {
725
+ return await readFile(filePath, "utf8");
726
+ }),
727
+ // An unresolved binary is carried through as "unresolved" rather than
728
+ // refused here: the translation is the only place that knows whether a
729
+ // codegraph binary was needed at all. A repo with no index needs none,
730
+ // and refusing to build a client for it would break the parity case
731
+ // #116's ledger recorded as correct.
732
+ ...(codegraphBinaryPath === undefined ? {} : { codegraphBinaryPath }),
733
+ });
734
+
735
+ return new OpenCodeSdkTransport({
736
+ client,
737
+ billingMode: usageBillingMode,
738
+ admissionIdentity,
739
+ defaultRoute,
740
+ });
741
+ });
742
+ }
743
+
744
+ register(
745
+ backend: RunnerBackend,
746
+ factoryOrInstance: ProviderTransport | TransportFactory,
747
+ ): void {
748
+ if (this.factories.has(backend)) {
749
+ this.userOverriddenBackends.add(backend);
750
+ }
751
+ this.factories.set(backend, factoryOrInstance);
752
+ this.instances.delete(backend);
753
+ for (const key of [...this.routeInstances.keys()]) {
754
+ if (key.startsWith(`${backend}:`)) {
755
+ this.routeInstances.delete(key);
756
+ }
757
+ }
758
+ }
759
+
760
+ private routeCacheKey(
761
+ backend: RunnerBackend,
762
+ routeFingerprint: string,
763
+ ): string {
764
+ return `${backend}:${routeFingerprint}`;
765
+ }
766
+
767
+ async probeOpenCodeSdk(): Promise<void> {
768
+ const loadSdk = this.defaultOptions.loadSdk ?? loadOpenCodeSdk;
769
+ await loadSdk();
770
+ }
771
+
772
+ needsOpenCodeSdkProbe(): boolean {
773
+ return !this.userOverriddenBackends.has("opencode");
774
+ }
775
+
776
+ release(routeFingerprint: string): void {
777
+ for (const key of [...this.routeInstances.keys()]) {
778
+ if (key.endsWith(`:${routeFingerprint}`)) {
779
+ this.routeInstances.delete(key);
780
+ }
781
+ }
782
+ }
783
+
784
+ has(backend: RunnerBackend): boolean {
785
+ return this.factories.has(backend);
786
+ }
787
+
788
+ get(
789
+ backend: RunnerBackend,
790
+ options?: TransportFactoryOptions,
791
+ ): ProviderTransport {
792
+ if (options?.routeFingerprint !== undefined) {
793
+ const routeKey = this.routeCacheKey(backend, options.routeFingerprint);
794
+ const routeCached = this.routeInstances.get(routeKey);
795
+ if (routeCached !== undefined) {
796
+ return routeCached;
797
+ }
798
+ } else if (!options) {
799
+ const cached = this.instances.get(backend);
800
+ if (cached !== undefined) {
801
+ return cached;
802
+ }
803
+ }
804
+ const entry = this.factories.get(backend);
805
+ if (!entry) {
806
+ throw new RouteAdmissionError(
807
+ redactDiagnostic(`No transport registered for backend "${backend}"`),
808
+ );
809
+ }
810
+ if (typeof entry === "function") {
811
+ const merged = { ...this.defaultOptions, ...options };
812
+ const instance = (entry as TransportFactory)(merged);
813
+ if (instance instanceof Promise) {
814
+ throw new RouteAdmissionError(
815
+ `Async transport factory for backend "${backend}" cannot be resolved synchronously in get()`,
816
+ );
817
+ }
818
+ if (options?.routeFingerprint !== undefined) {
819
+ const routeKey = this.routeCacheKey(backend, options.routeFingerprint);
820
+ this.routeInstances.set(routeKey, instance);
821
+ } else if (!options) {
822
+ this.instances.set(backend, instance);
823
+ }
824
+ return instance;
825
+ }
826
+ if (options?.routeFingerprint !== undefined) {
827
+ const routeKey = this.routeCacheKey(backend, options.routeFingerprint);
828
+ this.routeInstances.set(routeKey, entry);
829
+ } else if (!options) {
830
+ this.instances.set(backend, entry);
831
+ }
832
+ return entry;
833
+ }
834
+
835
+ async getCapabilityReport(
836
+ backend: RunnerBackend,
837
+ options?: TransportFactoryOptions,
838
+ ): Promise<ProviderCapabilityReport> {
839
+ const transport = this.get(backend, options);
840
+ return await transport.capabilities();
841
+ }
842
+
843
+ async getAllCapabilityReports(
844
+ options?: TransportFactoryOptions,
845
+ ): Promise<Map<RunnerBackend, ProviderCapabilityReport>> {
846
+ const reports = new Map<RunnerBackend, ProviderCapabilityReport>();
847
+ for (const backend of this.factories.keys()) {
848
+ try {
849
+ const report = await this.getCapabilityReport(backend, options);
850
+ reports.set(backend, report);
851
+ } catch (err) {
852
+ if (err instanceof OpenCodeProductionGatedError) {
853
+ reports.set(backend, {
854
+ backend,
855
+ status: "blocking",
856
+ auth: {
857
+ kind: "opencode_chatgpt_oauth",
858
+ projectionReady: false,
859
+ probe: "not_run",
860
+ },
861
+ isolation: {
862
+ syntheticHome: false,
863
+ workspaceReadBroker: false,
864
+ codegraphPolicy: false,
865
+ },
866
+ protocol: {
867
+ terminalProof: true,
868
+ boundedEvents: true,
869
+ usageMode: "none",
870
+ },
871
+ cancellation: {
872
+ deadlineMs: 6500,
873
+ conformance: "passed",
874
+ },
875
+ billing: {
876
+ mode: "subscription",
877
+ // #137 leaves this hardcoded: no model id is in scope. This is
878
+ // the synthetic report for a backend whose transport could not
879
+ // be CONSTRUCTED (OpenCodeProductionGatedError), so there is no
880
+ // route, no client and no model behind it — and the report is
881
+ // already blocking on `d1_11_production_gated`.
882
+ //
883
+ // 2026-09-02: NOT the case the OpenCode transport's `true`
884
+ // covers. That claim is a TRANSPORT reporting the provider cost
885
+ // it reads off each assistant message; here there is no
886
+ // transport to make the claim, so `false` is the only honest
887
+ // answer and stays one.
888
+ pricingReady: false,
889
+ },
890
+ issues: [
891
+ {
892
+ code: "d1_11_production_gated",
893
+ message: err.message,
894
+ blocking: true,
895
+ },
896
+ ],
897
+ });
898
+ } else {
899
+ throw err;
900
+ }
901
+ }
902
+ }
903
+ return reports;
904
+ }
905
+ }
906
+
907
+ export function createDefaultTransportRegistry(
908
+ options: CreateTransportRegistryOptions = {},
909
+ ): TransportRegistry {
910
+ return new DefaultTransportRegistry(options);
911
+ }
912
+
913
+ export interface AdmitRoutePlanOptions {
914
+ readonly mode?: "production" | "conformance";
915
+ readonly evidence?: Map<RunnerBackend, D1_11ReadinessEvidence>;
916
+ readonly capabilities?:
917
+ | ProviderCapabilityReport
918
+ | Map<RunnerBackend, ProviderCapabilityReport>;
919
+ }
920
+
921
+ export interface AdmittedRoutePlanResult {
922
+ readonly ok: true;
923
+ readonly plan: ResolvedRoutePlan;
924
+ readonly admittedSteps: readonly ResolvedStepRoute[];
925
+ readonly reports: ReadonlyMap<RunnerBackend, ProviderCapabilityReport>;
926
+ }
927
+
928
+ export async function admitRoutePlan(
929
+ plan: ResolvedRoutePlan,
930
+ registryOrCapabilities:
931
+ | TransportRegistry
932
+ | ProviderCapabilityReport
933
+ | Map<RunnerBackend, ProviderCapabilityReport>,
934
+ optionsOrRegistry?: TransportRegistry | AdmitRoutePlanOptions,
935
+ maybeOptions?: AdmitRoutePlanOptions,
936
+ ): Promise<AdmittedRoutePlanResult> {
937
+ let registry: TransportRegistry;
938
+ let options: AdmitRoutePlanOptions;
939
+
940
+ const isRegistry = (obj: unknown): obj is TransportRegistry => {
941
+ return (
942
+ typeof obj === "object" &&
943
+ obj !== null &&
944
+ !(obj instanceof Map) &&
945
+ !("backend" in obj) &&
946
+ "get" in obj &&
947
+ typeof (obj as TransportRegistry).get === "function"
948
+ );
949
+ };
950
+
951
+ if (isRegistry(registryOrCapabilities)) {
952
+ registry = registryOrCapabilities;
953
+ options = (optionsOrRegistry as AdmitRoutePlanOptions) ?? {};
954
+ } else {
955
+ // Signature: admitRoutePlan(plan, capabilities, registry?, options?)
956
+ if (isRegistry(optionsOrRegistry)) {
957
+ registry = optionsOrRegistry;
958
+ options = {
959
+ ...(maybeOptions ?? {}),
960
+ capabilities: registryOrCapabilities,
961
+ };
962
+ } else {
963
+ registry = new DefaultTransportRegistry();
964
+ options = {
965
+ capabilities: registryOrCapabilities,
966
+ ...((optionsOrRegistry as AdmitRoutePlanOptions) ?? {}),
967
+ };
968
+ }
969
+ }
970
+
971
+ const reports = new Map<RunnerBackend, ProviderCapabilityReport>();
972
+ const mode = options.mode ?? "production";
973
+
974
+ for (const step of plan.steps) {
975
+ const backend = step.route.backend;
976
+
977
+ if (!registry.has(backend)) {
978
+ throw new RouteAdmissionError(
979
+ redactDiagnostic(
980
+ `Step "${step.stepKey}" route backend "${backend}" is not registered`,
981
+ ),
982
+ );
983
+ }
984
+
985
+ // Check OpenCode D1-11 gate in production mode
986
+ if (backend === "opencode") {
987
+ const evidence = options.evidence?.get("opencode");
988
+ if (mode === "production") {
989
+ const readiness = checkD1_11Readiness(evidence);
990
+ if (!readiness.ready) {
991
+ throw new OpenCodeProductionGatedError(readiness.missing);
992
+ }
993
+ }
994
+ }
995
+
996
+ // Get and validate capability report
997
+ let report: ProviderCapabilityReport | undefined;
998
+ if (options.capabilities) {
999
+ if ("backend" in options.capabilities) {
1000
+ if (options.capabilities.backend === backend) {
1001
+ report = options.capabilities;
1002
+ }
1003
+ } else if (options.capabilities instanceof Map) {
1004
+ report = options.capabilities.get(backend);
1005
+ }
1006
+ }
1007
+
1008
+ if (!report) {
1009
+ report = await registry.getCapabilityReport(backend, {
1010
+ mode,
1011
+ evidence: options.evidence,
1012
+ });
1013
+ }
1014
+
1015
+ reports.set(backend, report);
1016
+
1017
+ const gate = capabilityGateDecision(report);
1018
+ if (!gate.ok) {
1019
+ throw new RouteAdmissionError(
1020
+ redactDiagnostic(
1021
+ `Step "${step.stepKey}" route backend "${backend}" rejected by capability gate: ${gate.reason}`,
1022
+ ),
1023
+ );
1024
+ }
1025
+ }
1026
+
1027
+ return {
1028
+ ok: true,
1029
+ plan,
1030
+ admittedSteps: plan.steps,
1031
+ reports,
1032
+ };
1033
+ }
1034
+
1035
+ export async function admitDiversityRoutePlan(
1036
+ plan: ResolvedRoutePlan,
1037
+ registryOrCapabilities: Parameters<typeof admitRoutePlan>[1],
1038
+ optionsOrRegistry?: Parameters<typeof admitRoutePlan>[2],
1039
+ maybeOptions?: Parameters<typeof admitRoutePlan>[3],
1040
+ ): Promise<AdmittedRoutePlanResult> {
1041
+ const { requireInternalFindingsCapability } = await import(
1042
+ "./diversity/admission"
1043
+ );
1044
+ requireInternalFindingsCapability();
1045
+ return admitRoutePlan(
1046
+ plan,
1047
+ registryOrCapabilities,
1048
+ optionsOrRegistry,
1049
+ maybeOptions,
1050
+ );
1051
+ }
1052
+
1053
+ // #149: the launcher the registry hands out when the caller injects none.
1054
+ // Named and exported because it is the ONLY place production chooses the
1055
+ // opencode server environment, and every existing test injects `launchServer`
1056
+ // instead — so an inline closure here was, by construction, untested.
1057
+ export function defaultOpenCodeLaunchServer(options: {
1058
+ readonly verifiedBinaryPath: string;
1059
+ readonly broker: CredentialBroker;
1060
+ readonly credentialKind: CredentialKind;
1061
+ readonly baseEnv?: Readonly<Record<string, string | undefined>>;
1062
+ readonly spawnFn?: typeof Bun.spawn;
1063
+ readonly killFn?: (pid: number, signal?: string | number) => unknown;
1064
+ }): (
1065
+ mcp?: OpenCodeMcpConfig,
1066
+ freeTierGatewayAsk?: readonly string[],
1067
+ ) => Promise<OpenCodeServerHandle> {
1068
+ return async (
1069
+ mcp?: OpenCodeMcpConfig,
1070
+ freeTierGatewayAsk?: readonly string[],
1071
+ ) => {
1072
+ return await launchProjectedOpenCodeServer({
1073
+ ...options,
1074
+ // #141: the run’s registry rides the SPAWN. OpenCode reads
1075
+ // `OPENCODE_CONFIG_CONTENT` at startup, so a server already running
1076
+ // cannot be given one without opening a window between "server up" and
1077
+ // "MCP connected".
1078
+ ...(mcp === undefined ? {} : { mcp }),
1079
+ // Free-tier gateway fix: same reason, same spawn-time constraint — see
1080
+ // opencode-client.ts's FREE_TIER_GATEWAY_TOOLS and opencode-server.ts's
1081
+ // launchOpenCodeServer for the full WHY.
1082
+ ...(freeTierGatewayAsk === undefined ? {} : { freeTierGatewayAsk }),
1083
+ });
1084
+ };
1085
+ }
1086
+
1087
+ // #149: how the registry turns its options into a launcher. Split out from the
1088
+ // factory so the WIRING is reachable from a test — the factory itself only
1089
+ // hands `launchServer` to the client, and every existing test injects one,
1090
+ // which is how the previous inline closure went untested for its whole life.
1091
+ export function openCodeLaunchServerFor(
1092
+ merged: TransportFactoryOptions,
1093
+ ): (
1094
+ mcp?: OpenCodeMcpConfig,
1095
+ freeTierGatewayAsk?: readonly string[],
1096
+ ) => Promise<OpenCodeServerHandle> {
1097
+ return defaultOpenCodeLaunchServer({
1098
+ verifiedBinaryPath:
1099
+ merged.openCodeBinaryPath ??
1100
+ merged.binaryPath ??
1101
+ "/usr/local/bin/opencode",
1102
+ // The same broker the credential authority resolved for this backend.
1103
+ // Defaulting a second instance here would be a second source of truth
1104
+ // beside runner-authority.ts, and a caller injecting a fake at the
1105
+ // authority would silently get a real one at the server.
1106
+ broker: merged.credentialBroker ?? new OpenCodeAuthBroker(),
1107
+ // #133: the kind the authority resolved for that broker. The default
1108
+ // below is the OAuth kind because the default BROKER on the line above is
1109
+ // the OAuth broker — the pair is only ever defaulted together, here.
1110
+ //
1111
+ // The one case where they intentionally MISMATCH: a caller that supplies
1112
+ // a metered `credentialKind` but no broker gets the OAuth default, which
1113
+ // then refuses `provider_api_token` by name. That is deliberate. #149's
1114
+ // invariant is that an absent broker stays absent rather than being
1115
+ // silently stood in for, so the honest outcome is a loud refusal, not a
1116
+ // guess — and never the reverse, an OAuth record projected under a
1117
+ // metered route.
1118
+ credentialKind: merged.credentialKind ?? "opencode_chatgpt_oauth",
1119
+ // pr-hero own environment, filtered to operational keys only. The
1120
+ // projection owns HOME/TMPDIR/XDG_* and overrides whatever survives;
1121
+ // see composeOpenCodeServerEnv.
1122
+ baseEnv: merged.env ?? process.env,
1123
+ });
1124
+ }