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,3328 @@
1
+ import { OpenCodeEvidenceCollector } from "./opencode-evidence";
2
+ // D1-06: the mapping between what @opencode-ai/sdk actually emits and the
3
+ // narrow `OpenCodeClientLike` contract the transport was built against.
4
+ //
5
+ // Everything here is derived from a recorded live probe
6
+ // (scripts/opencode-probe.ts), not from the SDK's type declarations: the
7
+ // declared Event union has 32 members and answers none of the questions that
8
+ // decide this mapping. The full findings, including the three traps encoded
9
+ // below, are in docs/research/opencode-adapter-mapping.md.
10
+ //
11
+ // This module is PURE. The impure half — spawning a server with the projected
12
+ // credential environment and a verified absolute binary — is a separate slice,
13
+ // because the SDK's own `createOpencodeServer` cannot be used for it: it
14
+ // inherits process.env wholesale and resolves the binary off PATH, so it would
15
+ // defeat both the credential projection (§6.1) and the verified-binary rule
16
+ // (§13).
17
+
18
+ import { realpathSync } from "node:fs";
19
+ import { resolve } from "node:path";
20
+ import type {
21
+ CredentialKind,
22
+ ProviderTerminalProof,
23
+ } from "../execution/contracts";
24
+ import {
25
+ ALL_MCP_TOOL_IDS,
26
+ assertMcpConnected,
27
+ mcpToolIdsFor,
28
+ type OpenCodeMcpConfig,
29
+ translateMcpConfig,
30
+ } from "./opencode-mcp";
31
+ import type {
32
+ OpenCodeClientEvent,
33
+ OpenCodeClientLike,
34
+ OpenCodeClientSession,
35
+ OpenCodeCreateSessionInput,
36
+ OpenCodePollResult,
37
+ } from "./opencode-sdk";
38
+ import {
39
+ formatPermissionRejectFailureDetail,
40
+ formatProviderLimitDetail,
41
+ } from "./opencode-sdk";
42
+ import type { OpenCodeServerHandle } from "./opencode-server";
43
+
44
+ // Structural, not imported from the SDK: pr-hero ships with ZERO runtime
45
+ // dependencies, and a Claude-only install must not pull an OpenCode SDK it
46
+ // will never call. The adapter slice declares the SDK an OPTIONAL peer and
47
+ // reaches it through a dynamic import.
48
+ interface RawEvent {
49
+ readonly id?: unknown;
50
+ readonly type?: unknown;
51
+ readonly properties?: unknown;
52
+ }
53
+
54
+ function props(raw: unknown): Record<string, unknown> | undefined {
55
+ const candidate = (raw as RawEvent)?.properties;
56
+ return typeof candidate === "object" && candidate !== null
57
+ ? (candidate as Record<string, unknown>)
58
+ : undefined;
59
+ }
60
+
61
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
62
+ return typeof value === "object" && value !== null
63
+ ? (value as Record<string, unknown>)
64
+ : undefined;
65
+ }
66
+
67
+ // #228: the raw provider event carries its session id in one of three
68
+ // places depending on its shape — a plain event's own `properties.sessionID`,
69
+ // a `message.part.*` event's `properties.part.sessionID`, or a
70
+ // `message.updated`-shaped event's `properties.info.sessionID`. Returns
71
+ // `undefined` when none of the three is present, which the caller treats as
72
+ // "cannot be attributed to any session" and therefore not filterable.
73
+ function eventSessionId(raw: unknown): string | undefined {
74
+ const p = props(raw);
75
+ if (p === undefined) return undefined;
76
+ if (typeof p.sessionID === "string") return p.sessionID;
77
+ const part = asRecord(p.part);
78
+ if (part !== undefined && typeof part.sessionID === "string")
79
+ return part.sessionID;
80
+ const info = asRecord(p.info);
81
+ if (info !== undefined && typeof info.sessionID === "string")
82
+ return info.sessionID;
83
+ return undefined;
84
+ }
85
+
86
+ function asNumber(value: unknown): number | undefined {
87
+ return typeof value === "number" && Number.isFinite(value)
88
+ ? value
89
+ : undefined;
90
+ }
91
+
92
+ // §5.2/§3.2: the proof must be PROVIDER-issued. `session.idle` cannot supply
93
+ // one — its entire payload is {sessionID} — so the proof CONTENT is taken from
94
+ // the assistant message, which carries a real completion record. Both §197
95
+ // observers reach it independently: the stream through `message.updated`, the
96
+ // poll through session.messages.
97
+ //
98
+ // A proof is not a BOUNDARY, and issue #127 is the whole cost of confusing the
99
+ // two. This function answers "did this STEP end", never "did the turn end":
100
+ // OpenCode creates one assistant message per agentic step, each with its own
101
+ // `time.completed`. The turn's boundary is `session.idle` on the stream and
102
+ // the session leaving `GET /session/status` on the poll; see mapOpenCodeEvents
103
+ // and pollStatus below.
104
+ export function terminalProofFromAssistant(
105
+ info: unknown,
106
+ state?: OpenCodeTurnState,
107
+ ): ProviderTerminalProof | undefined {
108
+ const message = asRecord(info);
109
+ if (message === undefined) return undefined;
110
+ if (message.role !== "assistant") return undefined;
111
+
112
+ const id = message.id;
113
+ if (typeof id !== "string" || id.length === 0) return undefined;
114
+
115
+ const completed = asNumber(asRecord(message.time)?.completed);
116
+ // Not finished is not a completion record. An assistant message exists from
117
+ // the moment its step starts; only `time.completed` says the step ended and
118
+ // therefore that there is anything here to quote as proof.
119
+ if (completed === undefined) return undefined;
120
+
121
+ if (state !== undefined) {
122
+ if (
123
+ state.sessionId !== undefined &&
124
+ message.sessionID !== undefined &&
125
+ message.sessionID !== state.sessionId
126
+ ) {
127
+ return undefined;
128
+ }
129
+ if (state.tombstones.has(id)) return undefined;
130
+ if (!isMessageOwned(id, state)) return undefined;
131
+ if (message.error === undefined) {
132
+ // Completed tool-calls or unknown finish never establishes success
133
+ if (message.finish !== "stop") return undefined;
134
+ if (hasOutstandingTools(state)) return undefined;
135
+ if (!isMessageOwned(id, state)) {
136
+ return undefined;
137
+ }
138
+ }
139
+ }
140
+
141
+ // providerStatus is a NORMALISED field, not a passthrough. The transport
142
+ // maps "completed" to success, "cancelled" to cancelled and EVERYTHING ELSE
143
+ // to failed (opencode-sdk.ts:781-789), so handing it OpenCode's raw finish
144
+ // reason reported every successful completion as a failure — pr-hero found
145
+ // exactly that, filed BLOCKER, on PR #82. The provider's vocabulary is
146
+ // translated here rather than leaked into a field whose meaning is fixed
147
+ // somewhere else.
148
+ //
149
+ // §3.2 sets the direction of every uncertain case: an unrecognised outcome
150
+ // must never become success. `finish` is declared `finish?: string` with no
151
+ // enumerated value space, so anything outside the known set stays outside
152
+ // "completed" and the transport's else-branch turns it into a failure.
153
+ const error = asRecord(message.error);
154
+ const finish = message.finish;
155
+ const providerStatus =
156
+ error !== undefined
157
+ ? // An abort is a cancellation, not a failure — the harness accounts
158
+ // for those differently (§5.3), and calling one the other loses the
159
+ // distinction that says whether remote work may still be running.
160
+ error.name === "MessageAbortedError"
161
+ ? "cancelled"
162
+ : "failed"
163
+ : finish === "stop"
164
+ ? "completed"
165
+ : typeof finish === "string" && finish.length > 0
166
+ ? finish
167
+ : "unknown";
168
+
169
+ return {
170
+ eventId: id,
171
+ providerStatus,
172
+ providerObservedAt: new Date(completed).toISOString(),
173
+ };
174
+ }
175
+
176
+ // SessionStatus's `retry` arm carries `next`, a timestamp. This is the
177
+ // provider-issued backoff hint decideRetryDisposition (§7) has accepted as an
178
+ // optional retryAfterMs since D1-07 and that no transport has ever been able
179
+ // to supply — the CLI transport reads the child's stdout and never sees an
180
+ // HTTP header. Returned as a DURATION because that is what the policy takes,
181
+ // and only when it is still in the future: a hint that already elapsed is not
182
+ // a hint, and passing a negative delay would be worse than passing none.
183
+ export function retryHintFromStatus(
184
+ status: unknown,
185
+ nowMs: number,
186
+ ): number | undefined {
187
+ const record = asRecord(status);
188
+ if (record?.type !== "retry") return undefined;
189
+ const next = asNumber(record.next);
190
+ if (next === undefined) return undefined;
191
+ const delta = next - nowMs;
192
+ return delta > 0 ? delta : undefined;
193
+ }
194
+
195
+ // #157: SessionStatus's `retry` arm can also carry an `action` naming an
196
+ // account/usage limit rather than an ordinary transient backoff. Only
197
+ // "account_rate_limit" has ever been observed (pr-157-8df2fca3-4, all three
198
+ // hunter captures, 3487 occurrences each) — this set is deliberately literal
199
+ // rather than "any retry", so an unrecognised future reason keeps today's
200
+ // alive-and-retrying behavior instead of guessing at a fact the provider
201
+ // never actually stated. `message` is read from the top-level retry status,
202
+ // not `action.message` — measured identical on the real capture, and the
203
+ // top-level field is what retryHintFromStatus above already reads its
204
+ // sibling `next` from.
205
+ const ACCOUNT_LIMIT_REASONS: ReadonlySet<string> = new Set([
206
+ "account_rate_limit",
207
+ ]);
208
+
209
+ export function providerLimitFromStatus(
210
+ status: unknown,
211
+ ): { reason: string; message: string } | undefined {
212
+ const record = asRecord(status);
213
+ if (record?.type !== "retry") return undefined;
214
+ const action = asRecord(record.action);
215
+ const reason = action?.reason;
216
+ if (typeof reason !== "string" || !ACCOUNT_LIMIT_REASONS.has(reason)) {
217
+ return undefined;
218
+ }
219
+ const message = typeof record.message === "string" ? record.message : "";
220
+ return { reason, message };
221
+ }
222
+
223
+ // #213: EventSessionError's `properties.error`. `responseBody` is not read —
224
+ // the witness is the name, the status, the retry flag, and `data.message`.
225
+ export function providerRefusalFromProperties(properties: unknown):
226
+ | {
227
+ name: string;
228
+ statusCode?: number;
229
+ retryable?: boolean;
230
+ message: string;
231
+ }
232
+ | undefined {
233
+ const error = asRecord(asRecord(properties)?.error);
234
+ if (error === undefined) return undefined;
235
+ const name =
236
+ typeof error.name === "string" && error.name.length > 0
237
+ ? error.name
238
+ : "unknown";
239
+ const data = asRecord(error.data);
240
+ const message = typeof data?.message === "string" ? data.message : "";
241
+ const statusCode = asNumber(data?.statusCode);
242
+ const retryable =
243
+ typeof data?.isRetryable === "boolean" ? data.isRetryable : undefined;
244
+ return {
245
+ name,
246
+ ...(statusCode !== undefined ? { statusCode } : {}),
247
+ ...(retryable !== undefined ? { retryable } : {}),
248
+ message,
249
+ };
250
+ }
251
+
252
+ // TRAP 4 (issue #124): `message.part.delta` carries NO part type. Its whole
253
+ // payload is {sessionID, messageID, partID, field, delta}, so the only way to
254
+ // know what a delta belongs to is to correlate its `partID` against the part
255
+ // announced earlier by `message.part.updated`.
256
+ //
257
+ // Filtering on `field === "text"` — the FIELD NAME — is not that correlation
258
+ // and never was: the SDK declares `ReasoningPart` with a member literally
259
+ // called `text`, exactly as `TextPart` has, so with a reasoning model the
260
+ // model's private thinking was concatenated into finalText as if it were the
261
+ // answer. The #116 smoke pass 3 artifact shows it verbatim, two reasoning
262
+ // deltas glued together with no separator where the JSON answer belonged, and
263
+ // every hunter in that run failed format_violation over it.
264
+ //
265
+ // This is the state that correlation needs. It travels with the SessionState
266
+ // so it dies with the session rather than with the process, and BOTH maps are
267
+ // bounded: an SSE subscription is long-lived and a map keyed by a
268
+ // provider-generated id would otherwise grow for as long as the session does.
269
+ // Eviction is oldest-first (a Map iterates in insertion order), which is the
270
+ // safe direction — parts are announced and streamed in order, so the oldest
271
+ // entry is the one no delta can still name.
272
+ export interface TrackedPartDetail {
273
+ readonly id: string;
274
+ messageId?: string;
275
+ type: string;
276
+ text?: string;
277
+ synthetic?: boolean;
278
+ ignored?: boolean;
279
+ emittedText: string;
280
+ toolStatus?: "pending" | "running" | "completed" | "error";
281
+ toolCallId?: string;
282
+ }
283
+
284
+ export interface TrackedMessageDetail {
285
+ readonly id: string;
286
+ readonly role: "user" | "assistant" | string;
287
+ sessionID?: string;
288
+ parentID?: string;
289
+ time?: { created?: number; completed?: number };
290
+ finish?: string;
291
+ error?: unknown;
292
+ hasToolCalls?: boolean;
293
+ partIds: string[];
294
+ }
295
+
296
+ export interface UnknownOwnerObservation {
297
+ readonly type: "part.updated" | "part.delta";
298
+ readonly partId: string;
299
+ readonly messageId?: string;
300
+ readonly raw: Record<string, unknown>;
301
+ // Set only for a buffered "part.delta": the provider event id, threaded
302
+ // through so replay (reconcileUnknownOwnerBuffer) can dedupe by identity
303
+ // the same way a live delta does. "part.updated" snapshots are cumulative
304
+ // and self-idempotent, so they carry no id.
305
+ readonly eventId?: string;
306
+ }
307
+
308
+ export interface OpenCodeTurnState {
309
+ readonly sessionId?: string;
310
+ currentUserId?: string;
311
+ expectedCwd?: string;
312
+ readonly assistantMessages: Set<string>;
313
+ readonly parts: Map<string, "answer" | "reasoning">;
314
+ readonly partDetails: Map<string, TrackedPartDetail>;
315
+ readonly messageDetails: Map<string, TrackedMessageDetail>;
316
+ readonly parentLinks: Map<string, string>;
317
+ readonly toolStates: Map<
318
+ string,
319
+ "pending" | "running" | "completed" | "error"
320
+ >;
321
+ // Owned ONLY by the stream path (`handlePartUpdated`). `reconcileMessages`
322
+ // (the poll readback) writes `toolStates` unconditionally and can observe
323
+ // a LATER status before the stream delivers that tool's own earlier ones
324
+ // — crediting activity off `toolStates` would let a poll-advanced rank
325
+ // suppress every real transition the stream later reports. See the WHY
326
+ // comment at its use site in `handlePartUpdated`.
327
+ readonly toolActivityRank: Map<string, number>;
328
+ // pr-hero review F001 (#214): every callID EVER observed "completed", by
329
+ // either the stream (`handlePartUpdated`) or the poll (`reconcileMessages`)
330
+ // — never removed, regardless of what a LATER observation reports for that
331
+ // same callID. `toolStates` above stores the provider's raw LAST-KNOWN
332
+ // status and is written unconditionally by both observers; a poll that
333
+ // recomputed "how many are completed" by re-filtering `toolStates` at each
334
+ // terminal (the pre-fix design) went DOWN the moment any earlier-completed
335
+ // call's status changed to "error" on a later readback. This set is the
336
+ // fix: `pollStatus` reports its members, never a fresh `toolStates`
337
+ // filter. Bounded by construction, not a separate cap — an id is added
338
+ // here only once it is already present in `toolStates`, which enforces
339
+ // MAX_TRACKED_PARTS before either write.
340
+ readonly completedToolCallIds: Set<string>;
341
+ // pr-hero review F001 (round 3): STREAM-OWNED — written and read ONLY by
342
+ // `handlePartUpdated`, to decide whether THIS observer has already emitted
343
+ // its own `{kind:"tool"}` for a callID. Deliberately a SEPARATE set from
344
+ // `completedToolCallIds` above, which `reconcileMessages` (prompt_result's
345
+ // own readback at session-create, and every poll round, winning or not)
346
+ // also writes unconditionally. Gating the stream's emission on the SHARED
347
+ // set (the round-2 shape) let a non-stream reconcile that observed
348
+ // "completed" for a callID BEFORE the stream's own SSE event for that
349
+ // exact completion arrive suppress the stream's emission entirely — and
350
+ // when the STREAM, not the poll, goes on to win the turn's terminal (no
351
+ // poll terminal ever reports that callID), the transport's union receives
352
+ // it from NEITHER channel and undercounts a hunter that plainly looked.
353
+ // Emission dedupe must be decided from what THIS observer has already
354
+ // emitted, never from what some other observer already recorded. Bounded
355
+ // by construction like `completedToolCallIds` (no separate cap, no
356
+ // eviction): every id here is added only after `toolStates`'s own
357
+ // MAX_TRACKED_PARTS check above already passed for that identity.
358
+ readonly streamCompletedToolCallIds: Set<string>;
359
+ readonly tombstones: Set<string>;
360
+ readonly unknownOwnerBuffer: Array<UnknownOwnerObservation>;
361
+ // Provider event ids for text deltas actually applied to `emittedText`
362
+ // (never ids merely seen while buffered — see `handlePartDelta`).
363
+ readonly deltaEventIds: Set<string>;
364
+ // Sibling to `deltaEventIds` above, kept separate rather than shared: that
365
+ // set's own comment fixes its meaning as "applied to emittedText", which a
366
+ // reasoning delta never is (see `handlePartDelta`'s reasoning branch). A
367
+ // provider event id is unique across the whole stream regardless of part
368
+ // kind, so there is no collision risk in sharing it — this is a semantics
369
+ // choice, not a safety one. Records every NOVEL reasoning-delta id seen,
370
+ // so a replayed id (an SSE Last-Event-ID reconnect) is recognized and does
371
+ // not earn useful-progress credit twice.
372
+ readonly reasoningDeltaEventIds: Set<string>;
373
+ readonly usage: Map<string, StepUsage>;
374
+ readonly completedUsage: Set<string>;
375
+ readonly payloadBytes: Map<string, number>;
376
+ readonly trackedPartOwners: Map<string, string>;
377
+ readonly evictedUsageIds: Set<string>;
378
+ usageCapped: boolean;
379
+ usageConflict?: boolean;
380
+ usageIncomplete?: boolean;
381
+ carriedUsage: StepUsage;
382
+ lastProof?: ProviderTerminalProof;
383
+ boundaryReported: boolean;
384
+ integrityFailure?: string;
385
+ }
386
+
387
+ interface StepUsage {
388
+ readonly inputTokens?: number;
389
+ readonly outputTokens?: number;
390
+ readonly costUsd?: number;
391
+ // OpenCode's `info.tokens` leaves are disjoint-additive
392
+ // (packages/schema/src/token-usage.ts): total = input + output + reasoning
393
+ // + cache.read + cache.write. Carried so cache use is measurable on this
394
+ // route; absent stays absent, never a fabricated 0.
395
+ readonly cacheReadTokens?: number;
396
+ readonly cacheWriteTokens?: number;
397
+ readonly reasoningTokens?: number;
398
+ }
399
+
400
+ const MAX_TRACKED_PARTS = 4096;
401
+ const MAX_TRACKED_MESSAGES = 512;
402
+ const MAX_UNKNOWN_OWNER_BUFFER = 256;
403
+ const MAX_TOMBSTONES = 1024;
404
+ const MAX_READBACK_BYTES = 4 * 1024 * 1024;
405
+ // Same order of magnitude as MAX_TRACKED_PARTS: sized to cover an SSE
406
+ // reconnect's Last-Event-ID replay window for one turn's answer deltas.
407
+ const MAX_TRACKED_DELTA_EVENTS = 4096;
408
+ // Own cap, same rationale as MAX_TRACKED_DELTA_EVENTS, for reasoningDeltaEventIds.
409
+ const MAX_TRACKED_REASONING_DELTA_EVENTS = 4096;
410
+ // PR #228 review, F002: same redelivery hazard as MAX_TRACKED_DELTA_EVENTS
411
+ // (an SSE Last-Event-ID reconnect can replay an event this session already
412
+ // saw), applied to `permission.asked` requestIDs — see SessionState's
413
+ // `respondedPermissions`. Permission prompts are far rarer than deltas
414
+ // within one attempt, so a smaller cap than MAX_TRACKED_DELTA_EVENTS is
415
+ // still generous; sized to MAX_TRACKED_MESSAGES for the same "one order of
416
+ // magnitude above anything a real attempt produces" reasoning. Unlike every
417
+ // OTHER bounded set here, reaching this cap does NOT evict the oldest id via
418
+ // `rememberId` — round 2 of the same review: an evicted requestID is
419
+ // indistinguishable from an unseen one, so its later redelivery would slip
420
+ // past the dedupe guard and fire a second reply. The attempt fails closed
421
+ // instead once this many distinct prompts have been answered in one turn.
422
+ const MAX_TRACKED_PERMISSION_REQUESTS = MAX_TRACKED_MESSAGES;
423
+ // An SSE `Last-Event-ID` reconnect can re-deliver an OLDER status after a
424
+ // newer one already landed (e.g. "running" replayed after "completed" was
425
+ // already observed) — `previousStatus !== status` alone would credit that
426
+ // replay as a transition, since it genuinely differs from what is stored.
427
+ // Rank makes only FORWARD movement count: `completed` and `error` share a
428
+ // rank because both are terminal outcomes and neither outranks the other, so
429
+ // one following the other (in either direction) is not progress either.
430
+ const TOOL_STATUS_RANK: Record<
431
+ "pending" | "running" | "completed" | "error",
432
+ number
433
+ > = {
434
+ pending: 0,
435
+ running: 1,
436
+ completed: 2,
437
+ error: 2,
438
+ };
439
+
440
+ export function createTurnState(
441
+ sessionId?: string,
442
+ currentUserId?: string,
443
+ expectedCwd?: string,
444
+ ): OpenCodeTurnState {
445
+ return {
446
+ sessionId,
447
+ currentUserId,
448
+ expectedCwd,
449
+ assistantMessages: new Set(),
450
+ parts: new Map(),
451
+ partDetails: new Map(),
452
+ messageDetails: new Map(),
453
+ parentLinks: new Map(),
454
+ toolStates: new Map(),
455
+ toolActivityRank: new Map(),
456
+ completedToolCallIds: new Set(),
457
+ streamCompletedToolCallIds: new Set(),
458
+ tombstones: new Set(),
459
+ unknownOwnerBuffer: [],
460
+ deltaEventIds: new Set(),
461
+ reasoningDeltaEventIds: new Set(),
462
+ usage: new Map(),
463
+ completedUsage: new Set(),
464
+ payloadBytes: new Map(),
465
+ trackedPartOwners: new Map(),
466
+ evictedUsageIds: new Set(),
467
+ usageCapped: false,
468
+ usageConflict: false,
469
+ usageIncomplete: false,
470
+ carriedUsage: {},
471
+ boundaryReported: false,
472
+ };
473
+ }
474
+
475
+ function failIntegrity(state: OpenCodeTurnState, detail: string): never {
476
+ state.integrityFailure = `[pr-hero] opencode client: ${detail}`;
477
+ throw new Error(state.integrityFailure);
478
+ }
479
+
480
+ function canonicalDirectory(path: string): string {
481
+ // Canonicalize existing symlinks, while keeping pure fixtures and a removed
482
+ // checkout deterministic. Neither spelling can authorize another directory.
483
+ try {
484
+ return realpathSync(path);
485
+ } catch {
486
+ return resolve(path);
487
+ }
488
+ }
489
+
490
+ function trackPayload(
491
+ state: OpenCodeTurnState,
492
+ key: string,
493
+ value: unknown,
494
+ ): void {
495
+ const bytes = Buffer.byteLength(JSON.stringify(value), "utf8");
496
+ let total = bytes;
497
+ for (const [id, size] of state.payloadBytes) if (id !== key) total += size;
498
+ if (total > MAX_READBACK_BYTES)
499
+ failIntegrity(state, "observation byte budget exceeded");
500
+ state.payloadBytes.set(key, bytes);
501
+ }
502
+
503
+ function trackPart(
504
+ state: OpenCodeTurnState,
505
+ part: Record<string, unknown>,
506
+ messageId: string,
507
+ ): void {
508
+ const id = part.id;
509
+ if (
510
+ typeof id !== "string" ||
511
+ part.messageID !== messageId ||
512
+ (state.sessionId !== undefined && part.sessionID !== state.sessionId)
513
+ ) {
514
+ failIntegrity(state, "part ownership mismatch or missing identity");
515
+ }
516
+ if (state.tombstones.has(id))
517
+ failIntegrity(state, "required part reappeared after removal");
518
+ const owner = state.trackedPartOwners.get(id);
519
+ if (owner !== undefined && owner !== messageId)
520
+ failIntegrity(state, "part identity changed ownership");
521
+ if (
522
+ owner === undefined &&
523
+ state.trackedPartOwners.size >= MAX_TRACKED_PARTS
524
+ ) {
525
+ failIntegrity(state, "maximum tracked parts exceeded");
526
+ }
527
+ trackPayload(state, `part:${id}`, part);
528
+ state.trackedPartOwners.set(id, messageId);
529
+ }
530
+
531
+ function trackMessage(
532
+ state: OpenCodeTurnState,
533
+ info: Record<string, unknown>,
534
+ ): void {
535
+ const id = info.id;
536
+ if (
537
+ typeof id !== "string" ||
538
+ (state.sessionId !== undefined && info.sessionID !== state.sessionId)
539
+ ) {
540
+ failIntegrity(state, "message ownership mismatch or missing identity");
541
+ }
542
+ const previous = state.messageDetails.get(id);
543
+ if (
544
+ previous !== undefined &&
545
+ (previous.role !== info.role ||
546
+ (previous.parentID !== undefined && previous.parentID !== info.parentID))
547
+ ) {
548
+ failIntegrity(state, "message identity changed role or parent");
549
+ }
550
+ if (
551
+ !state.payloadBytes.has(`message:${id}`) &&
552
+ [...state.payloadBytes.keys()].filter((key) => key.startsWith("message:"))
553
+ .length >= MAX_TRACKED_MESSAGES
554
+ ) {
555
+ failIntegrity(state, "message cap exceeded (cap exhaustion)");
556
+ }
557
+ const path = asRecord(info.path);
558
+ if (
559
+ info.role === "assistant" &&
560
+ state.expectedCwd !== undefined &&
561
+ (typeof path?.cwd !== "string" ||
562
+ canonicalDirectory(path.cwd) !== canonicalDirectory(state.expectedCwd))
563
+ ) {
564
+ failIntegrity(state, "message cwd mismatch or unavailable");
565
+ }
566
+ trackPayload(state, `message:${id}`, info);
567
+ }
568
+
569
+ export function isMessageOwned(
570
+ messageId: string,
571
+ state: OpenCodeTurnState,
572
+ ): boolean {
573
+ if (state.currentUserId === undefined) return false;
574
+ if (messageId === state.currentUserId) return true;
575
+ let current: string | undefined = state.parentLinks.get(messageId);
576
+ const visited = new Set<string>();
577
+ while (current !== undefined) {
578
+ if (visited.has(current)) return false;
579
+ visited.add(current);
580
+ if (current === state.currentUserId) return true;
581
+ current = state.parentLinks.get(current);
582
+ }
583
+ return false;
584
+ }
585
+
586
+ export function hasOutstandingTools(state: OpenCodeTurnState): boolean {
587
+ for (const status of state.toolStates.values()) {
588
+ if (status === "pending" || status === "running") {
589
+ return true;
590
+ }
591
+ }
592
+ return false;
593
+ }
594
+
595
+ function evaluateFinalAssistant(
596
+ info: unknown,
597
+ state: OpenCodeTurnState,
598
+ ): { valid: boolean; reason?: string } {
599
+ const message = asRecord(info);
600
+ if (message?.role !== "assistant") {
601
+ return { valid: false, reason: "not an assistant message" };
602
+ }
603
+ const id = typeof message.id === "string" ? message.id : undefined;
604
+ if (!id) return { valid: false, reason: "missing id" };
605
+
606
+ if (
607
+ state.sessionId !== undefined &&
608
+ message.sessionID !== undefined &&
609
+ message.sessionID !== state.sessionId
610
+ ) {
611
+ return { valid: false, reason: "cross-session message mismatch" };
612
+ }
613
+
614
+ if (state.tombstones.has(id)) {
615
+ return { valid: false, reason: "message tombstoned" };
616
+ }
617
+
618
+ const completed = asNumber(asRecord(message.time)?.completed);
619
+ if (completed === undefined) {
620
+ return { valid: false, reason: "not completed" };
621
+ }
622
+
623
+ if (message.error !== undefined) {
624
+ return { valid: true };
625
+ }
626
+
627
+ if (message.finish !== "stop") {
628
+ return {
629
+ valid: false,
630
+ reason: `unsupported finish: ${String(message.finish)}`,
631
+ };
632
+ }
633
+
634
+ if (hasOutstandingTools(state)) {
635
+ return { valid: false, reason: "outstanding tools in progress" };
636
+ }
637
+
638
+ if (!isMessageOwned(id, state)) {
639
+ return { valid: false, reason: "missing or invalid ownership" };
640
+ }
641
+
642
+ return { valid: true };
643
+ }
644
+
645
+ function remember<K, V>(map: Map<K, V>, key: K, value: V, cap: number): void {
646
+ map.set(key, value);
647
+ while (map.size > cap) {
648
+ const oldest = map.keys().next();
649
+ if (oldest.done === true) return;
650
+ map.delete(oldest.value);
651
+ }
652
+ }
653
+
654
+ function addField(
655
+ base: number | undefined,
656
+ step: number | undefined,
657
+ ): number | undefined {
658
+ if (step === undefined) return base;
659
+ return (base ?? 0) + step;
660
+ }
661
+
662
+ function addUsage(base: StepUsage, step: StepUsage): StepUsage {
663
+ const inputTokens = addField(base.inputTokens, step.inputTokens);
664
+ const outputTokens = addField(base.outputTokens, step.outputTokens);
665
+ const costUsd = addField(base.costUsd, step.costUsd);
666
+ const cacheReadTokens = addField(base.cacheReadTokens, step.cacheReadTokens);
667
+ const cacheWriteTokens = addField(
668
+ base.cacheWriteTokens,
669
+ step.cacheWriteTokens,
670
+ );
671
+ const reasoningTokens = addField(base.reasoningTokens, step.reasoningTokens);
672
+ return {
673
+ ...(inputTokens !== undefined ? { inputTokens } : {}),
674
+ ...(outputTokens !== undefined ? { outputTokens } : {}),
675
+ ...(costUsd !== undefined ? { costUsd } : {}),
676
+ ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),
677
+ ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),
678
+ ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
679
+ };
680
+ }
681
+
682
+ function mergeLeaf(
683
+ existing: number | undefined,
684
+ next: number | undefined,
685
+ ): number | undefined {
686
+ return existing !== undefined || next !== undefined
687
+ ? Math.max(existing ?? 0, next ?? 0)
688
+ : undefined;
689
+ }
690
+
691
+ function rememberUsage(
692
+ state: OpenCodeTurnState,
693
+ messageId: string,
694
+ usage: StepUsage,
695
+ completed = false,
696
+ ): void {
697
+ if (state.evictedUsageIds.has(messageId)) {
698
+ state.usageCapped = true;
699
+ state.usageIncomplete = true;
700
+ return;
701
+ }
702
+ const existing = state.usage.get(messageId);
703
+ const wasCompleted = state.completedUsage.has(messageId);
704
+ if (completed) state.completedUsage.add(messageId);
705
+ if (existing !== undefined) {
706
+ const costConflict =
707
+ existing.costUsd !== undefined &&
708
+ usage.costUsd !== undefined &&
709
+ (usage.costUsd < existing.costUsd ||
710
+ (wasCompleted && usage.costUsd !== existing.costUsd));
711
+ const tokenConflict =
712
+ (existing.inputTokens !== undefined &&
713
+ usage.inputTokens !== undefined &&
714
+ (usage.inputTokens < existing.inputTokens ||
715
+ (wasCompleted && usage.inputTokens !== existing.inputTokens))) ||
716
+ (existing.outputTokens !== undefined &&
717
+ usage.outputTokens !== undefined &&
718
+ (usage.outputTokens < existing.outputTokens ||
719
+ (wasCompleted && usage.outputTokens !== existing.outputTokens)));
720
+ if (costConflict || tokenConflict) {
721
+ state.usageConflict = true;
722
+ state.usageIncomplete = true;
723
+ }
724
+ const mergedInput =
725
+ existing.inputTokens !== undefined || usage.inputTokens !== undefined
726
+ ? Math.max(existing.inputTokens ?? 0, usage.inputTokens ?? 0)
727
+ : undefined;
728
+ const mergedOutput =
729
+ existing.outputTokens !== undefined || usage.outputTokens !== undefined
730
+ ? Math.max(existing.outputTokens ?? 0, usage.outputTokens ?? 0)
731
+ : undefined;
732
+ const mergedCost =
733
+ existing.costUsd !== undefined || usage.costUsd !== undefined
734
+ ? Math.max(existing.costUsd ?? 0, usage.costUsd ?? 0)
735
+ : undefined;
736
+ // Cache and reasoning leaves merge like input/output (Math.max) but are
737
+ // deliberately left out of the conflict check above: a snapshot that
738
+ // momentarily reports fewer cache tokens must not flag the whole turn as
739
+ // conflicting usage.
740
+ const mergedCacheRead = mergeLeaf(
741
+ existing.cacheReadTokens,
742
+ usage.cacheReadTokens,
743
+ );
744
+ const mergedCacheWrite = mergeLeaf(
745
+ existing.cacheWriteTokens,
746
+ usage.cacheWriteTokens,
747
+ );
748
+ const mergedReasoning = mergeLeaf(
749
+ existing.reasoningTokens,
750
+ usage.reasoningTokens,
751
+ );
752
+ state.usage.set(messageId, {
753
+ ...(mergedInput !== undefined ? { inputTokens: mergedInput } : {}),
754
+ ...(mergedOutput !== undefined ? { outputTokens: mergedOutput } : {}),
755
+ ...(mergedCost !== undefined ? { costUsd: mergedCost } : {}),
756
+ ...(mergedCacheRead !== undefined
757
+ ? { cacheReadTokens: mergedCacheRead }
758
+ : {}),
759
+ ...(mergedCacheWrite !== undefined
760
+ ? { cacheWriteTokens: mergedCacheWrite }
761
+ : {}),
762
+ ...(mergedReasoning !== undefined
763
+ ? { reasoningTokens: mergedReasoning }
764
+ : {}),
765
+ });
766
+ return;
767
+ }
768
+ state.usage.set(messageId, usage);
769
+ while (state.usage.size > MAX_TRACKED_MESSAGES) {
770
+ const oldest = state.usage.keys().next();
771
+ if (oldest.done === true) return;
772
+ const evicted = state.usage.get(oldest.value);
773
+ state.usage.delete(oldest.value);
774
+ if (evicted !== undefined) {
775
+ state.carriedUsage = addUsage(state.carriedUsage, evicted);
776
+ rememberId(state.evictedUsageIds, oldest.value, MAX_TRACKED_MESSAGES);
777
+ state.usageCapped = true;
778
+ state.usageIncomplete = true;
779
+ }
780
+ }
781
+ }
782
+
783
+ function turnUsage(state: OpenCodeTurnState): StepUsage {
784
+ let total = state.carriedUsage;
785
+ for (const step of state.usage.values()) total = addUsage(total, step);
786
+ return total;
787
+ }
788
+
789
+ function rememberId(set: Set<string>, id: string, cap: number): void {
790
+ set.add(id);
791
+ while (set.size > cap) {
792
+ const oldest = set.values().next();
793
+ if (oldest.done === true) return;
794
+ set.delete(oldest.value);
795
+ }
796
+ }
797
+
798
+ function handlePartUpdated(
799
+ p: Record<string, unknown>,
800
+ state: OpenCodeTurnState,
801
+ ): OpenCodeClientEvent[] {
802
+ const part = asRecord(p.part);
803
+ if (!part) return [];
804
+ const partId = typeof part.id === "string" ? part.id : undefined;
805
+ const messageId =
806
+ typeof part.messageID === "string" ? part.messageID : undefined;
807
+ if (!partId || !messageId) return [];
808
+ trackPart(state, part, messageId);
809
+
810
+ if (state.tombstones.has(partId) || state.tombstones.has(messageId)) {
811
+ return [];
812
+ }
813
+
814
+ // If message owner is unknown, buffer observation
815
+ if (
816
+ !state.messageDetails.has(messageId) &&
817
+ !state.assistantMessages.has(messageId)
818
+ ) {
819
+ if (state.unknownOwnerBuffer.length >= MAX_UNKNOWN_OWNER_BUFFER) {
820
+ state.integrityFailure =
821
+ "[pr-hero] opencode client: unknown-owner buffer cap exceeded (cap exhaustion)";
822
+ throw new Error(state.integrityFailure);
823
+ }
824
+ state.unknownOwnerBuffer.push({
825
+ type: "part.updated",
826
+ partId,
827
+ messageId,
828
+ raw: p,
829
+ });
830
+ return [];
831
+ }
832
+
833
+ if (!isMessageOwned(messageId, state)) return [];
834
+ const msgDetail = state.messageDetails.get(messageId);
835
+ if (msgDetail && !msgDetail.partIds.includes(partId)) {
836
+ msgDetail.partIds.push(partId);
837
+ }
838
+
839
+ const partType = part.type;
840
+ if (partType === "tool") {
841
+ const toolState = asRecord(part.state);
842
+ const status = toolState?.status as
843
+ | "pending"
844
+ | "running"
845
+ | "completed"
846
+ | "error"
847
+ | undefined;
848
+ const callId = typeof part.callID === "string" ? part.callID : partId;
849
+ let transitioned = false;
850
+ if (status) {
851
+ if (
852
+ !state.toolStates.has(callId) &&
853
+ state.toolStates.size >= MAX_TRACKED_PARTS
854
+ )
855
+ failIntegrity(state, "tool identity cap exceeded");
856
+ // `state.toolStates` still stores the raw reported status regardless
857
+ // of rank — other logic (e.g. `hasOutstandingTools`) reads it and
858
+ // must keep seeing the provider's literal last-known status, not a
859
+ // rank-filtered one. Only whether `activity` is EMITTED changes below.
860
+ state.toolStates.set(callId, status);
861
+ // #228's review: credit is computed against `toolActivityRank`, a map
862
+ // owned ONLY by this stream path — NEVER against `toolStates`, which
863
+ // `reconcileMessages` (the poll readback) also writes unconditionally.
864
+ // Three concurrent hunters sharing one server can have a poll round
865
+ // observe a tool's "completed" before the stream ever delivers that
866
+ // same tool's "pending"/"running". Comparing against `toolStates`
867
+ // would then compare the stream's real "pending" against the rank the
868
+ // POLL already advanced to "completed", crediting nothing for work
869
+ // the stream is only now reporting.
870
+ const previousRank = state.toolActivityRank.get(callId) ?? -1;
871
+ const newRank = TOOL_STATUS_RANK[status];
872
+ transitioned = newRank > previousRank;
873
+ if (transitioned)
874
+ remember(state.toolActivityRank, callId, newRank, MAX_TRACKED_PARTS);
875
+ }
876
+ if (msgDetail) msgDetail.hasToolCalls = true;
877
+ // Ownership was already established above (the `isMessageOwned` check
878
+ // before this switch), so a NOVEL status transition here is real
879
+ // provider work — the tool actually moved pending -> running ->
880
+ // completed/error. Re-observing the SAME status (a re-delivered or
881
+ // redundant update) is not new work and earns nothing. Before this, tool
882
+ // execution time counted as silence: this branch emitted no client
883
+ // event at all, transition or not.
884
+ const events: OpenCodeClientEvent[] = [];
885
+ if (transitioned) {
886
+ events.push({ kind: "activity" });
887
+ // #214: count a LOOK, not an announcement. Gated on `transitioned` —
888
+ // computed above off `toolActivityRank`, the STREAM-owned forward rank
889
+ // — and deliberately NOT off `toolStates` (which `reconcileMessages`,
890
+ // the poll readback, also writes unconditionally). Three concurrent
891
+ // hunters sharing one server can have a poll round observe a tool's
892
+ // "completed" before the stream ever delivers that same tool's
893
+ // "pending"/"running"; reading `toolStates` here would let the poll's
894
+ // race silently swallow the stream's own real "completed" transition
895
+ // and undercount a hunter that plainly looked. "error" is excluded on
896
+ // purpose: it produced no findable signal to reason from, and no test
897
+ // has asked for an errored call to count as "looked".
898
+ }
899
+ // pr-hero review F001 (round 2): the completion TALLY is keyed by SET
900
+ // MEMBERSHIP, never by `transitioned`/rank — deliberately a SEPARATE gate
901
+ // from "activity" above. "error" and "completed" share TOOL_STATUS_RANK
902
+ // (both terminal, neither outranks the other), so an error->completed
903
+ // transition for the same callID leaves `transitioned` false; nesting
904
+ // this tally inside `if (transitioned)` (the pre-fix shape) meant that
905
+ // sequence was NEVER added to `completedToolCallIds` and never emitted
906
+ // its `{kind:"tool"}` event at all — contradicting the set's own
907
+ // contract ("every callID EVER observed completed") and silently
908
+ // undercounting whenever the poll did not independently catch the same
909
+ // call.
910
+ if (status === "completed") {
911
+ // Always recorded in the SHARED set, unconditionally — this is what
912
+ // `pollStatus` reports if the POLL ends up winning the turn's terminal
913
+ // instead of the stream, and it must reflect every completion
914
+ // regardless of which observer saw it first.
915
+ state.completedToolCallIds.add(callId);
916
+ // pr-hero review F001 (round 3): emission is deduped against the
917
+ // STREAM-OWNED set, never the shared one above — see that field's own
918
+ // WHY comment on `OpenCodeTurnState`. Deduping against the shared set
919
+ // let a non-stream reconcile that saw this exact callID complete FIRST
920
+ // (prompt_result's own readback, a non-winning poll round) suppress
921
+ // the stream's own emission, silently losing the count whenever the
922
+ // stream — not the poll — went on to win the terminal. A REPEAT
923
+ // "completed" this observer has already emitted for is still a
924
+ // no-op, and the ownership guard above already confines this to the
925
+ // turn's own tool calls.
926
+ if (!state.streamCompletedToolCallIds.has(callId)) {
927
+ const tool =
928
+ typeof part.tool === "string" && part.tool.length > 0
929
+ ? part.tool
930
+ : "unknown";
931
+ state.streamCompletedToolCallIds.add(callId);
932
+ events.push({ kind: "tool", tool, callId });
933
+ }
934
+ }
935
+ return events;
936
+ }
937
+
938
+ if (partType === "reasoning") {
939
+ if (!isMessageOwned(messageId, state)) return [];
940
+ const previous = state.partDetails.get(partId)?.text ?? "";
941
+ const text = typeof part.text === "string" ? part.text : "";
942
+ remember(state.parts, partId, "reasoning", MAX_TRACKED_PARTS);
943
+ state.partDetails.set(partId, {
944
+ id: partId,
945
+ messageId,
946
+ type: "reasoning",
947
+ text: text.startsWith(previous) ? text : previous,
948
+ emittedText: "",
949
+ });
950
+ // An owned cumulative snapshot proving advancement is useful, and so —
951
+ // see `handlePartDelta`'s reasoning branch below — is a DELTA carrying a
952
+ // provider event id not seen before: PR #227 threaded that id through,
953
+ // which is exactly the replay identity this comment used to say a bare
954
+ // delta marker lacked. An id-less delta still has none and stays a bare
955
+ // marker there.
956
+ return [
957
+ {
958
+ kind: "reasoning",
959
+ progress: text.length > previous.length && text.startsWith(previous),
960
+ },
961
+ ];
962
+ }
963
+
964
+ if (msgDetail?.role === "user" || !state.assistantMessages.has(messageId)) {
965
+ return [];
966
+ }
967
+
968
+ if (partType === "text") {
969
+ const isSynthetic = part.synthetic === true;
970
+ const isIgnored = part.ignored === true;
971
+ const isIntermediateToolStep = msgDetail?.hasToolCalls === true;
972
+
973
+ if (isSynthetic || isIgnored || isIntermediateToolStep) {
974
+ return [];
975
+ }
976
+
977
+ remember(state.parts, partId, "answer", MAX_TRACKED_PARTS);
978
+
979
+ let detail = state.partDetails.get(partId);
980
+ if (!detail) {
981
+ detail = {
982
+ id: partId,
983
+ messageId,
984
+ type: "text",
985
+ synthetic: isSynthetic,
986
+ ignored: isIgnored,
987
+ emittedText: "",
988
+ };
989
+ state.partDetails.set(partId, detail);
990
+ }
991
+
992
+ const snapshotText = typeof part.text === "string" ? part.text : undefined;
993
+ if (snapshotText !== undefined && snapshotText.length > 0) {
994
+ detail.text = snapshotText;
995
+ const alreadyEmitted = detail.emittedText;
996
+ if (alreadyEmitted === snapshotText) {
997
+ return [];
998
+ }
999
+ if (alreadyEmitted.length === 0) {
1000
+ detail.emittedText = snapshotText;
1001
+ return [{ kind: "delta", text: snapshotText }];
1002
+ }
1003
+ if (snapshotText.startsWith(alreadyEmitted)) {
1004
+ const suffix = snapshotText.slice(alreadyEmitted.length);
1005
+ detail.emittedText = snapshotText;
1006
+ return [{ kind: "delta", text: suffix }];
1007
+ }
1008
+ state.integrityFailure = `[pr-hero] opencode client: conflicting snapshot observed for part ${partId}`;
1009
+ throw new Error(state.integrityFailure);
1010
+ }
1011
+ }
1012
+
1013
+ return [];
1014
+ }
1015
+
1016
+ function handlePartDelta(
1017
+ p: Record<string, unknown>,
1018
+ state: OpenCodeTurnState,
1019
+ eventId?: string,
1020
+ ): OpenCodeClientEvent[] {
1021
+ if (p.field !== "text") return [];
1022
+ const delta = p.delta;
1023
+ if (typeof delta !== "string" || delta.length === 0) return [];
1024
+ const partId = p.partID;
1025
+ if (typeof partId !== "string") return [];
1026
+ const messageId = typeof p.messageID === "string" ? p.messageID : undefined;
1027
+ if (messageId === undefined)
1028
+ failIntegrity(state, "delta missing message identity");
1029
+ trackPart(state, { ...p, id: partId }, messageId);
1030
+
1031
+ if (
1032
+ state.tombstones.has(partId) ||
1033
+ (messageId && state.tombstones.has(messageId))
1034
+ ) {
1035
+ return [];
1036
+ }
1037
+
1038
+ const kind = state.parts.get(partId);
1039
+ if (kind === "reasoning") {
1040
+ if (!messageId || !isMessageOwned(messageId, state)) return [];
1041
+ // #227 threaded the provider event id through this handler (the
1042
+ // `eventId` parameter), which is exactly the replay identity f842a8b
1043
+ // said a bare reasoning delta marker lacked ("bare delta markers have no
1044
+ // replay identity and cannot extend the deadline" — the old comment
1045
+ // here, and still true for an id-less delta). A delta whose id has not
1046
+ // been seen before is real, novel work the model did; the SAME id
1047
+ // redelivered (an SSE Last-Event-ID reconnect) is not. Unlike the answer
1048
+ // branch below, nothing is accumulated into any tracked text either way
1049
+ // — a redelivered id just falls back to the bare marker, never a
1050
+ // corrupted `emittedText` or a "conflicting snapshot" throw.
1051
+ if (eventId !== undefined && !state.reasoningDeltaEventIds.has(eventId)) {
1052
+ rememberId(
1053
+ state.reasoningDeltaEventIds,
1054
+ eventId,
1055
+ MAX_TRACKED_REASONING_DELTA_EVENTS,
1056
+ );
1057
+ return [{ kind: "reasoning", progress: true }];
1058
+ }
1059
+ return [{ kind: "reasoning" }];
1060
+ }
1061
+ if (kind === "answer") {
1062
+ if (!isMessageOwned(messageId, state)) return [];
1063
+ // Identity for dedup is the provider event id, not the delta's text.
1064
+ // The SDK's SSE client reconnects with `Last-Event-ID`
1065
+ // (serverSentEvents.gen.js) and can redeliver the same event verbatim,
1066
+ // but text is the wrong signal to detect that with: a prior version of
1067
+ // this check dropped any delta that merely repeated the tail already
1068
+ // emitted, which also matches a legitimately repeated token (e.g. "b"
1069
+ // after "b" in "a","b","b","c", or a second "}" closing nested JSON).
1070
+ // That either corrupted the delivered text (when no snapshot ever
1071
+ // arrived to reveal the gap) or threw "conflicting snapshot observed"
1072
+ // once one did. An event with no id — or a non-string one — carries no
1073
+ // identity to compare, so it is always treated as novel rather than
1074
+ // assumed a duplicate.
1075
+ if (eventId !== undefined && state.deltaEventIds.has(eventId)) {
1076
+ return [];
1077
+ }
1078
+ let detail = state.partDetails.get(partId);
1079
+ if (!detail) {
1080
+ detail = {
1081
+ id: partId,
1082
+ messageId,
1083
+ type: "text",
1084
+ emittedText: "",
1085
+ };
1086
+ state.partDetails.set(partId, detail);
1087
+ }
1088
+ if (
1089
+ Buffer.byteLength(delta, "utf8") > 64 * 1024 ||
1090
+ Buffer.byteLength(detail.emittedText + delta, "utf8") > 1024 * 1024
1091
+ )
1092
+ failIntegrity(state, "delta or answer byte limit exceeded");
1093
+ trackPayload(state, `retained:${partId}`, {
1094
+ text: detail.emittedText + delta,
1095
+ });
1096
+ detail.emittedText += delta;
1097
+ // Recorded only now that the delta is actually applied — never when
1098
+ // first buffered for an unknown owner — so a buffered delta that later
1099
+ // reconciles is not mistaken for its own duplicate.
1100
+ if (eventId !== undefined) {
1101
+ rememberId(state.deltaEventIds, eventId, MAX_TRACKED_DELTA_EVENTS);
1102
+ }
1103
+ return [{ kind: "delta", text: delta }];
1104
+ }
1105
+
1106
+ if (
1107
+ messageId &&
1108
+ !state.messageDetails.has(messageId) &&
1109
+ !state.assistantMessages.has(messageId)
1110
+ ) {
1111
+ if (state.unknownOwnerBuffer.length >= MAX_UNKNOWN_OWNER_BUFFER) {
1112
+ state.integrityFailure =
1113
+ "[pr-hero] opencode client: unknown-owner buffer cap exceeded (cap exhaustion)";
1114
+ throw new Error(state.integrityFailure);
1115
+ }
1116
+ state.unknownOwnerBuffer.push({
1117
+ type: "part.delta",
1118
+ partId,
1119
+ messageId,
1120
+ raw: p,
1121
+ eventId,
1122
+ });
1123
+ }
1124
+
1125
+ return [];
1126
+ }
1127
+
1128
+ function reconcileUnknownOwnerBuffer(
1129
+ messageId: string,
1130
+ state: OpenCodeTurnState,
1131
+ ): OpenCodeClientEvent[] {
1132
+ const events: OpenCodeClientEvent[] = [];
1133
+ const remaining: UnknownOwnerObservation[] = [];
1134
+ for (const obs of state.unknownOwnerBuffer) {
1135
+ if (obs.messageId === messageId) {
1136
+ if (obs.type === "part.updated") {
1137
+ events.push(...handlePartUpdated(obs.raw, state));
1138
+ } else if (obs.type === "part.delta") {
1139
+ events.push(...handlePartDelta(obs.raw, state, obs.eventId));
1140
+ }
1141
+ } else {
1142
+ remaining.push(obs);
1143
+ }
1144
+ }
1145
+ state.unknownOwnerBuffer.length = 0;
1146
+ state.unknownOwnerBuffer.push(...remaining);
1147
+ return events;
1148
+ }
1149
+
1150
+ export function reconcileMessages(
1151
+ list: unknown[],
1152
+ state: OpenCodeTurnState,
1153
+ // #223: `emit` gates ONLY the per-part "already delivered" bookkeeping
1154
+ // below (the loop that pushes `delta` events and advances
1155
+ // `detail.emittedText`). Every other effect of a call — trackMessage/
1156
+ // trackPart identity checks, usage, errors, `detail.text` snapshot storage
1157
+ // — always runs, because a caller that discards the returned `events` still
1158
+ // needs those ingested. Defaults to true so every existing caller (the poll
1159
+ // readback at pollStatus, and every direct test) keeps today's behaviour.
1160
+ options?: { readonly emit?: boolean },
1161
+ ): {
1162
+ events: OpenCodeClientEvent[];
1163
+ terminalProof?: ProviderTerminalProof;
1164
+ finalText?: string;
1165
+ usage?: StepUsage;
1166
+ usageIncomplete?: boolean;
1167
+ failure?: string;
1168
+ } {
1169
+ const emit = options?.emit ?? true;
1170
+ if (
1171
+ list.length > MAX_TRACKED_MESSAGES ||
1172
+ state.messageDetails.size > MAX_TRACKED_MESSAGES
1173
+ ) {
1174
+ state.integrityFailure =
1175
+ "[pr-hero] opencode client: message cap exceeded (cap exhaustion)";
1176
+ return { events: [], failure: state.integrityFailure };
1177
+ }
1178
+
1179
+ if (
1180
+ state.parts.size > MAX_TRACKED_PARTS ||
1181
+ state.partDetails.size > MAX_TRACKED_PARTS
1182
+ ) {
1183
+ state.integrityFailure =
1184
+ "[pr-hero] opencode client: maximum tracked parts exceeded";
1185
+ return { events: [], failure: state.integrityFailure };
1186
+ }
1187
+
1188
+ try {
1189
+ if (Buffer.byteLength(JSON.stringify(list), "utf8") > MAX_READBACK_BYTES) {
1190
+ failIntegrity(state, "total readback byte budget exceeded");
1191
+ }
1192
+ const seenMessages = new Set<string>();
1193
+ const seenParts = new Set<string>();
1194
+ for (const item of list) {
1195
+ const rec = asRecord(item);
1196
+ const info = asRecord(rec?.info ?? item);
1197
+ if (!info) failIntegrity(state, "invalid readback message");
1198
+ trackMessage(state, info);
1199
+ if (seenMessages.has(String(info.id)))
1200
+ failIntegrity(state, "duplicate message in readback");
1201
+ seenMessages.add(String(info.id));
1202
+ if (info.role === "assistant" && !Array.isArray(rec?.parts)) {
1203
+ failIntegrity(state, "unknown readback parts coverage");
1204
+ }
1205
+ for (const value of Array.isArray(rec?.parts) ? rec.parts : []) {
1206
+ const part = asRecord(value);
1207
+ if (!part) failIntegrity(state, "invalid readback part");
1208
+ trackPart(state, part, String(info.id));
1209
+ if (seenParts.has(String(part.id)))
1210
+ failIntegrity(state, "duplicate part in readback");
1211
+ seenParts.add(String(part.id));
1212
+ }
1213
+ }
1214
+ } catch {
1215
+ return { events: [], failure: state.integrityFailure };
1216
+ }
1217
+
1218
+ for (const item of list) {
1219
+ const itemRec = asRecord(item);
1220
+ const info = asRecord(itemRec?.info ?? item);
1221
+ if (!info) continue;
1222
+ const id = typeof info.id === "string" ? info.id : undefined;
1223
+ const role = info.role;
1224
+ if (!id) continue;
1225
+
1226
+ if (role === "user") {
1227
+ if (!state.messageDetails.has(id)) {
1228
+ state.messageDetails.set(id, { id, role: "user", partIds: [] });
1229
+ }
1230
+ } else if (role === "assistant") {
1231
+ rememberId(state.assistantMessages, id, MAX_TRACKED_MESSAGES);
1232
+ const parentID =
1233
+ typeof info.parentID === "string" ? info.parentID : undefined;
1234
+ if (parentID) state.parentLinks.set(id, parentID);
1235
+
1236
+ const finish = typeof info.finish === "string" ? info.finish : undefined;
1237
+ const isToolCalls = finish === "tool-calls" || finish === "tool_calls";
1238
+ const sessionID =
1239
+ typeof info.sessionID === "string"
1240
+ ? info.sessionID
1241
+ : typeof itemRec?.sessionID === "string"
1242
+ ? (itemRec.sessionID as string)
1243
+ : undefined;
1244
+ let msgDetail = state.messageDetails.get(id);
1245
+ if (!msgDetail) {
1246
+ msgDetail = {
1247
+ id,
1248
+ role: "assistant",
1249
+ sessionID,
1250
+ parentID,
1251
+ time: asRecord(info.time) as
1252
+ | { created?: number; completed?: number }
1253
+ | undefined,
1254
+ finish,
1255
+ error: info.error,
1256
+ hasToolCalls: isToolCalls,
1257
+ partIds: [],
1258
+ };
1259
+ state.messageDetails.set(id, msgDetail);
1260
+ } else {
1261
+ msgDetail.sessionID = sessionID ?? msgDetail.sessionID;
1262
+ msgDetail.parentID = parentID ?? msgDetail.parentID;
1263
+ msgDetail.finish = finish ?? msgDetail.finish;
1264
+ msgDetail.error = info.error ?? msgDetail.error;
1265
+ msgDetail.time =
1266
+ (asRecord(info.time) as
1267
+ | { created?: number; completed?: number }
1268
+ | undefined) ?? msgDetail.time;
1269
+ if (isToolCalls) msgDetail.hasToolCalls = true;
1270
+ }
1271
+
1272
+ if (!isMessageOwned(id, state)) continue;
1273
+ const tokens = asRecord(info.tokens);
1274
+ const inputTokens = asNumber(tokens?.input);
1275
+ const outputTokens = asNumber(tokens?.output);
1276
+ const costUsd = asNumber(info.cost);
1277
+ const cacheReadTokens = asNumber(asRecord(tokens?.cache)?.read);
1278
+ const cacheWriteTokens = asNumber(asRecord(tokens?.cache)?.write);
1279
+ const reasoningTokens = asNumber(tokens?.reasoning);
1280
+ if (
1281
+ inputTokens !== undefined ||
1282
+ outputTokens !== undefined ||
1283
+ costUsd !== undefined ||
1284
+ cacheReadTokens !== undefined ||
1285
+ cacheWriteTokens !== undefined ||
1286
+ reasoningTokens !== undefined
1287
+ ) {
1288
+ rememberUsage(
1289
+ state,
1290
+ id,
1291
+ {
1292
+ ...(inputTokens !== undefined ? { inputTokens } : {}),
1293
+ ...(outputTokens !== undefined ? { outputTokens } : {}),
1294
+ ...(costUsd !== undefined ? { costUsd } : {}),
1295
+ ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),
1296
+ ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),
1297
+ ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
1298
+ },
1299
+ asNumber(asRecord(info.time)?.completed) !== undefined,
1300
+ );
1301
+ }
1302
+
1303
+ const parts = Array.isArray(itemRec?.parts)
1304
+ ? (itemRec?.parts as unknown[])
1305
+ : Array.isArray(info.content)
1306
+ ? (info.content as unknown[])
1307
+ : [];
1308
+ const readbackPartIds: string[] = [];
1309
+ for (const p of parts) {
1310
+ const part = asRecord(p);
1311
+ if (!part) continue;
1312
+ const partId = typeof part.id === "string" ? part.id : undefined;
1313
+ if (!partId) continue;
1314
+ if (!readbackPartIds.includes(partId)) readbackPartIds.push(partId);
1315
+
1316
+ const partType = part.type;
1317
+ if (partType === "tool") {
1318
+ const toolState = asRecord(part.state);
1319
+ const status = toolState?.status as
1320
+ | "pending"
1321
+ | "running"
1322
+ | "completed"
1323
+ | "error"
1324
+ | undefined;
1325
+ const callId = typeof part.callID === "string" ? part.callID : partId;
1326
+ if (status) {
1327
+ if (
1328
+ !state.toolStates.has(callId) &&
1329
+ state.toolStates.size >= MAX_TRACKED_PARTS
1330
+ )
1331
+ failIntegrity(state, "tool identity cap exceeded");
1332
+ state.toolStates.set(callId, status);
1333
+ // pr-hero review F001: recorded in the monotonic set the moment
1334
+ // THIS readback sees "completed" — never removed by a later
1335
+ // readback that reports a different status for the same callID.
1336
+ // See the field's own WHY comment on `OpenCodeTurnState`.
1337
+ if (status === "completed") {
1338
+ state.completedToolCallIds.add(callId);
1339
+ }
1340
+ }
1341
+ msgDetail.hasToolCalls = true;
1342
+ // #214: this write feeds `hasOutstandingTools` (so a message the
1343
+ // poll alone has seen is not declared final while a tool is still
1344
+ // pending/running) AND, on a poll-won terminal, `pollStatus` reports
1345
+ // `completedToolCallIds`'s members as `OpenCodePollResult
1346
+ // .completedToolCallIds` — see the WHY comment there. This call
1347
+ // site stays `emit: false` (no `{kind:"tool"}` event rides through
1348
+ // here; the stream is still the only event-emitting observer), but
1349
+ // a completion this observer is the FIRST to see is no longer
1350
+ // silently uncounted: opencode-sdk.ts unions this poll-reported set
1351
+ // with its own stream-observed callIDs by identity at settlement.
1352
+ } else if (partType === "reasoning") {
1353
+ if (
1354
+ !state.parts.has(partId) &&
1355
+ state.parts.size >= MAX_TRACKED_PARTS
1356
+ ) {
1357
+ state.integrityFailure =
1358
+ "[pr-hero] opencode client: maximum tracked parts exceeded";
1359
+ return { events: [], failure: state.integrityFailure };
1360
+ }
1361
+ state.parts.set(partId, "reasoning");
1362
+ } else if (partType === "text") {
1363
+ const isSynthetic = part.synthetic === true;
1364
+ const isIgnored = part.ignored === true;
1365
+ if (!isSynthetic && !isIgnored && !msgDetail.hasToolCalls) {
1366
+ if (
1367
+ !state.parts.has(partId) &&
1368
+ state.parts.size >= MAX_TRACKED_PARTS
1369
+ ) {
1370
+ state.integrityFailure =
1371
+ "[pr-hero] opencode client: maximum tracked parts exceeded";
1372
+ return { events: [], failure: state.integrityFailure };
1373
+ }
1374
+ state.parts.set(partId, "answer");
1375
+ let detail = state.partDetails.get(partId);
1376
+ if (!detail) {
1377
+ if (state.partDetails.size >= MAX_TRACKED_PARTS) {
1378
+ state.integrityFailure =
1379
+ "[pr-hero] opencode client: maximum tracked parts exceeded";
1380
+ return { events: [], failure: state.integrityFailure };
1381
+ }
1382
+ detail = {
1383
+ id: partId,
1384
+ messageId: id,
1385
+ type: "text",
1386
+ emittedText: "",
1387
+ };
1388
+ state.partDetails.set(partId, detail);
1389
+ }
1390
+ if (typeof part.text === "string") {
1391
+ detail.text = part.text;
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1396
+ if (Array.isArray(itemRec?.parts) || Array.isArray(info.content)) {
1397
+ msgDetail.partIds = readbackPartIds;
1398
+ }
1399
+ }
1400
+ }
1401
+
1402
+ if (
1403
+ state.parts.size > MAX_TRACKED_PARTS ||
1404
+ state.partDetails.size > MAX_TRACKED_PARTS
1405
+ ) {
1406
+ state.integrityFailure =
1407
+ "[pr-hero] opencode client: maximum tracked parts exceeded";
1408
+ return { events: [], failure: state.integrityFailure };
1409
+ }
1410
+
1411
+ // Check missing usage across all completed assistant steps
1412
+ for (const msg of state.messageDetails.values()) {
1413
+ if (msg.role === "assistant" && isMessageOwned(msg.id, state)) {
1414
+ const stepUsage = state.usage.get(msg.id);
1415
+ if (
1416
+ msg.time?.completed === undefined ||
1417
+ stepUsage === undefined ||
1418
+ stepUsage.costUsd === undefined ||
1419
+ stepUsage.inputTokens === undefined ||
1420
+ stepUsage.outputTokens === undefined
1421
+ ) {
1422
+ state.usageIncomplete = true;
1423
+ }
1424
+ }
1425
+ }
1426
+
1427
+ const candidateIds: string[] = [];
1428
+ for (let i = list.length - 1; i >= 0; i -= 1) {
1429
+ const itemRec = asRecord(list[i]);
1430
+ const info = asRecord(itemRec?.info ?? list[i]);
1431
+ if (info?.role === "assistant" && typeof info.id === "string") {
1432
+ candidateIds.push(info.id);
1433
+ }
1434
+ }
1435
+ if (candidateIds.length === 0) {
1436
+ const allIds = Array.from(state.assistantMessages);
1437
+ for (let i = allIds.length - 1; i >= 0; i -= 1) {
1438
+ candidateIds.push(allIds[i]);
1439
+ }
1440
+ }
1441
+
1442
+ for (const id of candidateIds) {
1443
+ const msgDetail = state.messageDetails.get(id);
1444
+ if (!msgDetail) continue;
1445
+
1446
+ if (msgDetail.error !== undefined) {
1447
+ const proof = terminalProofFromAssistant(msgDetail, state);
1448
+ if (proof) return { events: [], terminalProof: proof, finalText: "" };
1449
+ }
1450
+
1451
+ const evalRes = evaluateFinalAssistant(msgDetail, state);
1452
+ if (!evalRes.valid) continue;
1453
+
1454
+ const proof = terminalProofFromAssistant(msgDetail, state);
1455
+ if (proof === undefined) continue;
1456
+
1457
+ const events: OpenCodeClientEvent[] = [];
1458
+ let canonicalFinalText = "";
1459
+ for (const partId of msgDetail.partIds) {
1460
+ const detail = state.partDetails.get(partId);
1461
+ if (
1462
+ detail &&
1463
+ detail.type === "text" &&
1464
+ !detail.synthetic &&
1465
+ !detail.ignored
1466
+ ) {
1467
+ canonicalFinalText += detail.text ?? detail.emittedText ?? "";
1468
+ }
1469
+ }
1470
+
1471
+ // #223: this is the ONLY place in this function that advances
1472
+ // `detail.emittedText` or produces a `delta` event, so it is exactly what
1473
+ // `emit: false` must skip. Skipping it here rather than filtering the
1474
+ // caller's returned `events` afterward keeps the invariant literal:
1475
+ // `emittedText` cannot advance except in the same branch that hands a
1476
+ // delta to the consumer, so a discard-only caller can never leave the
1477
+ // "already delivered" bookkeeping ahead of what was actually delivered.
1478
+ for (const partId of emit ? msgDetail.partIds : []) {
1479
+ const detail = state.partDetails.get(partId);
1480
+ if (
1481
+ detail &&
1482
+ detail.type === "text" &&
1483
+ !detail.synthetic &&
1484
+ !detail.ignored
1485
+ ) {
1486
+ const snapshotText = detail.text ?? "";
1487
+ const alreadyEmitted = detail.emittedText;
1488
+ if (alreadyEmitted === snapshotText) {
1489
+ continue;
1490
+ }
1491
+ if (alreadyEmitted.length === 0) {
1492
+ detail.emittedText = snapshotText;
1493
+ events.push({ kind: "delta", text: snapshotText });
1494
+ } else if (snapshotText.startsWith(alreadyEmitted)) {
1495
+ const suffix = snapshotText.slice(alreadyEmitted.length);
1496
+ detail.emittedText = snapshotText;
1497
+ events.push({ kind: "delta", text: suffix });
1498
+ } else {
1499
+ state.integrityFailure = `[pr-hero] opencode client: conflicting snapshot in readback for part ${partId}`;
1500
+ return {
1501
+ events: [],
1502
+ failure: state.integrityFailure,
1503
+ };
1504
+ }
1505
+ }
1506
+ }
1507
+
1508
+ const totalUsage = turnUsage(state);
1509
+ const isIncomplete =
1510
+ state.usageIncomplete === true ||
1511
+ state.usageConflict === true ||
1512
+ state.usageCapped === true;
1513
+
1514
+ return {
1515
+ events,
1516
+ terminalProof: proof,
1517
+ finalText: canonicalFinalText,
1518
+ usage: totalUsage,
1519
+ usageIncomplete: isIncomplete,
1520
+ };
1521
+ }
1522
+
1523
+ return { events: [] };
1524
+ }
1525
+
1526
+ export const reconcilePartsAndDelivery = reconcileMessages;
1527
+
1528
+ export function mapOpenCodeEvents(
1529
+ raw: unknown,
1530
+ sessionId: string,
1531
+ state: OpenCodeTurnState,
1532
+ ): OpenCodeClientEvent[] {
1533
+ if (state.integrityFailure !== undefined) {
1534
+ throw new Error(state.integrityFailure);
1535
+ }
1536
+
1537
+ const type = (raw as RawEvent)?.type;
1538
+ if (typeof type !== "string") return [];
1539
+ const p = props(raw);
1540
+ if (p === undefined) return [];
1541
+
1542
+ if (p.sessionID !== sessionId) return [];
1543
+
1544
+ switch (type) {
1545
+ case "message.removed": {
1546
+ const messageId = p.messageID;
1547
+ if (typeof messageId === "string") {
1548
+ if (
1549
+ !state.tombstones.has(messageId) &&
1550
+ state.tombstones.size >= MAX_TOMBSTONES
1551
+ )
1552
+ failIntegrity(state, "tombstone cap exceeded");
1553
+ rememberId(state.tombstones, messageId, MAX_TOMBSTONES);
1554
+ if (
1555
+ messageId === state.currentUserId ||
1556
+ (state.lastProof && state.lastProof.eventId === messageId)
1557
+ ) {
1558
+ state.integrityFailure = `[pr-hero] opencode client: required message removed: ${messageId}`;
1559
+ throw new Error(state.integrityFailure);
1560
+ }
1561
+ }
1562
+ return [];
1563
+ }
1564
+
1565
+ case "message.part.removed": {
1566
+ const partId = p.partID;
1567
+ if (typeof partId === "string") {
1568
+ if (
1569
+ !state.tombstones.has(partId) &&
1570
+ state.tombstones.size >= MAX_TOMBSTONES
1571
+ )
1572
+ failIntegrity(state, "tombstone cap exceeded");
1573
+ rememberId(state.tombstones, partId, MAX_TOMBSTONES);
1574
+ const detail = state.partDetails.get(partId);
1575
+ if (
1576
+ detail &&
1577
+ detail.type === "text" &&
1578
+ (detail.emittedText.length > 0 ||
1579
+ (detail.text && detail.text.length > 0))
1580
+ ) {
1581
+ state.integrityFailure = `[pr-hero] opencode client: required part removed: ${partId}`;
1582
+ throw new Error(state.integrityFailure);
1583
+ }
1584
+ }
1585
+ return [];
1586
+ }
1587
+
1588
+ case "message.part.delta": {
1589
+ const rawId = (raw as RawEvent)?.id;
1590
+ const eventId = typeof rawId === "string" ? rawId : undefined;
1591
+ return handlePartDelta(p, state, eventId);
1592
+ }
1593
+
1594
+ case "message.part.updated": {
1595
+ return handlePartUpdated(p, state);
1596
+ }
1597
+
1598
+ case "message.updated": {
1599
+ const info = asRecord(p.info);
1600
+ if (info === undefined) return [];
1601
+ const id = typeof info.id === "string" ? info.id : undefined;
1602
+ if (!id) return [];
1603
+ trackMessage(state, info);
1604
+
1605
+ const role = info.role;
1606
+
1607
+ if (role === "user") {
1608
+ state.messageDetails.set(id, { id, role: "user", partIds: [] });
1609
+ return [];
1610
+ }
1611
+
1612
+ if (role !== "assistant") return [];
1613
+
1614
+ rememberId(state.assistantMessages, id, MAX_TRACKED_MESSAGES);
1615
+ const parentID =
1616
+ typeof info.parentID === "string" ? info.parentID : undefined;
1617
+ if (parentID) state.parentLinks.set(id, parentID);
1618
+
1619
+ const finish = typeof info.finish === "string" ? info.finish : undefined;
1620
+ const isToolCalls = finish === "tool-calls" || finish === "tool_calls";
1621
+ const sessionID =
1622
+ typeof info.sessionID === "string"
1623
+ ? info.sessionID
1624
+ : typeof p.sessionID === "string"
1625
+ ? (p.sessionID as string)
1626
+ : undefined;
1627
+ let msgDetail = state.messageDetails.get(id);
1628
+ if (!msgDetail) {
1629
+ msgDetail = {
1630
+ id,
1631
+ role: "assistant",
1632
+ sessionID,
1633
+ parentID,
1634
+ time: asRecord(info.time) as
1635
+ | { created?: number; completed?: number }
1636
+ | undefined,
1637
+ finish,
1638
+ error: info.error,
1639
+ hasToolCalls: isToolCalls,
1640
+ partIds: [],
1641
+ };
1642
+ state.messageDetails.set(id, msgDetail);
1643
+ } else {
1644
+ msgDetail.sessionID = sessionID ?? msgDetail.sessionID;
1645
+ msgDetail.parentID = parentID ?? msgDetail.parentID;
1646
+ msgDetail.finish = finish ?? msgDetail.finish;
1647
+ msgDetail.error = info.error ?? msgDetail.error;
1648
+ msgDetail.time =
1649
+ (asRecord(info.time) as
1650
+ | { created?: number; completed?: number }
1651
+ | undefined) ?? msgDetail.time;
1652
+ if (isToolCalls) msgDetail.hasToolCalls = true;
1653
+ }
1654
+
1655
+ if (!isMessageOwned(id, state)) return [];
1656
+ const out: OpenCodeClientEvent[] = [];
1657
+ out.push(...reconcileUnknownOwnerBuffer(id, state));
1658
+
1659
+ const tokens = asRecord(info.tokens);
1660
+ const inputTokens = asNumber(tokens?.input);
1661
+ const outputTokens = asNumber(tokens?.output);
1662
+ const costUsd = asNumber(info.cost);
1663
+ const cacheReadTokens = asNumber(asRecord(tokens?.cache)?.read);
1664
+ const cacheWriteTokens = asNumber(asRecord(tokens?.cache)?.write);
1665
+ const reasoningTokens = asNumber(tokens?.reasoning);
1666
+ if (
1667
+ inputTokens !== undefined ||
1668
+ outputTokens !== undefined ||
1669
+ costUsd !== undefined ||
1670
+ cacheReadTokens !== undefined ||
1671
+ cacheWriteTokens !== undefined ||
1672
+ reasoningTokens !== undefined
1673
+ ) {
1674
+ rememberUsage(
1675
+ state,
1676
+ id,
1677
+ {
1678
+ ...(inputTokens !== undefined ? { inputTokens } : {}),
1679
+ ...(outputTokens !== undefined ? { outputTokens } : {}),
1680
+ ...(costUsd !== undefined ? { costUsd } : {}),
1681
+ ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),
1682
+ ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),
1683
+ ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
1684
+ },
1685
+ asNumber(asRecord(info.time)?.completed) !== undefined,
1686
+ );
1687
+ out.push({
1688
+ kind: "usage",
1689
+ id,
1690
+ mode: "snapshot",
1691
+ ...(state.usageCapped || state.usageConflict || state.usageIncomplete
1692
+ ? { incomplete: true }
1693
+ : {}),
1694
+ ...turnUsage(state),
1695
+ });
1696
+ }
1697
+
1698
+ const proof = terminalProofFromAssistant(info, state);
1699
+ if (proof !== undefined) state.lastProof = proof;
1700
+ return out;
1701
+ }
1702
+
1703
+ case "session.idle": {
1704
+ if (state.boundaryReported) return [];
1705
+ if (state.integrityFailure !== undefined) {
1706
+ throw new Error(state.integrityFailure);
1707
+ }
1708
+ if (hasOutstandingTools(state)) return [];
1709
+
1710
+ const proof = state.lastProof;
1711
+ if (proof === undefined) return [];
1712
+ if (state.tombstones.has(proof.eventId)) {
1713
+ state.integrityFailure = `[pr-hero] opencode client: terminal message was tombstoned: ${proof.eventId}`;
1714
+ throw new Error(state.integrityFailure);
1715
+ }
1716
+ state.boundaryReported = true;
1717
+
1718
+ const out: OpenCodeClientEvent[] = [];
1719
+ const msgDetail = state.messageDetails.get(proof.eventId);
1720
+ if (msgDetail) {
1721
+ for (const partId of msgDetail.partIds) {
1722
+ if (state.tombstones.has(partId)) {
1723
+ state.integrityFailure = `[pr-hero] opencode client: required part was tombstoned: ${partId}`;
1724
+ throw new Error(state.integrityFailure);
1725
+ }
1726
+ const detail = state.partDetails.get(partId);
1727
+ if (
1728
+ detail &&
1729
+ detail.type === "text" &&
1730
+ !detail.synthetic &&
1731
+ !detail.ignored
1732
+ ) {
1733
+ const snapshotText = detail.text ?? "";
1734
+ if (snapshotText.length > 0) {
1735
+ if (detail.emittedText.length === 0) {
1736
+ detail.emittedText = snapshotText;
1737
+ out.push({ kind: "delta", text: snapshotText });
1738
+ } else if (snapshotText.startsWith(detail.emittedText)) {
1739
+ const diff = snapshotText.slice(detail.emittedText.length);
1740
+ if (diff.length > 0) {
1741
+ detail.emittedText = snapshotText;
1742
+ out.push({ kind: "delta", text: diff });
1743
+ }
1744
+ } else {
1745
+ state.integrityFailure = `[pr-hero] opencode client: conflicting snapshot observed for part ${partId}`;
1746
+ throw new Error(state.integrityFailure);
1747
+ }
1748
+ }
1749
+ }
1750
+ }
1751
+ }
1752
+
1753
+ out.push({ kind: "terminal", proof });
1754
+ return out;
1755
+ }
1756
+
1757
+ case "session.status": {
1758
+ const status = asRecord(p.status);
1759
+ // #157: checked BEFORE the busy/heartbeat arm below — a retry status
1760
+ // naming an account/usage limit is not "still working", it is a fact
1761
+ // that ends the attempt. Reached only for THIS session: the shared
1762
+ // `p.sessionID !== sessionId` guard above already returned [] for
1763
+ // every other one.
1764
+ const limit = providerLimitFromStatus(status);
1765
+ if (limit !== undefined) {
1766
+ return [
1767
+ {
1768
+ kind: "provider_limit",
1769
+ reason: limit.reason,
1770
+ message: limit.message,
1771
+ },
1772
+ ];
1773
+ }
1774
+ return status?.type === "busy" ? [{ kind: "heartbeat" }] : [];
1775
+ }
1776
+
1777
+ // #213. The subscribed bus names this `session.error` (SDK
1778
+ // EventSessionError, properties.error = APIError). `opencode run
1779
+ // --format json` prints the same refusal as `type: "error"`. Neither
1780
+ // had an arm, so the event became [] , the turn completed empty, and
1781
+ // the harness filed format_violation. The sessionID guard above already
1782
+ // dropped every other session's refusal.
1783
+ case "session.error":
1784
+ case "error": {
1785
+ const refusal = providerRefusalFromProperties(p);
1786
+ if (refusal === undefined) return [];
1787
+ return [{ kind: "provider_refusal", ...refusal }];
1788
+ }
1789
+
1790
+ default:
1791
+ return [];
1792
+ }
1793
+ }
1794
+
1795
+ // ---------------------------------------------------------------------------
1796
+ // The impure half: an OpenCodeClientLike over the real SDK.
1797
+ //
1798
+ // Everything the SDK touches is behind `OpenCodeSdkLike` and reached through
1799
+ // an injectable loader. pr-hero ships with ZERO runtime dependencies, so the
1800
+ // SDK is an OPTIONAL PEER: a Claude-only install must never pull it, and an
1801
+ // install that does route here must be told what to add rather than handed a
1802
+ // module-resolution stack trace.
1803
+ // ---------------------------------------------------------------------------
1804
+
1805
+ // BOTH arms of the SDK's `RequestResult`. With its default
1806
+ // `ThrowOnError = false` every session call resolves to either
1807
+ // `{ data, error: undefined }` or `{ data: undefined, error }` — an API error
1808
+ // is a RESOLVED promise, not a rejected one. The first version of this
1809
+ // interface declared only the success arm, so a rejected model or a bad body
1810
+ // reached `.data.id` with `data` undefined and became a TypeError carrying
1811
+ // none of the provider's diagnosis (issue #121).
1812
+ //
1813
+ // Modelled as a union rather than collapsed with `throwOnError: true`
1814
+ // deliberately: the collapse is a per-call TYPE inference on the SDK's own
1815
+ // generic signatures, and it cannot travel through a narrow non-generic
1816
+ // interface like this one — the declared return type governs at every call
1817
+ // site here. The union is the shape the transport must actually survive.
1818
+ export type OpenCodeSdkResult<T> =
1819
+ | { readonly data: T; readonly error?: undefined }
1820
+ | { readonly data?: undefined; readonly error: unknown };
1821
+
1822
+ // Deliberately narrow: the transport needs five methods, not the SDK's
1823
+ // twenty namespaces. test/conformance/opencode-sdk-surface.test.ts asserts at
1824
+ // COMPILE TIME that the real `OpencodeClient` is assignable to this, so the
1825
+ // narrowing can never drift back into a guess. Members are method shorthand,
1826
+ // not properties, on purpose — property-style function types are checked
1827
+ // contravariantly under `strict` and would reject the real client's generic
1828
+ // signatures for a reason that has nothing to do with conformance.
1829
+ export interface OpenCodeSdkPromptParameters {
1830
+ readonly sessionID: string;
1831
+ readonly directory?: string;
1832
+ readonly workspace?: string;
1833
+ readonly messageID?: string;
1834
+ readonly model?: {
1835
+ readonly providerID: string;
1836
+ readonly modelID: string;
1837
+ };
1838
+ readonly agent?: string;
1839
+ readonly noReply?: boolean;
1840
+ readonly tools?: Readonly<Record<string, boolean>>;
1841
+ readonly format?: unknown;
1842
+ readonly system?: string;
1843
+ readonly variant?: string;
1844
+ readonly parts?: readonly unknown[];
1845
+ readonly [key: string]: unknown;
1846
+ }
1847
+
1848
+ // Deliberately narrow: the transport needs five methods, not the SDK's
1849
+ // twenty namespaces. test/conformance/opencode-sdk-surface.test.ts asserts at
1850
+ // COMPILE TIME that the real `OpencodeClient` from /v2 is assignable to this,
1851
+ // so the narrowing can never drift back into a guess. Members are method shorthand,
1852
+ // not properties, on purpose — property-style function types are checked
1853
+ // contravariantly under `strict` and would reject the real client's generic
1854
+ // signatures for a reason that has nothing to do with conformance.
1855
+ export interface OpenCodeSdkClientApi {
1856
+ readonly session: {
1857
+ create(
1858
+ options?: unknown,
1859
+ request?: { signal?: AbortSignal },
1860
+ ): Promise<OpenCodeSdkResult<{ id: string; directory?: string }>>;
1861
+ prompt(
1862
+ parameters: OpenCodeSdkPromptParameters,
1863
+ request?: { signal?: AbortSignal },
1864
+ ): Promise<OpenCodeSdkResult<unknown>>;
1865
+ messages(
1866
+ options: unknown,
1867
+ request?: { signal?: AbortSignal },
1868
+ ): Promise<OpenCodeSdkResult<unknown>>;
1869
+ // `GET /session/status` — the POLL observer's turn boundary (#127), and a
1870
+ // different endpoint from session.messages(), which is the point: §197
1871
+ // wants two INDEPENDENT observers, not two pipes onto one fact. REQUIRED,
1872
+ // never optional, for the same reason `tool.ids` is: an optional member
1873
+ // lets a fake skip the surface silently, which is the shape of issue #121.
1874
+ status(
1875
+ options?: unknown,
1876
+ request?: { signal?: AbortSignal },
1877
+ ): Promise<OpenCodeSdkResult<unknown>>;
1878
+ abort(
1879
+ options?: unknown,
1880
+ request?: { signal?: AbortSignal },
1881
+ ): Promise<OpenCodeSdkResult<unknown>>;
1882
+ };
1883
+ readonly event: {
1884
+ // `parameters`, not `options`: the SDK's first argument is the parameters
1885
+ // slot (`{directory?, workspace?}`); request options are its SECOND. The
1886
+ // old name invited `subscribe({ signal })`, and the call site did exactly
1887
+ // that — buildClientParams drops unknown keys, so the signal vanished and
1888
+ // no directory was ever sent. Only the first argument is declared because
1889
+ // it is the only one the call site passes.
1890
+ subscribe(
1891
+ parameters?: unknown,
1892
+ ): Promise<{ stream: AsyncIterable<unknown> }>;
1893
+ };
1894
+ // `GET /experimental/tool/ids` — "List all tool IDs (including built-in and
1895
+ // dynamically registered)". REQUIRED, never optional: an optional member
1896
+ // lets a fake skip the surface silently, which is the shape of issue #121.
1897
+ // The endpoint is experimental-prefixed, so pinning it here (and in the
1898
+ // surface conformance test) is what keeps a rename from going unnoticed.
1899
+ readonly tool: {
1900
+ ids(
1901
+ options?: unknown,
1902
+ request?: { signal?: AbortSignal },
1903
+ ): Promise<OpenCodeSdkResult<readonly string[]>>;
1904
+ };
1905
+ // `GET /mcp` — the §E readback's endpoint, and the only place a connected
1906
+ // MCP server is visible at all: it contributes nothing to `tool.ids` or
1907
+ // `tool.list` (measured, #141 fact 3). REQUIRED, never optional, for the
1908
+ // same reason as the two above — an optional member lets a fake skip the
1909
+ // surface silently, which is the shape of issue #121, and a skipped readback
1910
+ // is an unverified tool channel rather than a missing convenience.
1911
+ readonly mcp: {
1912
+ status(
1913
+ options?: unknown,
1914
+ request?: { signal?: AbortSignal },
1915
+ ): Promise<OpenCodeSdkResult<unknown>>;
1916
+ };
1917
+ // `POST /permission/{requestID}/reply` — the ONLY way to unblock a pending
1918
+ // OpenCode permission prompt (#157: `permission.asked` for
1919
+ // `external_directory` blocked a tool call for the whole usefulProgressMs
1920
+ // budget, since pr-hero has no UI to answer one and the server-side `deny`
1921
+ // config cannot cover every future permission kind). REQUIRED, never
1922
+ // optional, for the same reason as tool.ids/mcp.status above: an optional
1923
+ // member lets a fake skip the surface silently, which is the shape of
1924
+ // issue #121, and a skipped reply here is a hung tool call with no
1925
+ // evidence anything was ever attempted.
1926
+ readonly permission: {
1927
+ reply(
1928
+ parameters: {
1929
+ requestID: string;
1930
+ directory?: string;
1931
+ workspace?: string;
1932
+ reply?: "once" | "always" | "reject";
1933
+ message?: string;
1934
+ },
1935
+ request?: { signal?: AbortSignal },
1936
+ ): Promise<OpenCodeSdkResult<unknown>>;
1937
+ };
1938
+ }
1939
+
1940
+ export interface OpenCodeSdkLike {
1941
+ // `createOpencodeClient`, and the name is the whole of issue #121: this
1942
+ // interface used to declare `createClient`, which the SDK has never
1943
+ // exported. Nothing compared the two, so every live OpenCode step died on
1944
+ // `sdk.createClient is not a function` while the offline suite stayed green
1945
+ // — every mock was shaped to the same guess.
1946
+ createOpencodeClient(config: {
1947
+ baseUrl: string;
1948
+ directory?: string;
1949
+ experimental_workspaceID?: string;
1950
+ [key: string]: unknown;
1951
+ }): OpenCodeSdkClientApi;
1952
+ }
1953
+
1954
+ // The runtime half of the conformance check. `import type` is erased, so it
1955
+ // cannot guard the DYNAMIC import the transport registry performs; the loaded
1956
+ // module is therefore validated instead of asserted. This replaces two
1957
+ // `as unknown as OpenCodeSdkLike` casts — the strongest assertion TypeScript
1958
+ // has, pointed at a hand-written guess, which is precisely why the guess was
1959
+ // never caught.
1960
+ export function assertOpenCodeSdk(module: unknown): OpenCodeSdkLike {
1961
+ const candidate = module as Partial<OpenCodeSdkLike> | null | undefined;
1962
+ if (
1963
+ candidate === null ||
1964
+ candidate === undefined ||
1965
+ typeof candidate.createOpencodeClient !== "function"
1966
+ ) {
1967
+ throw new Error(
1968
+ "@opencode-ai/sdk/v2/client resolved but does not export createOpencodeClient(), " +
1969
+ "which Crysk needs to open a session. The installed package is not " +
1970
+ `the SDK this transport was built against (got ${describeModule(module)}).`,
1971
+ );
1972
+ }
1973
+ return candidate as OpenCodeSdkLike;
1974
+ }
1975
+
1976
+ function describeModule(module: unknown): string {
1977
+ if (typeof module !== "object" || module === null) return typeof module;
1978
+ const keys = Object.keys(module).sort();
1979
+ return keys.length === 0 ? "an object with no exports" : keys.join(", ");
1980
+ }
1981
+
1982
+ // Every `.data` read in this file goes through here. The alternative — reading
1983
+ // `.data` and trusting it — is the defect.
1984
+ function unwrap<T>(result: OpenCodeSdkResult<T>, call: string): T {
1985
+ const data = result.data;
1986
+ if (result.error !== undefined || data === undefined) {
1987
+ throw new Error(
1988
+ `opencode ${call} failed: ${describeSdkError(result.error)}`,
1989
+ );
1990
+ }
1991
+ return data;
1992
+ }
1993
+
1994
+ function describeSdkError(error: unknown): string {
1995
+ if (error === undefined) return "the provider returned no data and no error";
1996
+ if (typeof error === "string") return error;
1997
+ const message = asRecord(error)?.message;
1998
+ if (typeof message === "string" && message.length > 0) return message;
1999
+ try {
2000
+ return JSON.stringify(error) ?? String(error);
2001
+ } catch {
2002
+ return String(error);
2003
+ }
2004
+ }
2005
+
2006
+ export interface CreateOpenCodeClientOptions {
2007
+ readonly loadSdk: () => Promise<OpenCodeSdkLike>;
2008
+ /** Injected only for deterministic protocol fixtures; production IDs match ^msg. */
2009
+ readonly createMessageId?: () => string;
2010
+ readonly observedIdentity?: {
2011
+ sdkVersion: string;
2012
+ serverVersion: string;
2013
+ executableSha256: string;
2014
+ };
2015
+ readonly fetch?: typeof fetch;
2016
+ /** Production factory requires actual serving identity and pinned /doc proof. */
2017
+ readonly qualifyServer?: (
2018
+ url: string,
2019
+ signal?: AbortSignal,
2020
+ ) => Promise<unknown>;
2021
+ // #141: the run's MCP registry travels INTO the launch. OpenCode reads it
2022
+ // from the environment at startup, so a server already running cannot be
2023
+ // given one without leaving a window between "server up" and "MCP
2024
+ // connected" for a prompt to fall into (the #128 race class).
2025
+ //
2026
+ // The free-tier gateway fix (see FREE_TIER_GATEWAY_TOOLS below) travels the
2027
+ // same way, for the same reason: OpenCode reads its permission config from
2028
+ // the same startup env, so it has to reach the launch, not a later call.
2029
+ readonly launchServer: (
2030
+ mcp?: OpenCodeMcpConfig,
2031
+ freeTierGatewayAsk?: readonly string[],
2032
+ ) => Promise<OpenCodeServerHandle>;
2033
+ // The credential kind this client's route was bound to. Optional so every
2034
+ // existing caller (every test, and any non-opencode-free route) keeps
2035
+ // today's behavior unchanged; only `createSession` reads it, and only to
2036
+ // gate FREE_TIER_GATEWAY_TOOLS below.
2037
+ readonly credentialKind?: CredentialKind;
2038
+ readonly model: {
2039
+ readonly providerID: string;
2040
+ readonly modelID: string;
2041
+ readonly variant?: string;
2042
+ };
2043
+ readonly variant?: string;
2044
+ readonly readSystemPrompt: (promptPath: string) => Promise<string>;
2045
+ // #141: reads the Claude-shaped mcp.json named by the request. Optional only
2046
+ // because a request may carry no registry at all; a request that DOES carry
2047
+ // one and finds no reader here aborts rather than running without MCP, which
2048
+ // is the silent degradation this issue is about.
2049
+ readonly readMcpConfig?: (configPath: string) => Promise<string>;
2050
+ // Absolute, resolved by the caller (transport-registry.ts). The client never
2051
+ // looks a binary up: resolution is a PATH question, and this module has no
2052
+ // business answering one — the same rule opencode-server.ts states for the
2053
+ // opencode binary itself.
2054
+ readonly codegraphBinaryPath?: string;
2055
+ // §6 deny floor: tools that stay false unless the spec names them. Absent is
2056
+ // NOT the same as false — an absent key asks for the provider's default, and
2057
+ // the provider's default is not ours to inherit.
2058
+ readonly denyFloor?: readonly string[];
2059
+ }
2060
+
2061
+ const DEFAULT_DENY_FLOOR = ["bash"] as const;
2062
+
2063
+ // Free-tier gateway fix (2026-09-26). OpenCode's free catalogue (provider
2064
+ // `opencode`, e.g. `opencode/muse-spark-1.3-contributor-free`) started
2065
+ // refusing every turn with `APIError status=403: ... "OpenCode's free tier
2066
+ // can only be used from within OpenCode"` whenever the tools map it receives
2067
+ // denies `bash` or `read` outright. Measured live against opencode 1.18.30
2068
+ // (`opencode serve --pure` + the real SDK, $0):
2069
+ // tools: {} -> OK
2070
+ // tools: {"bash": false} -> 403
2071
+ // tools: {"read": false} -> 403
2072
+ // any OTHER single tool set false -> OK
2073
+ // permission.bash: "deny", no tools -> 403 (OpenCode drops a denied tool
2074
+ // from the reported surface — same
2075
+ // effect on the model as sending it
2076
+ // false)
2077
+ // permission.bash: "ask" -> OK
2078
+ // permission.bash/read both "ask" -> OK
2079
+ // This worked on 2026-09-07 with the same pr-hero code, so the change is
2080
+ // provider-side policy, not a regression here.
2081
+ //
2082
+ // These are the ONLY two ids this applies to — they are exactly the ids the
2083
+ // gateway's heuristic keys on, not "every tool" and not a general relaxation.
2084
+ // A `provider_free` route (see `credentialKind` above) omits a denied id here
2085
+ // from the tools map instead of writing it `false` (see the loop right after
2086
+ // `resolveToolMap`'s own map below), and gets OpenCode permission `"ask"` for
2087
+ // it in the server's config instead (opencode-server.ts's `launchOpenCodeServer`
2088
+ // — see the WHY there for how isolation is preserved without the tools-map
2089
+ // denial). Every other route is unaffected: this constant is read nowhere
2090
+ // unless `credentialKind === "provider_free"`.
2091
+ export const FREE_TIER_GATEWAY_TOOLS = ["bash", "read"] as const;
2092
+
2093
+ // The engine's canonical tool names are Claude Code's namespace
2094
+ // (`BINDING_ALLOWED_TOOLS`, and the `tools:` line of every bundled prompt).
2095
+ // They stay that way: the gate is backend-neutral and the prompt set is shared
2096
+ // across backends, so the translation into a provider's vocabulary belongs
2097
+ // HERE and nowhere else.
2098
+ //
2099
+ // Issue #122: this table did not exist, and the canonical names were written
2100
+ // into the prompt's `tools` map verbatim. That map is an OPEN
2101
+ // `{[key: string]: boolean}`, so OpenCode accepted "Read"/"Grep"/"Glob"/
2102
+ // "mcp__codegraph__codegraph_explore" and silently ignored all four — no
2103
+ // error, no warning, nothing in the response. The allowlist allowed nothing
2104
+ // and the denylist denied only "bash", which landed by pure naming
2105
+ // coincidence.
2106
+ //
2107
+ // #141: `mcp__codegraph__codegraph_explore` used to be absent from this table,
2108
+ // on the grounds that it mapped onto no OpenCode built-in and that dropping it
2109
+ // was parity with a codegraph-less repo. That was true of the TABLE and false
2110
+ // of the ROUTE: `mcpConfigPath` was threaded all the way into createSession
2111
+ // and then applied to nothing, so every OpenCode hunter ran without codegraph
2112
+ // even on an indexed repo — a silent capability gap between the two backends,
2113
+ // invisible in any artifact because the map recorded only ids the provider
2114
+ // reported.
2115
+ //
2116
+ // The id is OpenCode's `<server>_<tool>` normalisation of the codegraph
2117
+ // server's single tool, and it is MEASURED rather than derived (#141 fact 4):
2118
+ // with this key written false the model answered REFUSED and no tool call
2119
+ // appeared in the stream. Parity for the codegraph-less case is unchanged and
2120
+ // now explicit — an empty registry leaves the key written FALSE rather than
2121
+ // absent.
2122
+ const CANONICAL_TO_OPENCODE_TOOL: Readonly<Record<string, string>> = {
2123
+ Read: "read",
2124
+ Grep: "grep",
2125
+ Glob: "glob",
2126
+ mcp__codegraph__codegraph_explore: "codegraph_codegraph_explore",
2127
+ };
2128
+
2129
+ const MCP_TOOL_ID_SET: ReadonlySet<string> = new Set(ALL_MCP_TOOL_IDS);
2130
+
2131
+ // Which of `freeTierGatewayTools` (empty unless credentialKind is
2132
+ // "provider_free" — see FREE_TIER_GATEWAY_TOOLS above) this session's own
2133
+ // canonical grant list does NOT cover. Deliberately independent of the
2134
+ // provider's reported tool surface: `createSession` needs this answer BEFORE
2135
+ // the server even exists, to launch it with the right permission config
2136
+ // (§128's surface enumeration only happens after create+subscribe, which
2137
+ // needs a server), so it reads grants the same way resolveToolMap's own allow
2138
+ // loop does below — via CANONICAL_TO_OPENCODE_TOOL — rather than waiting on
2139
+ // `tool.ids()`. "bash" has no entry in that table at all (no AgentSpec has
2140
+ // ever granted it), so it is unconditionally denied whenever this is called
2141
+ // with a non-empty gate; "read" is denied exactly when this call's canonical
2142
+ // tools omit "Read" (a tool-less step: summarizer, scout).
2143
+ function deniedFreeTierGatewayTools(
2144
+ canonicalTools: readonly string[],
2145
+ freeTierGatewayTools: readonly string[],
2146
+ ): readonly string[] {
2147
+ const grantedIds = new Set(
2148
+ canonicalTools
2149
+ .map((tool) => CANONICAL_TO_OPENCODE_TOOL[tool])
2150
+ .filter((id): id is string => id !== undefined),
2151
+ );
2152
+ return freeTierGatewayTools.filter((tool) => !grantedIds.has(tool));
2153
+ }
2154
+
2155
+ // Fail-closed launch-seam guard. The tools-map deletion loop further down
2156
+ // (search FREE_TIER_GATEWAY_TOOLS) is safe ONLY on the assumption that the
2157
+ // server behind `handle` was launched with `deniedGatewayTools` set to
2158
+ // OpenCode permission "ask" — that is the ONLY thing standing between a
2159
+ // deleted `bash: false` and bash running under OpenCode's default
2160
+ // permission. `launchServer` is caller-injectable
2161
+ // (`CreateOpenCodeClientOptions.launchServer` / `TransportFactoryOptions.
2162
+ // launchServer`), so that assumption is a claim about an ARGUMENT, not a
2163
+ // fact about this module — a launcher that silently ignores its second
2164
+ // parameter (or was never updated to honour it) would make it false with no
2165
+ // visible symptom until a live gateway 403, or worse, a bash call that
2166
+ // should have been denied actually running.
2167
+ //
2168
+ // Verified, not trusted: `handle.gatewayAsk` is the launcher's OWN
2169
+ // attestation of what it wrote, and this compares it against exactly what
2170
+ // this call asked to have gated — sorted, so key order never causes a
2171
+ // false mismatch. Gated on a non-empty ask: a route that asks for nothing
2172
+ // (every non-`provider_free` route) needs no attestation, and passes
2173
+ // regardless of what a handle does or does not attest.
2174
+ function gatewayAskAttestationError(
2175
+ deniedGatewayTools: readonly string[],
2176
+ attestedGatewayAsk: readonly string[] | undefined,
2177
+ ): string | undefined {
2178
+ if (deniedGatewayTools.length === 0) return undefined;
2179
+ const expected = [...deniedGatewayTools].sort();
2180
+ const attested = [...(attestedGatewayAsk ?? [])].sort();
2181
+ const matches =
2182
+ expected.length === attested.length &&
2183
+ expected.every((tool, index) => tool === attested[index]);
2184
+ if (matches) return undefined;
2185
+ return (
2186
+ "the opencode server did not attest the free-tier gateway ask posture " +
2187
+ `this session requires (expected [${expected.join(", ")}], attested ` +
2188
+ `[${attested.join(", ")}]); refusing to lift bash/read off the ` +
2189
+ "tools-map deny list before a session is created. The deletion is only " +
2190
+ "safe because the server gates those tools itself on its own " +
2191
+ "permission surface — an unattested server would leave bash at " +
2192
+ "OpenCode's default permission instead."
2193
+ );
2194
+ }
2195
+
2196
+ // ENUMERATE, never trust a default. Every id the provider reports is written
2197
+ // into the map explicitly — the allows true, everything else false — so no key
2198
+ // is ever absent. An absent key asks for the provider's default, and
2199
+ // opencode.ai/docs/tools says "By default, all tools are enabled": leaving
2200
+ // `write`, `edit`, `apply_patch` or `task` absent hands the model exactly the
2201
+ // tools §6 exists to withhold. Enumerating makes the question moot rather than
2202
+ // answering it, which is the only durable form of the fix.
2203
+ function resolveToolMap(
2204
+ surface: readonly string[],
2205
+ canonicalTools: readonly string[],
2206
+ denyFloor: readonly string[],
2207
+ // #141: the MCP tool ids this session's registry actually delivers. Empty
2208
+ // when no registry was delivered — which is the common case and the parity
2209
+ // case, not an error.
2210
+ deliveredMcpToolIds: ReadonlySet<string>,
2211
+ ): Record<string, boolean> {
2212
+ const tools: Record<string, boolean> = {};
2213
+ for (const id of surface) tools[id] = false;
2214
+ // #141: MCP ids are legitimately ABSENT from the reported surface. Measured
2215
+ // on both endpoints, both providers, before and after connect: a connected
2216
+ // MCP server contributes nothing to `tool.ids()` or `tool.list()`, and the
2217
+ // SDK docstring promising "including built-in and dynamically registered" is
2218
+ // simply wrong about MCP. So they are seeded from pr-hero's own table — the
2219
+ // enumeration rule is unchanged, only its source differs for these ids.
2220
+ for (const id of ALL_MCP_TOOL_IDS) tools[id] = false;
2221
+ // Defense in depth. Ordering is unchanged from before the fix — the floor is
2222
+ // written first and a named allow may still flip it (`denyFloor`'s contract
2223
+ // says so) — but no canonical name in the table above maps onto a floor id,
2224
+ // so the floor cannot be lifted by a prompt's `tools:` line.
2225
+ for (const tool of denyFloor) tools[tool] = false;
2226
+ for (const canonical of canonicalTools) {
2227
+ const id = CANONICAL_TO_OPENCODE_TOOL[canonical];
2228
+ // Two separate drops, both intentional. An unmapped canonical name (the
2229
+ // codegraph MCP tool) has no built-in to name; an id the provider did not
2230
+ // report is not on this build's surface. Writing either one in would be
2231
+ // the absent-key hazard in reverse — a key we invented, meaning whatever
2232
+ // the provider decides it means.
2233
+ if (id === undefined) continue;
2234
+ // An MCP id can only be allowed by a registry that actually delivered it.
2235
+ // The `id in tools` guard below cannot make this call — the id is seeded
2236
+ // above, so it is always present — and it must not be allowed to: writing
2237
+ // true for a server that was never launched would grant the model a tool
2238
+ // that does not exist and hide the gap #141 exists to close.
2239
+ if (MCP_TOOL_ID_SET.has(id)) {
2240
+ if (deliveredMcpToolIds.has(id)) tools[id] = true;
2241
+ continue;
2242
+ }
2243
+ if (!(id in tools)) continue;
2244
+ tools[id] = true;
2245
+ }
2246
+ return tools;
2247
+ }
2248
+
2249
+ interface SessionState {
2250
+ evidence: OpenCodeEvidenceCollector;
2251
+ readonly api: OpenCodeSdkClientApi;
2252
+ // ONE consumer of the subscription, ever. The pump owns the iterator and
2253
+ // hands events over through this queue; streamEvents never touches the
2254
+ // stream itself. Two for-awaits on one async iterator is a race with two
2255
+ // losing sides: the second consumer can miss an event the first already
2256
+ // took, and either one exiting fires an implicit .return() that ends the
2257
+ // SHARED generator under the other. pr-hero found exactly that here
2258
+ // (F002/F003 on PR #84) — in a repo that had already written the hazard
2259
+ // down, in opencode-sdk.ts, and walked into it anyway.
2260
+ readonly queue: unknown[];
2261
+ queueBytes: number;
2262
+ // #124: partID → part kind, correlated from `message.part.updated`. #127
2263
+ // added the turn's proof and usage accumulators alongside them. Lives on the
2264
+ // session because that is the scope both are valid in, and because they must
2265
+ // be released with the session rather than with the client.
2266
+ readonly turn: OpenCodeTurnState;
2267
+ // #127, and OWNED BY THE POLL OBSERVER ALONE — never written from the
2268
+ // stream. `GET /session/status` reports a working session as busy and simply
2269
+ // OMITS one that is not working (measured against opencode 1.18.23; see
2270
+ // pollStatus), so absence is this observer's boundary. Absence is also
2271
+ // exactly what a wrong directory scope looks like, and the two are
2272
+ // indistinguishable in the response — so absence only counts once this
2273
+ // observer has proved, through its own endpoint, that it can see this
2274
+ // session at all.
2275
+ observedActive: boolean;
2276
+ ended: boolean;
2277
+ wake?: () => void;
2278
+ // The handoff can end two ways. The pump ending is an EOF and says nothing
2279
+ // about the turn; this says the turn never started, and carries the
2280
+ // provider's diagnosis to the consumer instead of leaving it to infer a
2281
+ // silence. Set only for a failure the stream itself could never report,
2282
+ // because a refused prompt creates no message and therefore no events.
2283
+ //
2284
+ // Read by BOTH observers, and that is not redundancy. streamEvents can only
2285
+ // see this while it is still being read, and the pump ends the handoff
2286
+ // asynchronously from the prompt it knows nothing about — so when the pump
2287
+ // wins that race the stream reader is already gone and pollStatus is the
2288
+ // only door left. §197 asks for two independent observers of one fact; one
2289
+ // observer plus a blind spot is not that.
2290
+ failure?: string;
2291
+ // PR #228 review, F002: `permission.asked` requestIDs already replied to
2292
+ // or currently in flight. An SSE Last-Event-ID reconnect can redeliver an
2293
+ // event this session already saw (the same hazard #227 dedupes for stream
2294
+ // deltas via OpenCodeTurnState.deltaEventIds) — a replayed permission.asked
2295
+ // must not send a second reply for a request the server already closed.
2296
+ // Added to BEFORE the reply is awaited, not after it resolves, so a
2297
+ // duplicate arriving while the first reply is still in flight also skips.
2298
+ readonly respondedPermissions: Set<string>;
2299
+ }
2300
+
2301
+ // #141. Returns an EMPTY registry for a request that names none, which is the
2302
+ // parity case rather than an error: a repo with no `.codegraph` index gets
2303
+ // {"mcpServers":{}} from the driver (src/cli.ts:1263-1272) and its hunters run
2304
+ // on read/grep/glob, exactly as they do on claude-code.
2305
+ async function resolveMcpConfig(
2306
+ options: CreateOpenCodeClientOptions,
2307
+ input: OpenCodeCreateSessionInput,
2308
+ ): Promise<OpenCodeMcpConfig> {
2309
+ const configPath = input.mcpConfigPath;
2310
+ if (configPath === undefined) return {};
2311
+ const read = options.readMcpConfig;
2312
+ // Aborts rather than proceeding without MCP. Silently skipping is the whole
2313
+ // of #141: the path was threaded through three layers and applied to
2314
+ // nothing, so an indexed repo's hunters ran blind and no artifact said so.
2315
+ if (read === undefined) {
2316
+ throw new Error(
2317
+ `the request names an mcp registry (${configPath}) but this opencode ` +
2318
+ "client has no reader for it, so MCP cannot be delivered; refusing to " +
2319
+ "run a step without the tools it was configured with",
2320
+ );
2321
+ }
2322
+ return translateMcpConfig({
2323
+ json: await read(configPath),
2324
+ configPath,
2325
+ cwd: input.cwd,
2326
+ ...(options.codegraphBinaryPath === undefined
2327
+ ? {}
2328
+ : { codegraphBinaryPath: options.codegraphBinaryPath }),
2329
+ });
2330
+ }
2331
+
2332
+ // bun-types 1.3.14 does not declare Bun's `timeout` fetch option on
2333
+ // RequestInit (or on BunFetchRequestInit, which only extends it) even though
2334
+ // Bun's runtime honours it — see the WHY comment at the call site below for
2335
+ // what this buys. A narrow local type spells the one field needed instead of
2336
+ // widening RequestInit itself.
2337
+ type FetchInitWithIdleTimeoutDisabled = RequestInit & {
2338
+ readonly timeout: false;
2339
+ };
2340
+
2341
+ // Distinguishes the ONE request this client fires that legitimately blocks
2342
+ // past Bun's default HTTP idle timeout: POST /session/{sessionID}/message
2343
+ // (session.prompt) only returns response headers once the whole model turn
2344
+ // finishes. Anchored so it never matches:
2345
+ // - GET /session/{sessionID}/message (session.messages: the poll
2346
+ // readback, answers immediately, must keep the default timeout)
2347
+ // - GET/DELETE /session/{sessionID}/message/{id} (getMessage/deleteMessage
2348
+ // — the single-message endpoint; the SDK never POSTs here, but the extra
2349
+ // path segment must be rejected regardless of method)
2350
+ // - POST /session/{sessionID}/prompt_async
2351
+ // - POST /session (session.create)
2352
+ // A query string (e.g. `?directory=...`, which every one of these calls
2353
+ // carries) never defeats the match: only pathname is checked.
2354
+ export function isBlockingPromptRequest(request: Request): boolean {
2355
+ if (request.method !== "POST") return false;
2356
+ const { pathname } = new URL(request.url);
2357
+ return /^\/session\/[^/]+\/message$/.test(pathname);
2358
+ }
2359
+
2360
+ export function createOpenCodeClient(
2361
+ options: CreateOpenCodeClientOptions,
2362
+ ): OpenCodeClientLike & { close(): Promise<void> } {
2363
+ const states = new Map<string, SessionState>();
2364
+ const captures = new Map<string, OpenCodeEvidenceCollector>();
2365
+ const denyFloor = options.denyFloor ?? DEFAULT_DENY_FLOOR;
2366
+ // ONE server for the whole client, launched lazily. A server per SESSION
2367
+ // left a spawned process behind for every attempt, released only by a
2368
+ // whole-client close() that is not even part of OpenCodeClientLike
2369
+ // (pr-hero F004 on PR #84). One server hosts many sessions; that is what
2370
+ // the session API is for.
2371
+ let serverPromise: Promise<OpenCodeServerHandle> | undefined;
2372
+ let server: OpenCodeServerHandle | undefined;
2373
+ // #141: the registry the shared server was actually launched with, as its
2374
+ // own JSON. The readback (§E) compares NAMES, and names are not the whole
2375
+ // config: two sessions on different trees would agree on "codegraph" while
2376
+ // disagreeing on the `-p <cwd>` baked into the command at spawn — which is
2377
+ // precisely the wrong-tree failure `-p` exists to prevent, and it would be
2378
+ // invisible to every other check here. Production does not hit this today
2379
+ // (one cwd per pipeline); the guard is for the day that changes.
2380
+ let launchedMcp: string | undefined;
2381
+ // Same guard, same reason, for the free-tier gateway ask set (see
2382
+ // FREE_TIER_GATEWAY_TOOLS). The registry caches ONE opencode client per
2383
+ // route (transport-registry.ts), so every step routed to the same
2384
+ // provider_free model shares this server — a hunter-shaped step (grants
2385
+ // read) and a tool-less step (summarizer/scout) on that SAME route would
2386
+ // otherwise silently ride whichever one's ask set the server happened to be
2387
+ // launched with. This is fixed at spawn exactly like the MCP registry
2388
+ // above, and the pipeline's own phase boundaries (hunters all finish before
2389
+ // dedupe releases the idle server, refuter/scout run in a later phase)
2390
+ // mean a real run only ever asks this server to relaunch, never to change
2391
+ // shape mid-flight — a genuine concurrent mismatch fails loud instead of
2392
+ // silently weakening.
2393
+ let launchedGatewayAsk: string | undefined;
2394
+ // Calls that have committed to the shared server but have not registered a
2395
+ // session yet. `states` alone cannot answer "is anyone using this?": its
2396
+ // entry appears only after session.create AND event.subscribe both
2397
+ // succeed, so a sibling mid-establishment is invisible to it — and a
2398
+ // failing call would then SIGTERM the server that healthy sibling is using.
2399
+ // Sharing one server is what created this hazard; per-session servers could
2400
+ // not have had it.
2401
+ let establishing = 0;
2402
+
2403
+ function stateFor(session: OpenCodeClientSession): SessionState {
2404
+ const state = states.get(session.id);
2405
+ if (state === undefined) {
2406
+ throw new Error(`unknown opencode session: ${session.id}`);
2407
+ }
2408
+ return state;
2409
+ }
2410
+
2411
+ // Shared by createSession's unwind and abort(). `states` alone cannot
2412
+ // answer "is anyone using this?" while a sibling is still establishing,
2413
+ // so both counters have to be zero.
2414
+ async function releaseIdleServer(): Promise<void> {
2415
+ if (establishing !== 0 || states.size !== 0) return;
2416
+ const dying = server;
2417
+ serverPromise = undefined;
2418
+ server = undefined;
2419
+ launchedMcp = undefined;
2420
+ // Reset with its sibling: the next launch records a fresh posture, and
2421
+ // this releases the only thing that makes a different posture legal.
2422
+ launchedGatewayAsk = undefined;
2423
+ if (dying !== undefined) await dying.close().catch(() => {});
2424
+ }
2425
+
2426
+ return {
2427
+ takeEvidence(sessionId, attempt) {
2428
+ const key = `${sessionId}:${attempt}`;
2429
+ const collector = captures.get(key);
2430
+ captures.delete(key);
2431
+ return collector?.snapshot();
2432
+ },
2433
+ async createSession(
2434
+ input: OpenCodeCreateSessionInput,
2435
+ ): Promise<OpenCodeClientSession> {
2436
+ const evidence = new OpenCodeEvidenceCollector(
2437
+ input.correlation ?? { sessionId: "unavailable", attempt: 0 },
2438
+ );
2439
+ if (input.correlation)
2440
+ captures.set(
2441
+ `${input.correlation.sessionId}:${input.correlation.attempt}`,
2442
+ evidence,
2443
+ );
2444
+ evidence.record("runtime_identity", options.observedIdentity ?? null);
2445
+ const checkCancelled = () => input.signal?.throwIfAborted();
2446
+ checkCancelled();
2447
+ // Free-tier gateway fix: computed once, up front, from this call's OWN
2448
+ // canonical tools — needed below at the server-launch decision (before
2449
+ // any server exists) AND again once the tools map is resolved (so the
2450
+ // same ids never get written `false` there either). Empty for every
2451
+ // route but `provider_free`, so both uses are no-ops elsewhere.
2452
+ const freeTierGatewayTools: readonly string[] =
2453
+ options.credentialKind === "provider_free"
2454
+ ? FREE_TIER_GATEWAY_TOOLS
2455
+ : [];
2456
+ const deniedGatewayTools = deniedFreeTierGatewayTools(
2457
+ input.tools,
2458
+ freeTierGatewayTools,
2459
+ );
2460
+ const requestOptions = { signal: input.signal };
2461
+ let cleanupDeadline: number | undefined;
2462
+ const cleanup = async (
2463
+ work: (signal: AbortSignal) => Promise<unknown>,
2464
+ ) => {
2465
+ const controller = new AbortController();
2466
+ cleanupDeadline ??= performance.now() + 1_000;
2467
+ const remaining = Math.max(0, cleanupDeadline - performance.now());
2468
+ let timer: ReturnType<typeof setTimeout> | undefined;
2469
+ try {
2470
+ await Promise.race([
2471
+ work(controller.signal),
2472
+ new Promise<void>((resolve) => {
2473
+ timer = setTimeout(() => {
2474
+ controller.abort();
2475
+ resolve();
2476
+ }, remaining);
2477
+ }),
2478
+ ]);
2479
+ } finally {
2480
+ if (timer !== undefined) clearTimeout(timer);
2481
+ controller.abort();
2482
+ }
2483
+ };
2484
+ let sdk: OpenCodeSdkLike;
2485
+ try {
2486
+ sdk = await options.loadSdk();
2487
+ checkCancelled();
2488
+ } catch (error) {
2489
+ throw new Error(
2490
+ "the opencode backend needs @opencode-ai/sdk, which is an optional " +
2491
+ "peer dependency of Crysk. Install it alongside Crysk to use " +
2492
+ `this backend. (${(error as Error).message})`,
2493
+ );
2494
+ }
2495
+
2496
+ // Read BEFORE anything is spawned. It is the one step that fails on the
2497
+ // operator's filesystem, and doing it first means an unreadable prompt
2498
+ // costs nothing to unwind. pr-hero F005 found it running AFTER the
2499
+ // server, the remote session and the registered state — leaking all
2500
+ // three, with the caller never given the id needed to abort any of them.
2501
+ const systemPrompt = await options.readSystemPrompt(
2502
+ input.systemPromptPath,
2503
+ );
2504
+
2505
+ // #141: read and translated BEFORE anything is spawned, for the same
2506
+ // F005 reason as the system prompt — a registry that cannot be honoured
2507
+ // must cost nothing to unwind — and because §D needs the config in hand
2508
+ // at launch, not after it.
2509
+ const mcpConfig = await resolveMcpConfig(options, input);
2510
+ checkCancelled();
2511
+ const mcpFingerprint = JSON.stringify(mcpConfig);
2512
+ // Order-independent: two calls that deny the same set in different
2513
+ // orders must fingerprint identically.
2514
+ const gatewayAskFingerprint = JSON.stringify(
2515
+ [...deniedGatewayTools].sort(),
2516
+ );
2517
+
2518
+ if (serverPromise === undefined) {
2519
+ serverPromise = options.launchServer(mcpConfig, deniedGatewayTools);
2520
+ // Recorded synchronously, before the first await: a sibling call that
2521
+ // arrives mid-launch must compare against this launch, not against
2522
+ // whatever it would have asked for.
2523
+ launchedMcp = mcpFingerprint;
2524
+ launchedGatewayAsk = gatewayAskFingerprint;
2525
+ try {
2526
+ server = await serverPromise;
2527
+ } catch (error) {
2528
+ // A failed launch must not poison the client forever.
2529
+ serverPromise = undefined;
2530
+ launchedMcp = undefined;
2531
+ launchedGatewayAsk = undefined;
2532
+ throw error;
2533
+ }
2534
+ } else if (
2535
+ launchedMcp !== mcpFingerprint ||
2536
+ launchedGatewayAsk !== gatewayAskFingerprint
2537
+ ) {
2538
+ throw new Error(
2539
+ "the opencode server for this client was launched with a different " +
2540
+ "MCP registry or free-tier gateway permission set; its servers " +
2541
+ "are fixed at spawn, so this session would silently ride the " +
2542
+ "first one's project scope or isolation posture",
2543
+ );
2544
+ }
2545
+ const handle = server ?? (await serverPromise);
2546
+ checkCancelled();
2547
+ // Free-tier gateway fix: verify the launch seam's assumption BEFORE
2548
+ // the tools-map deletion loop, tool enumeration, session.create, or
2549
+ // any prompt — see gatewayAskAttestationError's WHY above.
2550
+ const gatewayAttestationError = gatewayAskAttestationError(
2551
+ deniedGatewayTools,
2552
+ handle.gatewayAsk,
2553
+ );
2554
+ if (gatewayAttestationError !== undefined) {
2555
+ // No session of this call exists yet, so an otherwise idle server is
2556
+ // released here rather than left running until the run tears down;
2557
+ // one shared with live sessions stays up for them.
2558
+ await releaseIdleServer();
2559
+ throw new Error(gatewayAttestationError);
2560
+ }
2561
+ const api = sdk.createOpencodeClient({
2562
+ baseUrl: handle.url,
2563
+ fetch: evidence.wrapFetch((request) => {
2564
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2565
+ // Bun's fetch has a default 300s HTTP idle timeout
2566
+ // (BUN_CONFIG_HTTP_IDLE_TIMEOUT) that is armed while waiting for
2567
+ // response headers and is NOT re-armed by "the request is still
2568
+ // legitimately in flight" — only by socket activity. The blocking
2569
+ // prompt POST's headers only arrive once the whole model turn
2570
+ // completes (measured: real turns exceed 300s), and a REJECTION
2571
+ // here — a bare TimeoutError included — ends the entire turn: the
2572
+ // catch a short way below sets `state.failure` and `state.ended`,
2573
+ // even though the event stream (the actual delivery channel, see
2574
+ // the "FIRED, never awaited" comment on the call site) may still be
2575
+ // progressing normally. Live evidence: two hunters on a real PR
2576
+ // died at ~300s this way.
2577
+ //
2578
+ // The override is scoped to exactly that one request via
2579
+ // isBlockingPromptRequest — every other call in this file (session
2580
+ // create, /event's SSE subscription, mcp.status, tool.ids,
2581
+ // /session/status, abort, message readback) returns promptly and
2582
+ // keeps today's exact single-argument call shape unchanged.
2583
+ //
2584
+ // Cancellation is unaffected: the Request built by the SDK still
2585
+ // carries `requestOptions.signal` regardless of this second
2586
+ // argument, so an abort during a `timeout: false` call still
2587
+ // rejects the way it always has.
2588
+ if (isBlockingPromptRequest(request)) {
2589
+ const init: FetchInitWithIdleTimeoutDisabled = { timeout: false };
2590
+ return fetchImpl(request, init);
2591
+ }
2592
+ return fetchImpl(request);
2593
+ }),
2594
+ });
2595
+
2596
+ let sessionId: string | undefined;
2597
+ let subscription: { stream: AsyncIterable<unknown> } | undefined;
2598
+ establishing += 1;
2599
+ try {
2600
+ const qualification = await options.qualifyServer?.(
2601
+ handle.url,
2602
+ input.signal,
2603
+ );
2604
+ evidence.record("server_qualification", qualification ?? null);
2605
+ checkCancelled();
2606
+ // §E, and FIRST: the OpenCode analogue of claude-code's
2607
+ // `--strict-mcp-config`, except claude-code DECLARES its isolation
2608
+ // with a flag and this reads the connected set back from the provider.
2609
+ // Verified beats declared, and the concrete threat is measured (#141
2610
+ // fact 7): `--pure` suppresses neither config-delivered nor
2611
+ // config-FILE MCP servers, so a server that ever saw the operator's
2612
+ // real HOME connects whatever ~/.config/opencode/opencode.jsonc names.
2613
+ // Production is shielded only INCIDENTALLY, by the synthetic
2614
+ // XDG_CONFIG_HOME the credential projection happens to set — and
2615
+ // nothing else here could notice the difference, since a connected MCP
2616
+ // server contributes nothing to the tool surface enumerated below.
2617
+ //
2618
+ // The `directory` scope mirrors what the request asked for, and the
2619
+ // #127 analogue was checked rather than assumed. session.status
2620
+ // reported {} for a BUSY session given a directory other than the
2621
+ // one its session was created under (#223) — so pollStatus below
2622
+ // passes the SAME directory session.create used, never omits it —
2623
+ // and the obvious worry was that mcp.status scopes the same way and
2624
+ // would then abort every PR-mode step, since the server inherits
2625
+ // pr-hero's cwd and never the worktree.
2626
+ //
2627
+ // It does not. MEASURED against a real PR worktree, with the server's
2628
+ // cwd deliberately elsewhere: `directory` set to the worktree, to the
2629
+ // server's own cwd, to /tmp, and omitted altogether all returned the
2630
+ // same `{"codegraph":{"status":"connected"}}`. A config-delivered MCP
2631
+ // server belongs to the server process, not to a directory. The
2632
+ // mismatch arm in scripts/opencode-mcp-probe.ts runs by default and
2633
+ // re-derives this, so a provider that starts scoping it is a probe
2634
+ // failure rather than a silent PR-mode outage.
2635
+ assertMcpConnected(
2636
+ unwrap(
2637
+ await api.mcp.status({ directory: input.cwd }, requestOptions),
2638
+ "mcp.status",
2639
+ ),
2640
+ Object.keys(mcpConfig),
2641
+ );
2642
+
2643
+ checkCancelled();
2644
+ const created = await api.session.create(
2645
+ {
2646
+ directory: input.cwd,
2647
+ title: "crysk review step",
2648
+ },
2649
+ requestOptions,
2650
+ );
2651
+ const sessionRecord = unwrap(created, "session.create");
2652
+ sessionId = sessionRecord.id;
2653
+ checkCancelled();
2654
+ if (
2655
+ typeof sessionRecord.directory !== "string" ||
2656
+ canonicalDirectory(sessionRecord.directory) !==
2657
+ canonicalDirectory(input.cwd)
2658
+ ) {
2659
+ throw new Error(
2660
+ `opencode session created with mismatched directory: expected ${input.cwd}, got ${sessionRecord.directory}`,
2661
+ );
2662
+ }
2663
+
2664
+ // Subscribed BEFORE the prompt, and the ordering is not stylistic.
2665
+ // event.subscribe() is live and unbuffered, so a subscription opened
2666
+ // afterwards silently loses the early events — the ones carrying the
2667
+ // first deltas. The contract splits createSession and streamEvents
2668
+ // into separate calls, so unless the buffering happens here that
2669
+ // window cannot be closed at all.
2670
+ //
2671
+ // #223: `directory` here MUST be the same one session.create used
2672
+ // above (input.cwd) — GET /event is scoped by directory instance,
2673
+ // exactly like GET /session/status (see pollStatus). Measured
2674
+ // against opencode 1.18.30: a subscription opened under a different
2675
+ // directory than the session's own sees only
2676
+ // server.connected/heartbeat and never this session's events at all.
2677
+ //
2678
+ // `requestOptions` (`{signal}`) is deliberately NOT passed here. It
2679
+ // used to be passed as the FIRST argument — the SDK's parameters
2680
+ // slot, not its request-options slot — where buildClientParams drops
2681
+ // unknown keys, so the SSE request has never carried an abort signal;
2682
+ // stream close has always been owned by cleanup's `return()`. Moving
2683
+ // it to the second argument would change live cancellation semantics
2684
+ // (an AbortError inside the pump) that no fake here exercises, since
2685
+ // the fakes ignore call options. That is a separate change.
2686
+ subscription = await api.event.subscribe({ directory: input.cwd });
2687
+ evidence.record("subscription_ready", { sessionId });
2688
+ checkCancelled();
2689
+
2690
+ // #128: enumerate AFTER create+subscribe, immediately before the
2691
+ // prompt. The map is a snapshot of tool.ids(); an id registered in
2692
+ // the window is an absent key, and OpenCode's default is "all tools
2693
+ // enabled". There is no atomic tools surface (open map, no wildcard),
2694
+ // so this is the remaining narrowing: [ids → prompt] instead of
2695
+ // [ids → create → subscribe → prompt]. Still inside the try after
2696
+ // `establishing += 1` so a failure unwinds through `finally`.
2697
+ //
2698
+ // WHY before the pump, not after. Starting the pump and THEN awaiting
2699
+ // tool.ids lets a finite stream drain into the queue during that
2700
+ // HTTP round-trip. The live provider has no turn events yet (the
2701
+ // prompt has not fired), so nothing is lost by enumerating first;
2702
+ // a test fixture that yields its whole stream synchronously would
2703
+ // otherwise dump every delta into one stall window.
2704
+ let reported: readonly string[];
2705
+ try {
2706
+ reported = unwrap(
2707
+ await api.tool.ids({ directory: input.cwd }, requestOptions),
2708
+ "tool.ids",
2709
+ );
2710
+ } catch (error) {
2711
+ // Rethrown with context, never swallowed. The provider's own text is
2712
+ // APPENDED rather than replaced: classifyFailure checks its
2713
+ // auth/rate-limit/network patterns before the session-creation
2714
+ // marker, so "fetch failed" here still keeps its transient retry
2715
+ // instead of being flattened into a terminal ruling.
2716
+ throw new Error(
2717
+ "opencode could not report its tool surface, so the allow map " +
2718
+ `cannot be enumerated: ${(error as Error).message}`,
2719
+ );
2720
+ }
2721
+ const surface = (Array.isArray(reported) ? reported : []).filter(
2722
+ (id): id is string => typeof id === "string" && id.length > 0,
2723
+ );
2724
+ if (surface.length === 0) {
2725
+ throw new Error(
2726
+ "opencode reported an empty tool surface, so the allow map cannot " +
2727
+ "be enumerated and no tool can be proven denied; refusing to " +
2728
+ "open a session whose isolation is unverifiable",
2729
+ );
2730
+ }
2731
+ const tools = resolveToolMap(
2732
+ surface,
2733
+ input.tools,
2734
+ denyFloor,
2735
+ mcpToolIdsFor(mcpConfig),
2736
+ );
2737
+ // Free-tier gateway fix (FREE_TIER_GATEWAY_TOOLS above): `deniedGatewayTools`
2738
+ // was computed up front, before this map even existed, and already
2739
+ // decided the server's permission config (the launchServer call
2740
+ // above). Re-applied here for the SAME two ids so the map this
2741
+ // client actually sends never carries the `false` that trips
2742
+ // OpenCode's gateway. Only a key the loops above left `false` is
2743
+ // deleted — a tool this call DID grant (`read` for a hunter-shaped
2744
+ // spec) is untouched, so it stays `true` exactly as it would on any
2745
+ // other route.
2746
+ for (const tool of deniedGatewayTools) {
2747
+ if (tools[tool] === false) delete tools[tool];
2748
+ }
2749
+
2750
+ const userMessageId =
2751
+ options.createMessageId?.() ??
2752
+ `msg_${Date.now().toString(16)}${crypto.randomUUID().replaceAll("-", "")}`;
2753
+ if (!/^msg/.test(userMessageId))
2754
+ throw new Error("invalid OpenCode submitted message identity");
2755
+ evidence.record("session_identity", {
2756
+ sessionId,
2757
+ userMessageId,
2758
+ cwd: input.cwd,
2759
+ });
2760
+ const state: SessionState = {
2761
+ evidence,
2762
+ api,
2763
+ queue: [],
2764
+ queueBytes: 0,
2765
+ turn: createTurnState(sessionId, userMessageId, input.cwd),
2766
+ observedActive: false,
2767
+ ended: false,
2768
+ respondedPermissions: new Set(),
2769
+ };
2770
+ states.set(sessionId, state);
2771
+
2772
+ // The ONLY consumer of the subscription. Subscribing without pulling
2773
+ // buys nothing — an SSE iterator nobody reads is not a recording, the
2774
+ // events simply have not been requested yet.
2775
+ void (async () => {
2776
+ try {
2777
+ for await (const raw of subscription.stream) {
2778
+ // #228: this is ONE directory-scoped stream shared by every
2779
+ // concurrent hunter's session on the same server. Recording
2780
+ // every event unfiltered meant roughly 55% of a real
2781
+ // multi-hunter capture was OTHER sessions' events, filling the
2782
+ // record/byte cap long before this session's own silence
2783
+ // window was covered. An event with no attributable session id
2784
+ // is still recorded — there is nothing to filter it against.
2785
+ const rawSessionId = eventSessionId(raw);
2786
+ if (rawSessionId === undefined || rawSessionId === sessionId) {
2787
+ evidence.record("event", raw);
2788
+ }
2789
+ // #157 (pr-157-8df2fca3-6): a hunter's tool call for a path
2790
+ // OUTSIDE the reviewed worktree tripped `permission.asked`,
2791
+ // and pr-hero never answered it — the tool call sat blocked
2792
+ // until the silence tripwire killed the attempt 150s later at
2793
+ // $0. The server-side `deny` config (opencode-server.ts) is
2794
+ // the primary control; this is defense in depth for whatever
2795
+ // it does not cover — ANY permission, not only
2796
+ // `external_directory`, since pr-hero has no UI to answer a
2797
+ // prompt and must never leave one pending. Own session only:
2798
+ // `rawSessionId` is the SAME id `eventSessionId` already
2799
+ // computed above.
2800
+ if (
2801
+ rawSessionId === sessionId &&
2802
+ (raw as RawEvent)?.type === "permission.asked"
2803
+ ) {
2804
+ const properties = props(raw);
2805
+ const requestID = properties?.id;
2806
+ const permissionName =
2807
+ typeof properties?.permission === "string"
2808
+ ? properties.permission
2809
+ : "unknown";
2810
+ const patterns = Array.isArray(properties?.patterns)
2811
+ ? (properties.patterns as unknown[]).filter(
2812
+ (p): p is string => typeof p === "string",
2813
+ )
2814
+ : [];
2815
+ if (
2816
+ typeof requestID === "string" &&
2817
+ !state.respondedPermissions.has(requestID)
2818
+ ) {
2819
+ // PR #228 review (round 2), F002: `rememberId` (used for
2820
+ // every OTHER bounded id set in this file) evicts the
2821
+ // OLDEST entry once full — fine for high-volume, low-
2822
+ // stakes dedup like stream deltas, but wrong here: an
2823
+ // evicted requestID is indistinguishable from one this
2824
+ // session never saw, so ITS later SSE redelivery would
2825
+ // pass the `!has(requestID)` guard above and fire a
2826
+ // SECOND `permission.reply` for a request the server
2827
+ // already closed — exactly the failure this set exists to
2828
+ // prevent. A failed second reply already fails the
2829
+ // attempt below, so evicting just makes that failure
2830
+ // depend on redelivery timing this session cannot
2831
+ // control. 512 distinct permission prompts inside one
2832
+ // step is already anomalous — `external_directory` is
2833
+ // denied at the server config (opencode-server.ts) — so
2834
+ // failing closed here, the same way `failIntegrity` fails
2835
+ // closed on other exhausted identity caps (e.g. "tool
2836
+ // identity cap exceeded"), is strictly safer than ever
2837
+ // forgetting a requestID this session has committed to
2838
+ // answering.
2839
+ if (
2840
+ state.respondedPermissions.size >=
2841
+ MAX_TRACKED_PERMISSION_REQUESTS
2842
+ ) {
2843
+ state.turn.integrityFailure =
2844
+ "[pr-hero] opencode client: permission request cap exceeded (512)";
2845
+ state.wake?.();
2846
+ state.wake = undefined;
2847
+ break;
2848
+ }
2849
+ // PR #228 review, F002: added BEFORE the reply is even
2850
+ // sent, not after it resolves — an SSE Last-Event-ID
2851
+ // reconnect can redeliver this same event, and a duplicate
2852
+ // arriving while this reply is still in flight must also
2853
+ // see it here rather than racing the await below.
2854
+ state.respondedPermissions.add(requestID);
2855
+ void (async () => {
2856
+ try {
2857
+ unwrap(
2858
+ await api.permission.reply(
2859
+ {
2860
+ requestID,
2861
+ directory: input.cwd,
2862
+ reply: "reject",
2863
+ },
2864
+ requestOptions,
2865
+ ),
2866
+ "permission.reply",
2867
+ );
2868
+ // Visible in the attempt's evidence capture even
2869
+ // though nothing settles on the success path — this is
2870
+ // the only record that pr-hero ever saw, and answered,
2871
+ // this prompt.
2872
+ evidence.record("permission_rejected", {
2873
+ requestID,
2874
+ permission: permissionName,
2875
+ patterns,
2876
+ });
2877
+ } catch (error) {
2878
+ // The one case the server-side config cannot cover:
2879
+ // the reject control itself did not run. Settled
2880
+ // promptly rather than left to the silence tripwire —
2881
+ // see the second door below, exactly like the prompt
2882
+ // failure above.
2883
+ state.failure = formatPermissionRejectFailureDetail(
2884
+ permissionName,
2885
+ patterns,
2886
+ (error as Error).message,
2887
+ );
2888
+ state.ended = true;
2889
+ state.wake?.();
2890
+ state.wake = undefined;
2891
+ }
2892
+ })();
2893
+ }
2894
+ }
2895
+ const rawSize = Buffer.byteLength(JSON.stringify(raw), "utf8");
2896
+ state.queueBytes += rawSize;
2897
+ if (state.queueBytes > 4 * 1024 * 1024) {
2898
+ state.turn.integrityFailure =
2899
+ "[pr-hero] opencode client: raw subscription queue cap exceeded (cap exhaustion)";
2900
+ state.wake?.();
2901
+ state.wake = undefined;
2902
+ break;
2903
+ }
2904
+ state.queue.push(raw);
2905
+ state.wake?.();
2906
+ state.wake = undefined;
2907
+ }
2908
+ } catch {
2909
+ // A dead stream ends the handoff; the poll still observes the
2910
+ // attempt — including any failure recorded after this point, which
2911
+ // is why pollStatus reads `state.failure` too. Before it did, this
2912
+ // line was a claim the poll could not honour: it queries
2913
+ // session.messages(), and a turn that never started has none.
2914
+ } finally {
2915
+ state.ended = true;
2916
+ state.wake?.();
2917
+ state.wake = undefined;
2918
+ }
2919
+ })();
2920
+
2921
+ // FIRED, never awaited. session.prompt blocks until the turn finishes
2922
+ // — the probe measured 4.5s — and returns the completed message. The
2923
+ // ROADMAP forbids completing an attempt from one blocking HTTP call,
2924
+ // so this is the trigger and the event stream is the truth.
2925
+ //
2926
+ // Its RESULT is still observed, and the earlier `.catch()` was not
2927
+ // enough to do that: under the SDK's default `ThrowOnError = false` an
2928
+ // API-level refusal RESOLVES with `{ data: undefined, error }`, so the
2929
+ // handler never ran and the refusal was dropped. The comment that
2930
+ // stood here claimed both §197 observers would see it anyway, which is
2931
+ // false in exactly the case that matters — a prompt the provider
2932
+ // refused creates no message, so no event fires and the poll has
2933
+ // nothing to find. The attempt then sat armed waiting for a terminal
2934
+ // that a turn which never started could never produce, until the
2935
+ // harness watchdog charged it as a timeout.
2936
+ //
2937
+ // A refusal answers at CALL time, not at turn end, so observing it
2938
+ // costs the trigger shape nothing: this stays fired-not-awaited, and
2939
+ // only the failure travels — through the same `ended`/`wake` handoff
2940
+ // the pump uses. That handoff alone was NOT enough, though: the pump
2941
+ // ends it on its own schedule, so when the pump wins the race the
2942
+ // stream reader has already returned and the wake below is a no-op
2943
+ // into a state nobody reads again. Hence the second door, pollStatus,
2944
+ // which reads the same `state.failure`.
2945
+ void (async () => {
2946
+ try {
2947
+ const variant = options.variant ?? options.model.variant;
2948
+ const promptParams: OpenCodeSdkPromptParameters = {
2949
+ sessionID: sessionId,
2950
+ messageID: userMessageId,
2951
+ directory: input.cwd,
2952
+ model: {
2953
+ providerID: options.model.providerID,
2954
+ modelID: options.model.modelID,
2955
+ },
2956
+ ...(variant !== undefined ? { variant } : {}),
2957
+ system: systemPrompt,
2958
+ tools,
2959
+ parts: [{ type: "text", text: input.userPrompt }],
2960
+ };
2961
+ Object.defineProperty(promptParams, "body", {
2962
+ value: {
2963
+ model: promptParams.model,
2964
+ system: promptParams.system,
2965
+ tools: promptParams.tools,
2966
+ parts: promptParams.parts,
2967
+ },
2968
+ enumerable: false,
2969
+ });
2970
+ checkCancelled();
2971
+ const promptResult = unwrap(
2972
+ await api.session.prompt(promptParams, requestOptions),
2973
+ "session.prompt",
2974
+ );
2975
+ evidence.record("prompt_result", promptResult);
2976
+ if (asRecord(asRecord(promptResult)?.info) !== undefined) {
2977
+ // #223: this reconcile is INGEST ONLY — its `events` are
2978
+ // discarded because the event stream, never this blocking HTTP
2979
+ // response, is the delivery channel (see the "FIRED, never
2980
+ // awaited" comment above). `emit: false` keeps that discard
2981
+ // honest: two of twelve live opencode 1.18.30 attempts had this
2982
+ // call race ahead of the SAME text part's own announce -> delta
2983
+ // -> snapshot lifecycle on the stream, and letting it advance
2984
+ // `emittedText` here — for text nobody was actually handed —
2985
+ // made the stream's own, perfectly ordinary snapshot look like
2986
+ // a conflicting one and threw away a correct answer.
2987
+ reconcileMessages([promptResult], state.turn, { emit: false });
2988
+ }
2989
+ } catch (error) {
2990
+ state.failure = (error as Error).message;
2991
+ state.ended = true;
2992
+ state.wake?.();
2993
+ state.wake = undefined;
2994
+ }
2995
+ })();
2996
+
2997
+ // The map travels with the session so the attempt can stamp what was
2998
+ // ACTUALLY sent into its stderr notes. #116's ledger requires the
2999
+ // tools/MCP axis be provable by reading artifacts; before this,
3000
+ // nothing recorded the map at all and the only evidence of the defect
3001
+ // was a hunter narrating tool use it never performed.
3002
+ return { id: sessionId, toolMap: Object.freeze(tools) };
3003
+ } catch (error) {
3004
+ // #128 opened subscribe() before tool.ids. If enumeration fails, the
3005
+ // pump never starts, so this is the only chance to close the global
3006
+ // SSE. `return()` on a never-started iterator is how AsyncIterable
3007
+ // cancellation is expressed; ignoring it leaks one unread stream
3008
+ // against the shared server for as long as a sibling keeps it alive.
3009
+ if (subscription !== undefined) {
3010
+ const iterator = subscription.stream[Symbol.asyncIterator]();
3011
+ await cleanup(async () => iterator.return?.());
3012
+ }
3013
+ // Unwind whatever this call managed to create. Without this the
3014
+ // caller gets an exception and no id, so nothing can be released by
3015
+ // hand afterwards.
3016
+ if (sessionId !== undefined) {
3017
+ states.delete(sessionId);
3018
+ // A remote session that WAS created is real work on the provider's
3019
+ // side; dropping the local map entry does not release it.
3020
+ //
3021
+ // The result is OBSERVED, like every other call in this file: the
3022
+ // `.catch(() => {})` that stood here could not see a refusal at all,
3023
+ // because under `ThrowOnError = false` an API-level failure RESOLVES
3024
+ // with `{ data: undefined, error }`. A refused abort leaves remote
3025
+ // work running — and billing — with no trail at all.
3026
+ //
3027
+ // The trail is APPENDED to the error that caused the unwind, never
3028
+ // thrown over it. This handler has no notes channel; the propagated
3029
+ // error is the channel, since the transport stamps it into
3030
+ // stderrTail as "session creation failed: …". And the failure that
3031
+ // caused the unwind is the one the caller must still see — masking
3032
+ // it with a teardown detail would trade a diagnosis for a symptom.
3033
+ try {
3034
+ await cleanup(async (signal) =>
3035
+ unwrap(
3036
+ await api.session.abort({ sessionID: sessionId }, { signal }),
3037
+ "session.abort",
3038
+ ),
3039
+ );
3040
+ } catch (abortError) {
3041
+ const detail = (abortError as Error).message;
3042
+ if (error instanceof Error) {
3043
+ error.message = `${error.message} (${detail})`;
3044
+ } else {
3045
+ throw new Error(`${String(error)} (${detail})`);
3046
+ }
3047
+ }
3048
+ }
3049
+ throw error;
3050
+ } finally {
3051
+ establishing -= 1;
3052
+ // Do not await on the success path: an extra tick lets a finite
3053
+ // fixture stream drain into one stall window before execute() starts.
3054
+ if (establishing === 0 && states.size === 0) {
3055
+ await releaseIdleServer();
3056
+ }
3057
+ }
3058
+ },
3059
+
3060
+ async *streamEvents(session: OpenCodeClientSession) {
3061
+ const state = stateFor(session);
3062
+ // Reads the QUEUE, never the stream. Everything buffered before this
3063
+ // call is already here in arrival order, and everything after arrives
3064
+ // through the same door — so there is no handoff to race.
3065
+ for (;;) {
3066
+ while (state.queue.length > 0) {
3067
+ const raw = state.queue.shift();
3068
+ state.queueBytes = Math.max(
3069
+ 0,
3070
+ state.queueBytes - Buffer.byteLength(JSON.stringify(raw), "utf8"),
3071
+ );
3072
+ yield* mapOpenCodeEvents(raw, session.id, state.turn);
3073
+ }
3074
+ if (state.turn.integrityFailure !== undefined) {
3075
+ throw new Error(state.turn.integrityFailure);
3076
+ }
3077
+ // Checked AFTER the drain and BEFORE `ended`: anything the provider
3078
+ // already said is delivered first — a terminal buffered before the
3079
+ // failure still wins its slot — and a failure is a louder end than an
3080
+ // EOF, so it must not be swallowed by the plain return below.
3081
+ if (state.failure !== undefined) throw new Error(state.failure);
3082
+ if (state.ended) return;
3083
+ await new Promise<void>((resolve) => {
3084
+ state.wake = resolve;
3085
+ });
3086
+ }
3087
+ },
3088
+
3089
+ async pollStatus(
3090
+ session: OpenCodeClientSession,
3091
+ signal?: AbortSignal,
3092
+ ): Promise<OpenCodePollResult> {
3093
+ const state = states.get(session.id);
3094
+ // #131: abort() owns the Map release. Absence must not throw (a throw
3095
+ // is a failed observation the harness counts and retries forever). It
3096
+ // also must not be `{kind:"failed"}`: runPoll treats that as
3097
+ // session_failed and first-write-wins against the abortConfirmMs
3098
+ // window (opencode-sdk.ts runAbortSequence). Pending lets the stream
3099
+ // still deliver a provider terminal, or the timer settle
3100
+ // abort_unconfirmed.
3101
+ if (state === undefined) {
3102
+ return { kind: "pending" };
3103
+ }
3104
+ if (state.turn.integrityFailure !== undefined) {
3105
+ return { kind: "failed", detail: state.turn.integrityFailure };
3106
+ }
3107
+
3108
+ // #127: the BOUNDARY first, and from a different endpoint. This observer
3109
+ // has no event stream, so it cannot see `session.idle`; scanning
3110
+ // session.messages() for the last completed assistant message is not a
3111
+ // substitute, because at any poll instant "last completed" is step 1
3112
+ // until step 2 exists. Two observers of one wrong fact are not two
3113
+ // observers, which is precisely why the §197 cross-check could not catch
3114
+ // the defect.
3115
+ //
3116
+ // Measured against opencode 1.18.23 at $0 — a local `opencode serve`
3117
+ // plus a model-free `POST /session/{id}/shell` running `sleep 6`:
3118
+ //
3119
+ // while the session is working {"ses_…":{"type":"busy"}}
3120
+ // after it stops, and when freshly created {}
3121
+ //
3122
+ // An idle session is simply ABSENT from the map; it is never reported as
3123
+ // {"type":"idle"}. Requiring the explicit value — the reading the SDK's
3124
+ // `SessionStatus` union invites — would have left this observer
3125
+ // permanently blind and §197 down to one observer again. The explicit
3126
+ // arm is still honoured for the build that does send it.
3127
+ //
3128
+ // #223: `directory` IS required, and it must be the SAME one
3129
+ // session.create used for this session — `state.turn.expectedCwd`,
3130
+ // set from `input.cwd` by `createTurnState` (and the exact value
3131
+ // `session.messages` below queries with too). Measured against
3132
+ // opencode 1.18.30: `GET /session/status` is scoped by directory
3133
+ // instance exactly like `GET /event` above, so omitting it — or
3134
+ // naming a different one — watches an instance that has never heard
3135
+ // of this session and reports it `{}` even while it is BUSY. That is
3136
+ // indistinguishable from "finished" in the response shape, which is
3137
+ // #127 reopened: a wrong scope silently discards the model's answer
3138
+ // once the useful-progress deadline elapses, because this observer
3139
+ // never sees anything to report.
3140
+ //
3141
+ // The still-true half of the old rationale survives below: absence is
3142
+ // ambiguous on its own even with the RIGHT directory, because it is
3143
+ // also what a session this call has simply never seen looks like.
3144
+ const statuses = asRecord(
3145
+ unwrap(
3146
+ await state.api.session.status(
3147
+ { directory: state.turn.expectedCwd },
3148
+ { signal },
3149
+ ),
3150
+ "session.status",
3151
+ ),
3152
+ );
3153
+ signal?.throwIfAborted();
3154
+ state.evidence.record("status", { sessionId: session.id, statuses });
3155
+ const statusRecord = asRecord(statuses?.[session.id]);
3156
+ // #157: checked BEFORE "retry means still working" below, and it is
3157
+ // its own second observer of the same fact the stream carries when it
3158
+ // is still alive to carry it — see mapOpenCodeEvents's "session.status"
3159
+ // case. `statuses?.[session.id]` is already scoped to THIS session, so
3160
+ // no separate session-match check is needed here.
3161
+ const limit = providerLimitFromStatus(statusRecord);
3162
+ if (limit !== undefined) {
3163
+ return {
3164
+ kind: "failed",
3165
+ detail: formatProviderLimitDetail(limit.reason, limit.message),
3166
+ };
3167
+ }
3168
+ const statusType = statusRecord?.type;
3169
+ // Both are the provider still working. `retry` especially: a session in
3170
+ // backoff is neither done nor idle, and it will produce more steps — its
3171
+ // `next` timestamp is what retryHintFromStatus reads for the policy.
3172
+ if (statusType === "busy" || statusType === "retry") {
3173
+ state.observedActive = true;
3174
+ } else if (statusType === "idle" || statusType === undefined) {
3175
+ // Absence is the boundary, but it is ALSO what a session this call
3176
+ // cannot see looks like (wrong scope, unknown id, a pruned entry), and
3177
+ // the response cannot tell the two apart. So it only counts once this
3178
+ // observer has seen the provider name this session through this same
3179
+ // endpoint. An explicit idle names it, so it arms and settles at once.
3180
+ if (statusType === "idle") state.observedActive = true;
3181
+ if (state.observedActive) {
3182
+ signal?.throwIfAborted();
3183
+ const response = await state.api.session.messages(
3184
+ {
3185
+ sessionID: session.id,
3186
+ directory: state.turn.expectedCwd,
3187
+ },
3188
+ { signal },
3189
+ );
3190
+ signal?.throwIfAborted();
3191
+ // Throws on the error arm rather than reporting "pending": the
3192
+ // caller treats a poll that throws as a FAILED OBSERVATION and
3193
+ // counts it (opencode-sdk.ts:707), whereas a silent "pending" would
3194
+ // let the attempt run to its stall deadline on an API error the
3195
+ // provider already explained.
3196
+ const messages = unwrap(response, "session.messages");
3197
+ state.evidence.record("readback", {
3198
+ sessionId: session.id,
3199
+ cwd: state.turn.expectedCwd,
3200
+ coverage: Array.isArray(messages) ? "complete" : "unknown",
3201
+ messages,
3202
+ });
3203
+ // The qualified ordinary endpoint returns the complete array when
3204
+ // no limit is supplied. An object/cursor is unknown coverage, not []
3205
+ // and never an excuse to reuse a prior terminal snapshot.
3206
+ if (!Array.isArray(messages)) {
3207
+ state.turn.integrityFailure =
3208
+ "[pr-hero] opencode client: unknown message readback coverage";
3209
+ return { kind: "failed", detail: state.turn.integrityFailure };
3210
+ }
3211
+ const list = messages;
3212
+
3213
+ // #223 follow-up: this reconcile is INGEST ONLY, exactly like the
3214
+ // prompt_result call site above — its `events` are discarded below
3215
+ // (only `failure`/`terminalProof`/`finalText`/`usage`/
3216
+ // `usageIncomplete` are read), because the event stream, never this
3217
+ // polled HTTP readback, is the delivery channel. `emit: false`
3218
+ // keeps that discard honest: without it, a poll that races ahead of
3219
+ // the stream — observing a text part's FULL persisted snapshot
3220
+ // while the stream has only delivered a PREFIX of it — still
3221
+ // advanced `emittedText` to the full text here, for a consumer
3222
+ // that was never handed the rest. The stream's own still-in-flight
3223
+ // remaining deltas then found `emittedText` already past what was
3224
+ // really delivered, and its own later restating snapshot (every
3225
+ // real fixture sends one before the turn ends) found a
3226
+ // `snapshotText` shorter than the now-advanced `emittedText` and
3227
+ // threw "conflicting snapshot observed" — turning a turn that
3228
+ // actually finished cleanly into a `stream_error`/`failed` outcome.
3229
+ // `finalText` is unaffected either way: `canonicalFinalText`
3230
+ // (opencode-client.ts reconcileMessages) is computed from
3231
+ // `detail.text`, not `detail.emittedText`, before this gate runs.
3232
+ const reconciled = reconcileMessages(list, state.turn, {
3233
+ emit: false,
3234
+ });
3235
+ if (
3236
+ reconciled.failure !== undefined ||
3237
+ state.turn.integrityFailure !== undefined
3238
+ ) {
3239
+ return {
3240
+ kind: "failed",
3241
+ detail:
3242
+ reconciled.failure ??
3243
+ state.turn.integrityFailure ??
3244
+ "opencode client integrity failure",
3245
+ };
3246
+ }
3247
+ if (hasOutstandingTools(state.turn)) {
3248
+ return { kind: "pending" };
3249
+ }
3250
+
3251
+ if (reconciled.terminalProof !== undefined) {
3252
+ // pr-hero review F001 (#214): reported HERE as the CURRENT
3253
+ // members of `completedToolCallIds` (whose own WHY comment on
3254
+ // `OpenCodeTurnState` carries the full reasoning), not inside
3255
+ // `reconcileMessages` (whose return type stays untouched) and not
3256
+ // re-derived from `toolStates`/`list` fresh at this moment — a
3257
+ // fresh re-filter is exactly the bug: an id that reached
3258
+ // "completed" on an earlier readback and "error" on this one
3259
+ // would silently drop out of a live recount. Ownership is already
3260
+ // enforced above, in the parts loop that only runs past
3261
+ // `isMessageOwned`, so every id in this set is this turn's own.
3262
+ return {
3263
+ kind: "terminal",
3264
+ proof: reconciled.terminalProof,
3265
+ finalText: reconciled.finalText,
3266
+ usage: reconciled.usage,
3267
+ usageIncomplete: reconciled.usageIncomplete,
3268
+ completedToolCallIds: Array.from(state.turn.completedToolCallIds),
3269
+ };
3270
+ }
3271
+ }
3272
+ }
3273
+ // The SECOND observer of the failure, and the reason it exists: the
3274
+ // stream can only carry a failure while it is still being read, and the
3275
+ // subscription pump ends the handoff on its own schedule — completely
3276
+ // asynchronously from the fired-not-awaited prompt. Lose that race and
3277
+ // streamEvents has already returned at `if (state.ended) return`, so
3278
+ // whatever the prompt's catch writes afterwards would reach nobody, and
3279
+ // this poll would answer "pending" forever over a session that can never
3280
+ // produce a message. §197 wants two INDEPENDENT observers of ONE fact; a
3281
+ // failure only one of them can see is not two observers.
3282
+ //
3283
+ // Checked AFTER the message scan, for the same reason streamEvents
3284
+ // checks it after draining the queue: a terminal the provider ALREADY
3285
+ // sent still wins its slot.
3286
+ if (state.failure !== undefined) {
3287
+ return { kind: "failed", detail: state.failure };
3288
+ }
3289
+ return { kind: "pending" };
3290
+ },
3291
+
3292
+ async abort(session: OpenCodeClientSession): Promise<void> {
3293
+ const state = states.get(session.id);
3294
+ if (state === undefined) return;
3295
+ // The result is CHECKED, not discarded. Awaiting the error arm proves
3296
+ // nothing on its own — it resolves — so a provider-side refusal used to
3297
+ // return here as an ordinary success and the caller recorded a confirmed
3298
+ // abort over a remote session that may still be running, and billing.
3299
+ // Throwing is what makes it visible: the single caller
3300
+ // (opencode-sdk.ts's callAbortOnce) catches and stamps a note into
3301
+ // stderrTail, which keeps abort best-effort — observed, never fatal to
3302
+ // the teardown it runs inside.
3303
+ state.evidence.record("abort_requested", { sessionId: session.id });
3304
+ unwrap(
3305
+ await state.api.session.abort({ sessionID: session.id }),
3306
+ "session.abort",
3307
+ );
3308
+ state.evidence.record("abort_acknowledged", { sessionId: session.id });
3309
+ // #131: abort is the attempt's teardown, so it owns the Map release.
3310
+ // streamEvents already holds this object by reference, so in-flight
3311
+ // readers survive the delete; later pollStatus/abort see the gap.
3312
+ state.ended = true;
3313
+ state.wake?.();
3314
+ state.wake = undefined;
3315
+ states.delete(session.id);
3316
+ await releaseIdleServer();
3317
+ },
3318
+
3319
+ async close(): Promise<void> {
3320
+ states.clear();
3321
+ const handle = server;
3322
+ server = undefined;
3323
+ serverPromise = undefined;
3324
+ launchedMcp = undefined;
3325
+ if (handle !== undefined) await handle.close();
3326
+ },
3327
+ };
3328
+ }