@bitkyc08/opencodex 2.92.0 → 2.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/bin/ocx.mjs +10 -5
  2. package/gui/dist/assets/{App-sUf_8afJ.js → App-CizjBqyk.js} +18 -18
  3. package/gui/dist/assets/{Tray-BSsxznDm.js → Tray-DamiMqcX.js} +1 -1
  4. package/gui/dist/assets/{index-BlFE_VB_.js → index-DQsht3vH.js} +12 -12
  5. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  6. package/gui/dist/assets/{quota-summary-BRlbXgw0.js → quota-summary-BXu4zE8H.js} +1 -1
  7. package/gui/dist/index.html +2 -2
  8. package/package.json +5 -5
  9. package/src/adapters/anthropic.ts +28 -5
  10. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  11. package/src/adapters/coding-agent/profile.ts +54 -16
  12. package/src/adapters/coding-agent/turn.ts +30 -2
  13. package/src/adapters/command-code.ts +114 -7
  14. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  15. package/src/adapters/devin/live-models.ts +4 -0
  16. package/src/adapters/google-wire-compiler.ts +1 -2
  17. package/src/adapters/kiro/reasoning.ts +2 -0
  18. package/src/adapters/kiro-refusal.ts +6 -1
  19. package/src/adapters/kiro-wire.ts +1 -1
  20. package/src/adapters/openai-chat/messages.ts +8 -2
  21. package/src/adapters/openai-chat/passthrough.ts +35 -14
  22. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  23. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  24. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  25. package/src/adapters/openai-chat.ts +7 -8
  26. package/src/adapters/openai-responses/passthrough.ts +7 -4
  27. package/src/adapters/openai-responses/reasoning.ts +13 -0
  28. package/src/adapters/openai-responses/request-strips.ts +1 -1
  29. package/src/adapters/qoder/adapter.ts +129 -8
  30. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  31. package/src/adapters/reasoning-controls.ts +16 -0
  32. package/src/adapters/tool-call-id.ts +1 -3
  33. package/src/bridge/errors.ts +27 -0
  34. package/src/bridge.ts +1 -1
  35. package/src/chat/inbound.ts +4 -1
  36. package/src/chat/outbound.ts +9 -2
  37. package/src/chat/reasoning-details.ts +28 -5
  38. package/src/claude/desktop-first-party.ts +54 -4
  39. package/src/claude/desktop-picker.ts +11 -8
  40. package/src/claude/first-party-settings.ts +3 -1
  41. package/src/claude/inbound.ts +2 -1
  42. package/src/claude/intercept/local-ca.ts +2 -1
  43. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  44. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  45. package/src/claude/intercept/picker-models.ts +6 -3
  46. package/src/claude/intercept/picker-runtime.ts +3 -2
  47. package/src/claude/intercept/runtime.ts +6 -3
  48. package/src/claude/model-info.ts +31 -8
  49. package/src/cli/account-api.ts +11 -0
  50. package/src/cli/capabilities-agents-routing.ts +2 -2
  51. package/src/cli/capabilities-base.ts +7 -1
  52. package/src/cli/capabilities-observe-system.ts +10 -0
  53. package/src/cli/claude-desktop.ts +9 -8
  54. package/src/cli/claude.ts +3 -2
  55. package/src/cli/codex-shim-autorestore.ts +9 -0
  56. package/src/cli/combo-result.ts +7 -0
  57. package/src/cli/combo.ts +18 -0
  58. package/src/cli/cross-home-owner.ts +13 -1
  59. package/src/cli/dispatch.ts +25 -6
  60. package/src/cli/ensure-desired-integrations.ts +8 -6
  61. package/src/cli/export-command.ts +4 -1
  62. package/src/cli/help.ts +2 -1
  63. package/src/cli/index.ts +45 -45
  64. package/src/cli/integration-plan-dto.ts +4 -0
  65. package/src/cli/opencode.ts +20 -9
  66. package/src/cli/registry.ts +6 -4
  67. package/src/cli/root.ts +9 -0
  68. package/src/cli/status.ts +59 -1
  69. package/src/cli/stop-restore.ts +113 -0
  70. package/src/cli/sync-expectation.ts +60 -0
  71. package/src/cli/uninstall-integrations.ts +41 -7
  72. package/src/client/connect.ts +40 -3
  73. package/src/client/link-home.ts +10 -1
  74. package/src/client/machine-api.ts +3 -1
  75. package/src/client/sync-expectation.ts +118 -0
  76. package/src/clients/config-export/agent-clients.ts +96 -0
  77. package/src/clients/config-export/contracts.ts +25 -7
  78. package/src/clients/config-export/qoder.ts +38 -23
  79. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  80. package/src/clients/config-export.ts +12 -0
  81. package/src/clients/lazycodex.ts +7 -2
  82. package/src/clients/reasoning-controls.ts +49 -0
  83. package/src/codex/auth-api/account-identity.ts +14 -0
  84. package/src/codex/auth-api/account-list.ts +29 -2
  85. package/src/codex/auth-api/http.ts +13 -0
  86. package/src/codex/auth-api/main-account-probe.ts +2 -2
  87. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  88. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  89. package/src/codex/auth-context.ts +15 -12
  90. package/src/codex/catalog/build-entries.ts +22 -0
  91. package/src/codex/catalog/configured-tiers.ts +70 -0
  92. package/src/codex/catalog/effort.ts +44 -10
  93. package/src/codex/catalog/gather-capture.ts +1 -0
  94. package/src/codex/catalog/heal-observation.ts +155 -13
  95. package/src/codex/catalog/metadata.ts +6 -0
  96. package/src/codex/catalog/model-hints.ts +60 -11
  97. package/src/codex/catalog/model-visibility.ts +3 -2
  98. package/src/codex/catalog/native-models.ts +18 -3
  99. package/src/codex/catalog/parsing.ts +10 -8
  100. package/src/codex/catalog/pinned-models.ts +2 -1
  101. package/src/codex/catalog/provider-models.ts +4 -5
  102. package/src/codex/catalog/retained-sync.ts +2 -1
  103. package/src/codex/catalog/routed-gather.ts +19 -20
  104. package/src/codex/catalog/write-audit.ts +3 -2
  105. package/src/codex/catalog-self-heal.ts +43 -23
  106. package/src/codex/collision-identity.ts +30 -5
  107. package/src/codex/convergence.ts +4 -3
  108. package/src/codex/data/roster-pinned-models.json +177 -1
  109. package/src/codex/desired-state.ts +6 -1
  110. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  111. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  112. package/src/codex/desktop-compatibility/usage-controller.ts +2 -0
  113. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  114. package/src/codex/inject/config-toml.ts +0 -18
  115. package/src/codex/inject/plan.ts +18 -3
  116. package/src/codex/inject/remove.ts +6 -2
  117. package/src/codex/inject.ts +1 -1
  118. package/src/codex/journal.ts +61 -1
  119. package/src/codex/model-entitlements.ts +1 -1
  120. package/src/codex/native-main-owner.ts +27 -1
  121. package/src/codex/native-profile-store.ts +2 -1
  122. package/src/codex/pool-credit-policy.ts +35 -1
  123. package/src/codex/quota-types.ts +3 -0
  124. package/src/codex/quota.ts +24 -4
  125. package/src/codex/role-auto-assign.ts +6 -2
  126. package/src/codex/subagent-defaults.ts +49 -4
  127. package/src/combos/failover.ts +17 -2
  128. package/src/combos/jev-decision-contract.ts +22 -1
  129. package/src/combos/jev-service-exchange.ts +3 -1
  130. package/src/combos/jev.ts +95 -9
  131. package/src/combos/resolve.ts +45 -1
  132. package/src/combos/types.ts +24 -0
  133. package/src/config/load-degrade.ts +5 -0
  134. package/src/config/paths.ts +19 -3
  135. package/src/config/pending-teardown.ts +22 -1
  136. package/src/config/provider-validation.ts +15 -4
  137. package/src/config/removed-opencode-free.ts +11 -0
  138. package/src/config/schema/leaf-validators.ts +5 -0
  139. package/src/generated/compatibility-version.json +314 -230
  140. package/src/generated/model-metadata.ts +5 -5
  141. package/src/images/loop.ts +16 -2
  142. package/src/integrations/catalog-refresh.ts +1 -1
  143. package/src/integrations/hermes-profiles.ts +251 -0
  144. package/src/integrations/merge.ts +8 -0
  145. package/src/integrations/mutation-plan.ts +19 -4
  146. package/src/integrations/registry.ts +5 -0
  147. package/src/integrations/state.ts +36 -1
  148. package/src/integrations/writer.ts +18 -4
  149. package/src/lib/bun-path-runtime.mjs +2 -1
  150. package/src/lib/errors.ts +62 -0
  151. package/src/lib/eventstream-decoder.ts +81 -37
  152. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  153. package/src/lib/pinned-http.ts +35 -2
  154. package/src/lib/process-control.ts +13 -1
  155. package/src/lib/socks5-fetch.ts +59 -64
  156. package/src/lib/socks5-upload-waiter.ts +50 -0
  157. package/src/lib/sse-decoder.ts +7 -2
  158. package/src/lib/state-store-sweeper.ts +40 -14
  159. package/src/lib/windows-native-principal-worker.ts +14 -0
  160. package/src/lib/windows-native-principal.ts +188 -0
  161. package/src/lib/windows-secret-acl.ts +39 -3
  162. package/src/lib/windows-user-principal.ts +62 -18
  163. package/src/link/ssh-config.ts +35 -3
  164. package/src/providers/account-quota-disk.ts +12 -4
  165. package/src/providers/codebuddy-models.ts +6 -0
  166. package/src/providers/codex-capacity.ts +3 -1
  167. package/src/providers/derive.ts +28 -0
  168. package/src/providers/kiro-models.ts +3 -0
  169. package/src/providers/mimo-thinking.ts +12 -0
  170. package/src/providers/model-rename-fields.ts +1 -0
  171. package/src/providers/model-rename-migration.ts +10 -0
  172. package/src/providers/openai-sidecar-credit.ts +2 -2
  173. package/src/providers/reasoning-capabilities.ts +76 -0
  174. package/src/providers/registry/entries-core.ts +14 -12
  175. package/src/providers/registry/entries-extended.ts +63 -20
  176. package/src/providers/registry/model-ids.ts +2 -0
  177. package/src/providers/registry/model-seeds.ts +93 -28
  178. package/src/providers/registry/types.ts +10 -1
  179. package/src/providers/resolved-model-policy.ts +26 -6
  180. package/src/providers/routed-config.ts +9 -1
  181. package/src/providers/stale-model-roster-migration.ts +44 -7
  182. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  183. package/src/responses/compaction-summary.ts +45 -0
  184. package/src/responses/muse-tool-name-alias.ts +1 -2
  185. package/src/responses/parser.ts +3 -2
  186. package/src/responses/schema.ts +1 -0
  187. package/src/responses/thought-signature-replay.ts +10 -2
  188. package/src/routing/capability.ts +8 -2
  189. package/src/routing/history/ingest.ts +28 -3
  190. package/src/server/auth-cors.ts +3 -2
  191. package/src/server/chat-completions.ts +7 -0
  192. package/src/server/chat-native-eligibility.ts +7 -0
  193. package/src/server/chat-native-reasoning.ts +14 -4
  194. package/src/server/direct-local-http.ts +5 -2
  195. package/src/server/effort-policy.ts +5 -1
  196. package/src/server/index/live-sideband.ts +18 -15
  197. package/src/server/index/serve-options.ts +5 -4
  198. package/src/server/management/agent-settings-routes.ts +27 -15
  199. package/src/server/management/combo-routes.ts +4 -0
  200. package/src/server/management/config-routes.ts +2 -2
  201. package/src/server/management/decision-discovery.ts +12 -2
  202. package/src/server/management/hermes-profile-routes.ts +156 -0
  203. package/src/server/management/integration-routes.ts +85 -24
  204. package/src/server/management/model-routes.ts +2 -2
  205. package/src/server/management/model-row-export-metadata.ts +25 -6
  206. package/src/server/management/model-rows.ts +15 -20
  207. package/src/server/management/native-integration-routes.ts +11 -8
  208. package/src/server/management/route-registry.ts +4 -0
  209. package/src/server/management-api.ts +5 -0
  210. package/src/server/models-capabilities.ts +21 -3
  211. package/src/server/responses/adapter-delivery.ts +11 -1
  212. package/src/server/responses/adapter-dispatch.ts +2 -2
  213. package/src/server/responses/codex-ws-exchange.ts +39 -9
  214. package/src/server/responses/codex-ws-session.ts +38 -4
  215. package/src/server/responses/codex-ws-wire.ts +6 -1
  216. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  217. package/src/server/responses/combo-stream-preflight.ts +8 -1
  218. package/src/server/responses/compact.ts +4 -3
  219. package/src/server/responses/context-overflow.ts +8 -1
  220. package/src/server/responses/core-combo-failure.ts +10 -0
  221. package/src/server/responses/core-combo.ts +23 -15
  222. package/src/server/responses/core-lifetime.ts +3 -0
  223. package/src/server/responses/core-normalize.ts +11 -1
  224. package/src/server/responses/core-options.ts +2 -0
  225. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  226. package/src/server/responses/passthrough-delivery.ts +40 -2
  227. package/src/server/responses/policy-fallback.ts +6 -1
  228. package/src/server/responses/request-compression.ts +12 -7
  229. package/src/server/responses/request-prepare.ts +22 -2
  230. package/src/server/responses/request-sidecar-auth.ts +2 -0
  231. package/src/server/responses/response-effects.ts +22 -10
  232. package/src/server/responses/sidecar-execution.ts +11 -3
  233. package/src/server/stop-teardown.ts +36 -1
  234. package/src/server/ws-bridge.ts +1 -1
  235. package/src/service/desktop-supervision.d.mts +7 -4
  236. package/src/service/desktop-supervision.mjs +90 -13
  237. package/src/service/ownership-mutation-lease.mjs +21 -7
  238. package/src/types/config.ts +8 -2
  239. package/src/types/provider.ts +20 -6
  240. package/src/types/request.ts +10 -0
  241. package/src/types.ts +1 -0
  242. package/src/update/bind-probe.ts +29 -0
  243. package/src/update/job.ts +10 -29
  244. package/src/update/npm-install-job.ps1 +173 -0
  245. package/src/update/npm-install.mjs +70 -0
  246. package/src/update/stop-contract.d.mts +1 -0
  247. package/src/update/stop-contract.mjs +14 -0
  248. package/src/update/stop-decision.d.mts +1 -1
  249. package/src/update/stop-decision.mjs +13 -3
  250. package/src/update/teardown-handover.ts +166 -0
  251. package/src/update/transactional-install.d.mts +14 -3
  252. package/src/update/transactional-install.mjs +33 -7
  253. package/src/usage/expected-prices.ts +64 -31
  254. package/src/usage/timeline.ts +19 -9
  255. package/src/vision/eligibility.ts +15 -5
  256. package/src/vision/plan.ts +2 -2
  257. package/src/web-search/loop.ts +16 -2
  258. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * `application/vnd.amazon.eventstream` decoder.
3
3
  *
4
- * Ported from jawcode `packages/ai/src/providers/aws-eventstream.ts` (verbatim logic).
4
+ * Framing logic ported from jawcode `packages/ai/src/providers/aws-eventstream.ts`.
5
5
  * Foundational dependency for AWS-eventstream providers: kiro (CodeWhisperer
6
- * GenerateAssistantResponse) and amazon-bedrock (Converse). Self-contained — only
7
- * uses Buffer / DataView / TextDecoder (Bun + Node compatible).
6
+ * GenerateAssistantResponse) and amazon-bedrock (Converse). Checksums use Bun's
7
+ * native CRC32; framing uses Buffer / DataView / TextDecoder.
8
8
  *
9
9
  * Wire format (all integers big-endian):
10
10
  *
@@ -32,21 +32,9 @@ export interface EventStreamMessage {
32
32
  payload: Uint8Array;
33
33
  }
34
34
 
35
- /** CRC32 (IEEE / zlib polynomial 0xEDB88320), matches `@aws-crypto/crc32`. */
36
- const CRC_TABLE = (() => {
37
- const t = new Uint32Array(256);
38
- for (let i = 0; i < 256; i++) {
39
- let c = i;
40
- for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
41
- t[i] = c >>> 0;
42
- }
43
- return t;
44
- })();
45
-
35
+ /** Unsigned IEEE CRC32 over this byte view; the seed may continue a previous checksum. */
46
36
  export function crc32(bytes: Uint8Array, seed = 0): number {
47
- let c = (seed ^ 0xffffffff) >>> 0;
48
- for (let i = 0; i < bytes.length; i++) c = (CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8)) >>> 0;
49
- return (c ^ 0xffffffff) >>> 0;
37
+ return Bun.hash.crc32(bytes, seed >>> 0);
50
38
  }
51
39
 
52
40
  /**
@@ -170,40 +158,96 @@ function bigIntFromBytes(b: Uint8Array): bigint {
170
158
  return v;
171
159
  }
172
160
 
161
+ function frameLength(bytes: Uint8Array): number {
162
+ const total = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, false);
163
+ if (total < MIN_MESSAGE_LEN) throw new Error(`eventstream: total length ${total} below minimum`);
164
+ if (total > MAX_MESSAGE_LEN) throw new Error(`eventstream: total length ${total} exceeds maximum`);
165
+ return total;
166
+ }
167
+
168
+ function validatePrelude(bytes: Uint8Array, total: number): void {
169
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
170
+ const headersLen = view.getUint32(4, false);
171
+ if (crc32(bytes.subarray(0, PRELUDE_LEN)) !== view.getUint32(8, false)) {
172
+ throw new Error("eventstream: prelude CRC mismatch");
173
+ }
174
+ if (headersLen > MAX_HEADERS_LEN) throw new Error(`eventstream: headers length ${headersLen} exceeds maximum`);
175
+ if (headersLen > total - MIN_MESSAGE_LEN) throw new Error("eventstream: headers length exceeds frame payload");
176
+ }
177
+
173
178
  /**
174
179
  * Async generator that consumes a `ReadableStream<Uint8Array>` (a fetch response
175
180
  * body) and yields fully-framed messages, handling arbitrary chunk boundaries.
176
181
  */
177
182
  export async function* decodeEventStream(source: ReadableStream<Uint8Array>): AsyncGenerator<EventStreamMessage> {
178
183
  const reader = source.getReader();
179
- let buf: Uint8Array = new Uint8Array(0);
184
+ const empty = new Uint8Array(0);
185
+ let carry: Uint8Array = empty;
186
+ let used = 0;
187
+ let total = 0;
188
+ const append = (bytes: Uint8Array): void => {
189
+ if (bytes.length === 0) return;
190
+ const required = used + bytes.length;
191
+ if (required > carry.length) {
192
+ // The prelude is tiny; grow payload storage only as bytes actually arrive.
193
+ const capacity = Math.min(total || HEADER_BLOCK_OFFSET,
194
+ Math.max(required, carry.length < HEADER_BLOCK_OFFSET ? HEADER_BLOCK_OFFSET : Math.max(4096, carry.length * 2)));
195
+ const grown = new Uint8Array(capacity);
196
+ grown.set(carry.subarray(0, used));
197
+ carry = grown;
198
+ }
199
+ carry.set(bytes, used);
200
+ used = required;
201
+ };
180
202
  try {
181
203
  while (true) {
182
204
  const { value, done } = await reader.read();
183
- if (value && value.length > 0) buf = buf.length === 0 ? value : Buffer.concat([buf, value]);
184
205
  let offset = 0;
185
- while (buf.length - offset >= 4) {
186
- const dv = new DataView(buf.buffer, buf.byteOffset + offset, buf.length - offset);
187
- const total = dv.getUint32(0, false);
188
- if (total < MIN_MESSAGE_LEN) throw new Error(`eventstream: total length ${total} below minimum`);
189
- if (total > MAX_MESSAGE_LEN) throw new Error(`eventstream: total length ${total} exceeds maximum`);
190
- if (buf.length - offset >= HEADER_BLOCK_OFFSET) {
191
- const headersLen = dv.getUint32(4, false);
192
- const preludeCrc = dv.getUint32(8, false);
193
- const computedPreludeCrc = crc32(buf.subarray(offset, offset + PRELUDE_LEN));
194
- if (computedPreludeCrc !== preludeCrc) throw new Error("eventstream: prelude CRC mismatch");
195
- if (headersLen > MAX_HEADERS_LEN) throw new Error(`eventstream: headers length ${headersLen} exceeds maximum`);
206
+ while (value && offset < value.length) {
207
+ if (used === 0 && value.length - offset >= HEADER_BLOCK_OFFSET) {
208
+ const remaining = value.subarray(offset);
209
+ total = frameLength(remaining);
210
+ validatePrelude(remaining, total);
211
+ if (remaining.length >= total) {
212
+ // Complete frames borrow the source chunk without a working copy.
213
+ yield decodeMessage(remaining.subarray(0, total));
214
+ offset += total;
215
+ total = 0;
216
+ continue;
217
+ }
218
+ append(remaining);
219
+ offset = value.length;
220
+ continue;
221
+ }
222
+ if (used < 4) {
223
+ const end = Math.min(value.length, offset + 4 - used);
224
+ append(value.subarray(offset, end));
225
+ offset = end;
226
+ if (used < 4) continue;
227
+ total = frameLength(carry);
228
+ }
229
+ if (used < HEADER_BLOCK_OFFSET) {
230
+ const end = Math.min(value.length, offset + HEADER_BLOCK_OFFSET - used);
231
+ append(value.subarray(offset, end));
232
+ offset = end;
233
+ if (used < HEADER_BLOCK_OFFSET) continue;
234
+ validatePrelude(carry, total);
235
+ }
236
+ const end = Math.min(value.length, offset + total - used);
237
+ append(value.subarray(offset, end));
238
+ offset = end;
239
+ if (used === total) {
240
+ const frame = carry.subarray(0, used);
241
+ // A yielded payload owns this allocation; never overwrite it for a later frame.
242
+ carry = empty;
243
+ used = 0;
244
+ total = 0;
245
+ yield decodeMessage(frame);
196
246
  }
197
- if (buf.length - offset < total) break;
198
- const frame = buf.subarray(offset, offset + total);
199
- yield decodeMessage(frame);
200
- offset += total;
201
247
  }
202
- if (offset > 0) buf = buf.slice(offset);
203
- if (buf.length > MAX_MESSAGE_LEN) throw new Error(`eventstream: buffered frame exceeds maximum ${MAX_MESSAGE_LEN}`);
204
248
  if (done) break;
205
249
  }
206
- if (buf.length > 0) throw new Error("eventstream: truncated message at end of stream");
250
+ if (used > 0) throw new Error("eventstream: truncated message at end of stream");
207
251
  } finally {
208
252
  // Early termination (consumer break/return, turn abort, or an HTTP/2 mid-body reset) can leave
209
253
  // an in-flight `reader.read()` pending when this generator's `finally` runs. Releasing the lock
@@ -78,7 +78,8 @@ function connectOne(authority: string, proxy: OpaqueProxyRoute, { signal, timeou
78
78
  // Keep a defensive observer across the promise-to-owner handoff. Errors still
79
79
  // settle the establishment promise or are handled by the relay after handoff.
80
80
  socket.on('error', () => {});
81
- let pending: Buffer = Buffer.alloc(0); let settled = false, tlsReady = !secure;
81
+ let pending: Buffer = Buffer.alloc(0), pendingLength = 0;
82
+ let owned = false, statusChecked = false, settled = false, tlsReady = !secure;
82
83
  const connectedEvent = secure ? 'secureConnect' : 'connect';
83
84
  const cleanup = () => {
84
85
  clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
@@ -103,22 +104,43 @@ function connectOne(authority: string, proxy: OpaqueProxyRoute, { signal, timeou
103
104
  socket.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n${auth}\r\n`);
104
105
  };
105
106
  const onData = (chunk: Buffer) => {
106
- pending = Buffer.concat([pending, chunk]);
107
- const lineEnd = pending.indexOf('\r\n');
107
+ if (settled || chunk.length === 0) return;
108
+ const previousLength = pendingLength;
109
+ // Never copy a whole coalesced target payload into the bounded header buffer.
110
+ const inputLength = Math.min(chunk.length, maxHeaderBytes - previousLength);
111
+ const needed = previousLength + inputLength;
112
+ if (previousLength === 0) {
113
+ // Most proxies deliver the complete header at once: borrow that chunk.
114
+ pending = chunk.subarray(0, inputLength);
115
+ } else if (inputLength > 0) {
116
+ if (!owned || needed > pending.length) {
117
+ const capacity = Math.min(maxHeaderBytes, Math.max(1024, pending.length * 2, needed));
118
+ const grown = Buffer.allocUnsafe(capacity);
119
+ pending.copy(grown, 0, 0, previousLength);
120
+ pending = grown;
121
+ owned = true;
122
+ }
123
+ chunk.copy(pending, previousLength, 0, inputLength);
124
+ }
125
+ pendingLength = needed;
126
+ const received = pending.subarray(0, pendingLength);
127
+ // Only the new suffix and a possible split delimiter need another scan.
128
+ const lineEnd = statusChecked ? -1 : received.indexOf('\r\n', Math.max(0, previousLength - 1));
108
129
  if (lineEnd >= 0) {
109
- const firstLine = pending.subarray(0, lineEnd).toString('latin1');
130
+ statusChecked = true;
131
+ const firstLine = received.subarray(0, lineEnd).toString('latin1');
110
132
  const firstStatus = /^HTTP\/1\.[01] ([0-9]{3})(?: [\t\x20-\x7e\x80-\xff]*)?$/.exec(firstLine);
111
133
  if (!firstStatus) return fail(new TunnelError('PROTOCOL', 'Invalid HTTP proxy status line'));
112
134
  const status = Number(firstStatus[1]);
113
135
  if (status < 200 || status >= 300) return fail(new TunnelError('REFUSED', 'HTTP proxy refused CONNECT', { status }));
114
136
  }
115
- const end = pending.indexOf('\r\n\r\n');
137
+ const end = received.indexOf('\r\n\r\n', Math.max(0, previousLength - 3));
116
138
  if (end < 0) {
117
- if (pending.length > maxHeaderBytes) fail(new TunnelError('PROTOCOL', 'HTTP proxy response headers exceed limit'));
139
+ if (inputLength < chunk.length) fail(new TunnelError('PROTOCOL', 'HTTP proxy response headers exceed limit'));
118
140
  return;
119
141
  }
120
142
  if (end + 4 > maxHeaderBytes) return fail(new TunnelError('PROTOCOL', 'HTTP proxy response headers exceed limit'));
121
- const lines = pending.subarray(0, end).toString('latin1').split('\r\n');
143
+ const lines = received.subarray(0, end).toString('latin1').split('\r\n');
122
144
  const statusLine = lines[0];
123
145
  const match = /^HTTP\/1\.[01] ([0-9]{3})(?: [^\r\n]*)?$/.exec(statusLine);
124
146
  if (!match) return fail(new TunnelError('PROTOCOL', 'Invalid HTTP proxy status line'));
@@ -128,7 +150,9 @@ function connectOne(authority: string, proxy: OpaqueProxyRoute, { signal, timeou
128
150
  }
129
151
  if (status < 200 || status >= 300) return fail(new TunnelError('REFUSED', 'HTTP proxy refused CONNECT', { status }));
130
152
  settled = true; socket.pause(); cleanup();
131
- const head = pending.subarray(end + 4);
153
+ // unshift is LIFO: restore the outside-cap suffix before the buffered head.
154
+ if (inputLength < chunk.length) socket.unshift(chunk.subarray(inputLength));
155
+ const head = received.subarray(end + 4);
132
156
  if (head.length) socket.unshift(head);
133
157
  resolve(socket);
134
158
  };
@@ -61,6 +61,7 @@ function decodedBody(
61
61
  maxBytes: number | undefined,
62
62
  context: string,
63
63
  release: () => void,
64
+ setBackpressure: (paused: boolean) => void,
64
65
  ): ReadableStream<Uint8Array> {
65
66
  // Interposed purely to attribute failures. Once bytes enter the decompressor, a transport
66
67
  // error and a corrupt trailer are indistinguishable from the far side of the pipe.
@@ -95,6 +96,7 @@ function decodedBody(
95
96
  return new ReadableStream<Uint8Array>({
96
97
  async pull(controller) {
97
98
  try {
99
+ setBackpressure(false);
98
100
  const next = await reader.read();
99
101
  if (next.done) {
100
102
  controller.close();
@@ -105,6 +107,9 @@ function decodedBody(
105
107
  throw new PinnedHttpError("output_byte_limit", `${context} exceeds ${maxBytes} byte cap`);
106
108
  }
107
109
  controller.enqueue(next.value);
110
+ // The native decoder may accept more coded input while its output is queued.
111
+ // Carry the final consumer's pressure to the socket as well as its immediate input.
112
+ setBackpressure(controller.desiredSize !== null && controller.desiredSize <= 0);
108
113
  } catch (error) {
109
114
  // A failure the socket stream raised is the caller's answer, whatever shape it has.
110
115
  // Only what the decompressor itself rejected is renamed.
@@ -284,9 +289,26 @@ function pinnedHttpRequest(
284
289
  }
285
290
 
286
291
  let received = 0;
292
+ let bodySettled = false;
293
+ let sourceDemand = true;
294
+ let decodedBackpressure = false;
295
+ let paused = false;
296
+ const updateBodyFlow = () => {
297
+ const shouldPause = !sourceDemand || decodedBackpressure;
298
+ if (bodySettled || paused === shouldPause) return;
299
+ paused = shouldPause;
300
+ if (paused) {
301
+ response.pause();
302
+ // A full local queue is consumer backpressure, not upstream inactivity.
303
+ // This also suspends the legacy request timeout on the same socket.
304
+ response.setTimeout(0);
305
+ } else {
306
+ response.setTimeout(inactivityTimeoutMs);
307
+ response.resume();
308
+ }
309
+ };
287
310
  const stream = new ReadableStream<Uint8Array>({
288
311
  start(controller) {
289
- let bodySettled = false;
290
312
  const failBody = (error: Error) => {
291
313
  if (bodySettled) return;
292
314
  bodySettled = true;
@@ -307,6 +329,8 @@ function pinnedHttpRequest(
307
329
  return;
308
330
  }
309
331
  try { controller.enqueue(buffer); } catch { /* closed */ }
332
+ sourceDemand = controller.desiredSize !== null && controller.desiredSize > 0;
333
+ updateBodyFlow();
310
334
  });
311
335
  response.on("end", () => {
312
336
  if (bodySettled) return;
@@ -317,7 +341,13 @@ function pinnedHttpRequest(
317
341
  failBody(error);
318
342
  });
319
343
  },
344
+ pull() {
345
+ sourceDemand = true;
346
+ updateBodyFlow();
347
+ },
320
348
  cancel() {
349
+ bodySettled = true;
350
+ response.destroy();
321
351
  req?.destroy();
322
352
  },
323
353
  });
@@ -329,7 +359,10 @@ function pinnedHttpRequest(
329
359
  try { req?.destroy(); } catch { /* ignore */ }
330
360
  };
331
361
  const payload = coding.kind === "decodable"
332
- ? decodedBody(stream, coding.format, maxBytes, context, release)
362
+ ? decodedBody(stream, coding.format, maxBytes, context, release, backpressured => {
363
+ decodedBackpressure = backpressured;
364
+ updateBodyFlow();
365
+ })
333
366
  : stream;
334
367
  resolve(new Response(payload, { status, headers: responseHeaders }));
335
368
  };
@@ -2,6 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { isIP } from "node:net";
3
3
  import { loadConfig } from "../config";
4
4
  import { readRuntimePort } from "../config/process-state";
5
+ import { directLocalHttpFetch } from "../server/direct-local-http";
5
6
  import { configuredAdminToken } from "./admin-secrets";
6
7
 
7
8
  export function isProcessAlive(pid: number): boolean {
@@ -203,6 +204,17 @@ export async function stopProxyGracefully(pid: number, io: GracefulStopIo = {}):
203
204
  */
204
205
  type StopRefusal = { message: string | null; code: string | null };
205
206
 
207
+ async function stopRequestFetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
208
+ let status: number | undefined;
209
+ try {
210
+ return await directLocalHttpFetch(input, init, { onResponseStatus: value => { status = value; } });
211
+ } catch (error) {
212
+ // A received refusal forbids forced stop even if its explanatory body fails.
213
+ if (status === 409) return new Response(null, { status });
214
+ throw error;
215
+ }
216
+ }
217
+
206
218
  async function stopProxyGracefullyDetailed(
207
219
  pid: number,
208
220
  io: GracefulStopIo = {},
@@ -217,7 +229,7 @@ async function stopProxyGracefullyDetailed(
217
229
  const headers: Record<string, string> = {};
218
230
  const token = configuredAdminToken(env.OPENCODEX_HOME?.trim() || undefined, env as NodeJS.ProcessEnv);
219
231
  if (token) headers["x-opencodex-api-key"] = token;
220
- const fetchFn = io.fetchFn ?? fetch;
232
+ const fetchFn = io.fetchFn ?? stopRequestFetch;
221
233
  let sharedTeardownConfirmed = false;
222
234
  try {
223
235
  // `ocx stop` asks the proxy NOT to restore shared client config: it does that itself,
@@ -1,3 +1,4 @@
1
+ import { createUploadWaiter } from "./socks5-upload-waiter";
1
2
  import net, { type Socket } from "node:net";
2
3
  import tls, { type TLSSocket } from "node:tls";
3
4
  import { classifyContentCoding, isNullBodyStatus } from "./http-response-semantics";
@@ -90,7 +91,7 @@ function connectSocket(hostname: string, port: number, signal?: AbortSignal): Pr
90
91
  }
91
92
 
92
93
  class SocketReader {
93
- private buffer = Buffer.alloc(0);
94
+ private buffer: Buffer = Buffer.alloc(0);
94
95
  private ended = false;
95
96
  private failure: Error | undefined;
96
97
  private readonly exactWaiters: Array<{
@@ -99,6 +100,7 @@ class SocketReader {
99
100
  reject: (error: unknown) => void;
100
101
  }> = [];
101
102
  private readonly anyWaiters: Array<{
103
+ maxBytes: number;
102
104
  resolve: (value: Buffer) => void;
103
105
  reject: (error: unknown) => void;
104
106
  }> = [];
@@ -122,10 +124,14 @@ class SocketReader {
122
124
  private readonly onData = (chunk: Buffer | string): void => {
123
125
  const value = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
124
126
  if (this.anyWaiters.length > 0) {
125
- this.anyWaiters.shift()!.resolve(value);
127
+ const waiter = this.anyWaiters.shift()!;
128
+ const end = Math.min(value.byteLength, waiter.maxBytes);
129
+ if (end < value.byteLength) this.buffer = value.subarray(end);
130
+ if (this.buffer.byteLength >= MAX_BODY_SLICE_BYTES) this.socket.pause();
131
+ waiter.resolve(end === value.byteLength ? value : value.subarray(0, end));
126
132
  return;
127
133
  }
128
- this.buffer = Buffer.concat([this.buffer, value]);
134
+ this.buffer = this.buffer.byteLength === 0 ? value : Buffer.concat([this.buffer, value]);
129
135
  this.flushExact();
130
136
  if (this.buffer.byteLength >= MAX_BODY_SLICE_BYTES) this.socket.pause();
131
137
  };
@@ -210,12 +216,13 @@ class SocketReader {
210
216
  }
211
217
  }
212
218
 
213
- readAny(signal?: AbortSignal): Promise<Buffer> {
219
+ readAny(signal?: AbortSignal, maxBytes = Number.MAX_SAFE_INTEGER): Promise<Buffer> {
214
220
  if (signal?.aborted) return Promise.reject(signal.reason ?? new Error("The operation was aborted"));
215
221
  if (this.buffer.byteLength > 0) {
216
- const value = this.buffer;
217
- this.buffer = Buffer.alloc(0);
218
- this.socket.resume();
222
+ const end = Math.min(this.buffer.byteLength, maxBytes);
223
+ const value = end === this.buffer.byteLength ? this.buffer : this.buffer.subarray(0, end);
224
+ this.buffer = end === this.buffer.byteLength ? Buffer.alloc(0) : this.buffer.subarray(end);
225
+ if (this.buffer.byteLength < MAX_BODY_SLICE_BYTES) this.socket.resume();
219
226
  return Promise.resolve(value);
220
227
  }
221
228
  if (this.failure) return Promise.reject(this.failure);
@@ -227,6 +234,7 @@ class SocketReader {
227
234
  waiter.reject(signal?.reason ?? new Error("The operation was aborted"));
228
235
  };
229
236
  const waiter = {
237
+ maxBytes,
230
238
  resolve: (value: Buffer) => { signal?.removeEventListener("abort", onAbort); resolve(value); },
231
239
  reject: (error: unknown) => { signal?.removeEventListener("abort", onAbort); reject(error); },
232
240
  };
@@ -237,13 +245,17 @@ class SocketReader {
237
245
  });
238
246
  }
239
247
 
240
- dispose(): void {
248
+ dispose(preserveBuffered = false): void {
241
249
  this.socket.pause();
242
250
  this.socket.removeListener("data", this.onData);
243
251
  this.socket.removeListener("error", this.onError);
244
252
  this.socket.removeListener("end", this.onEnd);
245
253
  this.socket.removeListener("close", this.onEnd);
246
- if (this.buffer.byteLength > 0) this.socket.unshift(this.buffer);
254
+ // Only a successful handshake hands unread bytes to another socket owner.
255
+ // Terminal cleanup must not unshift after EOF or retain abandoned payload.
256
+ if (preserveBuffered && !this.ended && !this.socket.destroyed && this.buffer.byteLength > 0) {
257
+ this.socket.unshift(this.buffer);
258
+ }
247
259
  this.buffer = Buffer.alloc(0);
248
260
  this.rejectExact(new Socks5FetchError("SOCKS5 reader disposed"));
249
261
  this.rejectAny(new Socks5FetchError("SOCKS5 reader disposed"));
@@ -268,7 +280,7 @@ async function socks5Connect(proxy: string, target: URL, signal?: AbortSignal):
268
280
  if (error instanceof Socks5HandshakeError) throw new Socks5FetchError(error.message);
269
281
  throw error;
270
282
  } finally {
271
- reader.dispose();
283
+ reader.dispose(true);
272
284
  }
273
285
  }
274
286
 
@@ -423,6 +435,7 @@ function responseBody(
423
435
  const chunked = (headers.get("transfer-encoding") ?? "").toLowerCase().split(",").some(value => value.trim() === "chunked");
424
436
  let remaining = contentLength;
425
437
  let chunkRemaining = 0;
438
+ let chunkTerminatorPending = false;
426
439
  let complete = false;
427
440
  const finish = () => {
428
441
  if (complete) return;
@@ -434,8 +447,24 @@ function responseBody(
434
447
  };
435
448
  const onAbort = () => socket.destroy();
436
449
  signal.addEventListener("abort", onAbort, { once: true });
450
+ // Framing needs exact reads, payload does not: waiting to fill 64 KiB can hold
451
+ // many complete SSE events behind bytes the upstream has not generated yet.
452
+ const readPayload = async (length: number): Promise<Buffer> => {
453
+ const value = await reader.readAny(signal, Math.min(length, MAX_BODY_SLICE_BYTES));
454
+ if (value.byteLength === 0) {
455
+ throw new Socks5FetchError("SOCKS5 socket ended before the expected bytes arrived");
456
+ }
457
+ return value;
458
+ };
437
459
  const readChunk = async (): Promise<Buffer | null> => {
438
460
  if (chunked) {
461
+ // Verify the previous chunk's delimiter before accepting another chunk,
462
+ // without holding already-received payload while the delimiter is delayed.
463
+ if (chunkTerminatorPending) {
464
+ const ending = await reader.read(2, signal);
465
+ if (!ending.equals(CRLF)) throw new Socks5FetchError("SOCKS5 upstream returned an invalid chunk terminator");
466
+ chunkTerminatorPending = false;
467
+ }
439
468
  if (chunkRemaining === 0) {
440
469
  const line = (await reader.readUntil(CRLF, MAX_RESPONSE_HEADER_BYTES, signal)).subarray(0, -2).toString("ascii");
441
470
  const size = parseChunkSize(line);
@@ -448,21 +477,18 @@ function responseBody(
448
477
  }
449
478
  chunkRemaining = size;
450
479
  }
451
- const value = await reader.read(Math.min(chunkRemaining, MAX_BODY_SLICE_BYTES), signal);
480
+ const value = await readPayload(chunkRemaining);
452
481
  chunkRemaining -= value.byteLength;
453
- if (chunkRemaining === 0) {
454
- const ending = await reader.read(2, signal);
455
- if (!ending.equals(CRLF)) throw new Socks5FetchError("SOCKS5 upstream returned an invalid chunk terminator");
456
- }
482
+ chunkTerminatorPending = chunkRemaining === 0;
457
483
  return value;
458
484
  }
459
485
  if (remaining !== undefined) {
460
486
  if (remaining === 0) return null;
461
- const value = await reader.read(Math.min(remaining, MAX_BODY_SLICE_BYTES), signal);
487
+ const value = await readPayload(remaining);
462
488
  remaining -= value.byteLength;
463
489
  return value;
464
490
  }
465
- const value = await reader.readAny(signal);
491
+ const value = await reader.readAny(signal, MAX_BODY_SLICE_BYTES);
466
492
  return value.byteLength === 0 ? null : value;
467
493
  };
468
494
  return new ReadableStream<Uint8Array>({
@@ -475,6 +501,12 @@ function responseBody(
475
501
  return;
476
502
  }
477
503
  controller.enqueue(value);
504
+ // A fixed-length response needs no further read to prove completion.
505
+ // Release its connection even when the consumer leaves this chunk queued.
506
+ if (!chunked && remaining === 0) {
507
+ finish();
508
+ controller.close();
509
+ }
478
510
  } catch (error) {
479
511
  finish();
480
512
  controller.error(error);
@@ -559,37 +591,9 @@ async function finalResponseHead(
559
591
  return head;
560
592
  }
561
593
 
562
- /**
563
- * A promise that rejects with the caller's abort reason, and a way to stop listening.
564
- *
565
- * Destroying the socket is not enough to end a pending `bodyReader.read()`: that promise belongs
566
- * to the caller's body stream, which knows nothing about this socket. Racing it against this one
567
- * is what turns an abort into a settled fetch instead of a permanently pending one.
568
- */
569
- function abortRejection(signal: AbortSignal): { promise: Promise<never>; dispose: () => void } {
570
- let onAbort = (): void => { /* replaced below */ };
571
- const promise = new Promise<never>((_resolve, reject) => {
572
- // Reject with the caller's reason exactly, including `null` and `false`. A real
573
- // `AbortSignal` always has one — `abort()` with no argument supplies an AbortError — so
574
- // the fallback covers only a hand-built signal that exposes none.
575
- onAbort = () => reject(signal.reason === undefined ? new Error("The operation was aborted") : signal.reason);
576
- if (signal.aborted) onAbort();
577
- else signal.addEventListener("abort", onAbort, { once: true });
578
- });
579
- // The race below may settle on another branch first; this rejection must not be reported as
580
- // unhandled when nobody is left waiting for it.
581
- promise.catch(() => { /* surfaced by whoever loses the race */ });
582
- return { promise, dispose: () => signal.removeEventListener("abort", onAbort) };
583
- }
584
-
585
- /**
586
- * The two races below have different possible outcomes, so they have different result types.
587
- * One union covering both would let the compiler accept reading `value` off a drain result,
588
- * which is the kind of mistake a type is supposed to catch rather than describe.
589
- */
590
- type Answered = { kind: "answered" };
591
- type BodyStep = { kind: "chunk"; value: Uint8Array } | { kind: "end" } | Answered;
592
- type DrainStep = { kind: "drained" } | Answered;
594
+ /** Read and drain results stay distinct; the waiter adds the shared early-answer outcome. */
595
+ type BodyStep = { kind: "chunk"; value: Uint8Array } | { kind: "end" };
596
+ type DrainStep = { kind: "drained" };
593
597
 
594
598
  /**
595
599
  * Send the request body, settling on caller abort or on an answer that arrives first.
@@ -613,21 +617,13 @@ async function uploadRequestBody(
613
617
  if (!body) return;
614
618
  const signal = request.signal;
615
619
  const bodyReader = body.getReader();
616
- const abort = abortRejection(signal);
617
- const answered: Promise<Answered> = head.then(
618
- (): Answered => ({ kind: "answered" }),
619
- (): Answered => ({ kind: "answered" }),
620
- );
620
+ const waiter = createUploadWaiter(head, signal);
621
621
  let completed = false;
622
622
  try {
623
623
  for (;;) {
624
- const read: Promise<BodyStep> = bodyReader.read().then(
624
+ const step = await waiter.wait(() => bodyReader.read().then(
625
625
  (result): BodyStep => (result.done ? { kind: "end" } : { kind: "chunk", value: result.value }),
626
- );
627
- // Releasing the lock below rejects a read still waiting on a source that stopped
628
- // producing. That rejection is this function's own doing, not a failure to report.
629
- read.catch(() => { /* settled by releasing the reader */ });
630
- const step = await Promise.race([read, answered, abort.promise]);
626
+ ));
631
627
  if (step.kind === "answered") break;
632
628
  if (step.kind === "end") {
633
629
  completed = true;
@@ -637,17 +633,16 @@ async function uploadRequestBody(
637
633
  ? Buffer.concat([Buffer.from(`${step.value.byteLength.toString(16)}\r\n`), Buffer.from(step.value), CRLF])
638
634
  : step.value;
639
635
  if (socket.write(payload)) continue;
640
- const drain: Promise<DrainStep> = waitForDrain(socket, signal).then((): DrainStep => ({ kind: "drained" }));
641
- if ((await Promise.race([drain, answered, abort.promise])).kind === "answered") break;
636
+ const drain = await waiter.wait(() => waitForDrain(socket, signal).then((): DrainStep => ({ kind: "drained" })));
637
+ if (drain.kind === "answered") break;
642
638
  }
643
639
  // A terminating chunk written after the peer has already answered goes into a conversation
644
640
  // that is over, and a peer that has moved on may read it as the head of the next request.
645
641
  if (completed && chunked && !socket.write("0\r\n\r\n")) {
646
- const drain: Promise<DrainStep> = waitForDrain(socket, signal).then((): DrainStep => ({ kind: "drained" }));
647
- await Promise.race([drain, answered, abort.promise]);
642
+ await waiter.wait(() => waitForDrain(socket, signal).then((): DrainStep => ({ kind: "drained" })));
648
643
  }
649
644
  } finally {
650
- abort.dispose();
645
+ waiter.dispose();
651
646
  if (!completed) {
652
647
  // Cancelling runs the caller's own cancel algorithm, which is free to never settle, so it
653
648
  // is started rather than awaited. Releasing the lock is what actually frees a read still
@@ -0,0 +1,50 @@
1
+ type Answered = { kind: "answered" };
2
+ type Interruption = { value: Answered } | { error: unknown };
3
+
4
+ /**
5
+ * One head observer and abort listener for a serial upload, not one Promise.race
6
+ * reaction per chunk. Only the current read/drain resolver is retained; clearing it
7
+ * lets completed read results go before a slow peer answers. The response owner
8
+ * still reports head failures, while cancellation keeps the caller's exact reason.
9
+ */
10
+ export function createUploadWaiter(head: Promise<unknown>, signal: AbortSignal) {
11
+ let interruption: Interruption | undefined;
12
+ let pending: {
13
+ resolve: (value: Answered) => void;
14
+ reject: (error: unknown) => void;
15
+ } | undefined;
16
+ const interrupt = (outcome: Interruption) => {
17
+ interruption ??= outcome;
18
+ if ("error" in interruption) pending?.reject(interruption.error);
19
+ else pending?.resolve(interruption.value);
20
+ };
21
+ const answered = () => interrupt({ value: { kind: "answered" } });
22
+ void head.then(answered, answered);
23
+ const onAbort = () => interrupt({
24
+ error: signal.reason === undefined ? new Error("The operation was aborted") : signal.reason,
25
+ });
26
+ if (signal.aborted) onAbort();
27
+ else signal.addEventListener("abort", onAbort, { once: true });
28
+
29
+ return {
30
+ async wait<T>(operation: () => Promise<T>): Promise<T | Answered> {
31
+ try {
32
+ return await new Promise<T | Answered>((resolve, reject) => {
33
+ pending = { resolve, reject };
34
+ if (interruption) {
35
+ interrupt(interruption);
36
+ return;
37
+ }
38
+ // Both outcomes stay observed when an early head/abort wins instead.
39
+ void operation().then(resolve, reject);
40
+ });
41
+ } finally {
42
+ pending = undefined;
43
+ }
44
+ },
45
+ dispose(): void {
46
+ pending = undefined;
47
+ signal.removeEventListener("abort", onAbort);
48
+ },
49
+ };
50
+ }