@bitkyc08/opencodex 2.99.0 → 2.100.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 (276) hide show
  1. package/AGENTS_INSTALL.md +19 -1
  2. package/README.md +37 -33
  3. package/SPONSORS.md +5 -1
  4. package/bin/ocx.mjs +1 -1
  5. package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
  6. package/gui/dist/assets/App-g3Cm2xhZ.js +59 -0
  7. package/gui/dist/assets/Tray-BMDkAiXy.js +1 -0
  8. package/gui/dist/assets/brand-mark-nr3ziR-T.js +1 -0
  9. package/gui/dist/assets/index-Bziu8gTy.css +2 -0
  10. package/gui/dist/assets/index-OYzhQUNP.js +94 -0
  11. package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-DKCVUUTi.js} +1 -1
  12. package/gui/dist/classic/assets/App-CgPBKUP-.js +58 -0
  13. package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-BedmOsE7.js} +1 -1
  14. package/gui/dist/classic/assets/index-BR-HhNrp.js +94 -0
  15. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +1 -0
  16. package/gui/dist/classic/index.html +1 -1
  17. package/gui/dist/index.html +2 -2
  18. package/native/ocx-child/Cargo.lock +215 -0
  19. package/native/ocx-child/Cargo.toml +31 -0
  20. package/native/ocx-child/src/cli.rs +1901 -0
  21. package/native/ocx-child/src/codex_home.rs +429 -0
  22. package/native/ocx-child/src/codex_settings.rs +231 -0
  23. package/native/ocx-child/src/daemon.rs +363 -0
  24. package/native/ocx-child/src/http_wire.rs +619 -0
  25. package/native/ocx-child/src/journal.rs +977 -0
  26. package/native/ocx-child/src/lib.rs +22 -0
  27. package/native/ocx-child/src/main.rs +9 -0
  28. package/native/ocx-child/src/parity.rs +102 -0
  29. package/native/ocx-child/src/platform.rs +1487 -0
  30. package/native/ocx-child/src/relay.rs +1288 -0
  31. package/native/ocx-child/src/relay_auth.rs +166 -0
  32. package/native/ocx-child/src/routes.rs +236 -0
  33. package/native/ocx-child/src/state.rs +190 -0
  34. package/native/ocx-child/src/test_hooks.rs +58 -0
  35. package/native/ocx-child/src/toml_surgeon.rs +1156 -0
  36. package/package.json +8 -2
  37. package/src/adapters/anthropic-image-normalize.ts +1 -1
  38. package/src/adapters/anthropic.ts +28 -2
  39. package/src/adapters/claude-cli/adapter.ts +5 -25
  40. package/src/adapters/claude-cli/instruction-images.ts +31 -0
  41. package/src/adapters/claude-cli/stable-replay.ts +42 -14
  42. package/src/adapters/claude-cli/usage-admission.ts +53 -64
  43. package/src/adapters/client-fingerprint.ts +1 -1
  44. package/src/adapters/coding-agent/protocol.ts +1 -1
  45. package/src/adapters/devin/live-models.ts +3 -0
  46. package/src/adapters/google-http.ts +3 -0
  47. package/src/adapters/google-vertex-key-project.ts +10 -2
  48. package/src/adapters/google.ts +40 -8
  49. package/src/adapters/kiro/usage.ts +3 -13
  50. package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
  51. package/src/adapters/openai-chat-images.ts +100 -0
  52. package/src/adapters/openai-chat.ts +6 -9
  53. package/src/adapters/openai-responses/passthrough.ts +5 -2
  54. package/src/adapters/openai-responses/request-strips.ts +32 -0
  55. package/src/adapters/openai-responses/tool-schema.ts +9 -4
  56. package/src/chat/inbound.ts +1 -1
  57. package/src/claude/auth-detect.ts +26 -8
  58. package/src/claude/inbound-content-options.ts +18 -3
  59. package/src/claude/inbound.ts +5 -2
  60. package/src/cli/bundled-bun-diagnostic.ts +91 -0
  61. package/src/cli/capabilities-agents-routing.ts +2 -2
  62. package/src/cli/capabilities-observe-system.ts +60 -0
  63. package/src/cli/combo-input.ts +6 -0
  64. package/src/cli/combo-result.ts +1 -1
  65. package/src/cli/combo.ts +4 -0
  66. package/src/cli/config-command.ts +16 -2
  67. package/src/cli/connect.ts +12 -10
  68. package/src/cli/dispatch.ts +4 -0
  69. package/src/cli/doctor.ts +11 -0
  70. package/src/cli/help.ts +1 -0
  71. package/src/cli/init.ts +4 -0
  72. package/src/cli/link-enrollment.ts +152 -25
  73. package/src/cli/link-local-control.ts +49 -0
  74. package/src/cli/link.ts +37 -10
  75. package/src/cli/provider-lifecycle-runtime.ts +4 -2
  76. package/src/cli/registry.ts +13 -0
  77. package/src/cli/star-prompt.ts +2 -0
  78. package/src/cli/status.ts +1 -1
  79. package/src/cli/telemetry-profile.ts +206 -0
  80. package/src/cli/telemetry.ts +260 -0
  81. package/src/client/hub-relay.ts +26 -0
  82. package/src/client/machine-api.ts +3 -0
  83. package/src/clients/config-export/t3code.ts +44 -5
  84. package/src/clients/omo-role-models.ts +1 -1
  85. package/src/codex/catalog/bundled.ts +44 -2
  86. package/src/codex/runtime.ts +12 -0
  87. package/src/codex/shim-restore-lock.ts +67 -30
  88. package/src/combos/types.ts +21 -1
  89. package/src/config/atomic-write.ts +24 -1
  90. package/src/config/diagnostics.ts +15 -0
  91. package/src/config/live-reconcile.ts +17 -0
  92. package/src/config/load-degrade.ts +16 -0
  93. package/src/config/provider-validation.ts +29 -0
  94. package/src/config/schema/config-schema.ts +24 -0
  95. package/src/config/schema/leaf-validators.ts +17 -0
  96. package/src/config/telemetry-carry.ts +30 -0
  97. package/src/config.ts +13 -1
  98. package/src/generated/compatibility-version.json +422 -170
  99. package/src/generated/model-metadata.ts +3 -3
  100. package/src/integrations/aside-profiles.ts +7 -1
  101. package/src/integrations/owned-refresh.ts +9 -2
  102. package/src/lab/artifacts/secure-fs.ts +12 -11
  103. package/src/lab/fabric/scratch.ts +11 -9
  104. package/src/lab/public/community.ts +2 -3
  105. package/src/lab/public/file-safety.ts +18 -20
  106. package/src/lab/public/mutation-lock.ts +109 -337
  107. package/src/lab/public/private-file.ts +4 -3
  108. package/src/lib/bun-runtime-preflight.ts +1 -1
  109. package/src/lib/codex-catalog-read-only.ts +122 -0
  110. package/src/lib/config-ownership.ts +56 -18
  111. package/src/lib/errors.ts +11 -0
  112. package/src/lib/gcp-adc.ts +167 -48
  113. package/src/lib/jsonc.ts +4 -2
  114. package/src/lib/local-control-socket.ts +88 -0
  115. package/src/lib/privacy.ts +15 -0
  116. package/src/lib/provider-client-headers.ts +3 -0
  117. package/src/lib/token-estimate.ts +13 -2
  118. package/src/link/child-binary-source.ts +228 -0
  119. package/src/link/ephemeral-child.ts +45 -0
  120. package/src/link/remote-plant.ts +306 -0
  121. package/src/link/remote-windows.ts +59 -5
  122. package/src/link/ssh-argv.ts +71 -8
  123. package/src/link/status-projection.ts +2 -0
  124. package/src/link/store.ts +5 -1
  125. package/src/oauth/anthropic-model-quota.ts +12 -0
  126. package/src/oauth/anthropic-routing.ts +11 -4
  127. package/src/oauth/claude-keychain-read.ts +165 -0
  128. package/src/oauth/kiro-iam-identity-center.ts +4 -1
  129. package/src/oauth/local-token-detect.ts +14 -17
  130. package/src/protocols/envelope.ts +20 -2
  131. package/src/providers/api-key-selection.ts +8 -2
  132. package/src/providers/claude-cli-identity.ts +9 -3
  133. package/src/providers/claude-cli-usage-state.ts +93 -0
  134. package/src/providers/claude-cli-usage.ts +3 -2
  135. package/src/providers/github-copilot-auto.ts +25 -5
  136. package/src/providers/meta-muse-plan-refusal.ts +94 -0
  137. package/src/providers/model-rename-fields.ts +3 -0
  138. package/src/providers/quota/anthropic-family-headers.ts +8 -1
  139. package/src/providers/quota/anthropic-usage-windows.ts +49 -2
  140. package/src/providers/quota/vendor-probes-key.ts +23 -4
  141. package/src/providers/quota/vendor-probes-oauth.ts +59 -0
  142. package/src/providers/quota/workbuddy.ts +2 -2
  143. package/src/providers/quota-types.ts +7 -0
  144. package/src/providers/quota.ts +25 -18
  145. package/src/providers/registry/entries-core.ts +7 -4
  146. package/src/providers/registry/entries-extended.ts +42 -8
  147. package/src/providers/registry/model-ids.ts +1 -0
  148. package/src/providers/registry/model-seeds.ts +10 -2
  149. package/src/providers/registry/types.ts +6 -0
  150. package/src/providers/resolved-model-policy.ts +4 -0
  151. package/src/providers/routed-config.ts +30 -3
  152. package/src/providers/stale-no-vision-seed-migration.ts +7 -0
  153. package/src/providers/vertex-environment-authority.ts +50 -0
  154. package/src/providers/workbuddy-credit-balance.ts +38 -6
  155. package/src/quota-pool/assemble.ts +14 -6
  156. package/src/responses/retained-compaction.ts +31 -5
  157. package/src/router.ts +1 -0
  158. package/src/server/adapter-resolve.ts +11 -6
  159. package/src/server/audio-dictation.ts +21 -7
  160. package/src/server/auth-cors.ts +19 -0
  161. package/src/server/background-lifecycle.ts +71 -0
  162. package/src/server/chat-completions.ts +2 -0
  163. package/src/server/claude-messages.ts +30 -3
  164. package/src/server/index/live-sideband.ts +15 -1
  165. package/src/server/index/local-control-listener.ts +515 -0
  166. package/src/server/index/optional-listeners.ts +21 -1
  167. package/src/server/index/serve-options.ts +4 -3
  168. package/src/server/index/websocket-handler.ts +2 -0
  169. package/src/server/index.ts +3 -0
  170. package/src/server/management/combo-routes.ts +6 -1
  171. package/src/server/management/context.ts +1 -0
  172. package/src/server/management/link-child-preflight.ts +74 -0
  173. package/src/server/management/link-enrollment.ts +190 -25
  174. package/src/server/management/link-route-state.ts +6 -1
  175. package/src/server/management/link-routes.ts +27 -9
  176. package/src/server/management/model-rows.ts +4 -0
  177. package/src/server/management/oauth-account-routes.ts +9 -4
  178. package/src/server/management/provider-overwrite-carry.ts +9 -2
  179. package/src/server/management/provider-routes.ts +14 -0
  180. package/src/server/management/provider-thinking-display-patch.ts +54 -0
  181. package/src/server/management/route-registry.ts +7 -0
  182. package/src/server/management/session-routes.ts +4 -1
  183. package/src/server/management/telemetry-routes.ts +37 -0
  184. package/src/server/management/usage-aggregate-cache.ts +290 -67
  185. package/src/server/management-api.ts +11 -2
  186. package/src/server/messages-native-preflight.ts +166 -0
  187. package/src/server/messages-native.ts +143 -43
  188. package/src/server/messages-shared.ts +14 -0
  189. package/src/server/proxy-liveness.ts +99 -6
  190. package/src/server/request-log-conversation.ts +18 -2
  191. package/src/server/request-log.ts +7 -2
  192. package/src/server/responses/adapter-continuation.ts +1 -0
  193. package/src/server/responses/adapter-dispatch.ts +11 -28
  194. package/src/server/responses/adapter-failure-message.ts +68 -0
  195. package/src/server/responses/combo-stream-preflight.ts +14 -2
  196. package/src/server/responses/compact.ts +13 -1
  197. package/src/server/responses/core-auth.ts +26 -5
  198. package/src/server/responses/core-codex-account.ts +8 -1
  199. package/src/server/responses/core-combo-failure.ts +6 -1
  200. package/src/server/responses/core-combo-native.ts +150 -37
  201. package/src/server/responses/core-combo.ts +15 -9
  202. package/src/server/responses/core-normalize.ts +1 -0
  203. package/src/server/responses/core-options.ts +7 -1
  204. package/src/server/responses/core-pipeline.ts +21 -1
  205. package/src/server/responses/fetch-helpers.ts +5 -0
  206. package/src/server/responses/opengateway-completion-guard.ts +7 -3
  207. package/src/server/responses/passthrough-delivery.ts +8 -1
  208. package/src/server/responses/passthrough-error.ts +22 -0
  209. package/src/server/responses/request-prepare.ts +7 -1
  210. package/src/server/responses/request-transport.ts +28 -5
  211. package/src/server/responses/run-turn-execution.ts +13 -0
  212. package/src/server/sse-frame-buffer.ts +5 -0
  213. package/src/server/ws-bridge.ts +10 -0
  214. package/src/service/launchd.ts +78 -4
  215. package/src/telemetry/aggregate.ts +348 -0
  216. package/src/telemetry/consent.ts +128 -0
  217. package/src/telemetry/contract.ts +403 -0
  218. package/src/telemetry/disclosure.ts +19 -0
  219. package/src/telemetry/install-id.ts +226 -0
  220. package/src/telemetry/payload.ts +129 -0
  221. package/src/telemetry/profile/client.ts +150 -0
  222. package/src/telemetry/profile/contract.ts +288 -0
  223. package/src/telemetry/profile/disclosure.ts +14 -0
  224. package/src/telemetry/profile/paths.ts +13 -0
  225. package/src/telemetry/profile/routes.ts +99 -0
  226. package/src/telemetry/profile/service.ts +234 -0
  227. package/src/telemetry/profile/state.ts +189 -0
  228. package/src/telemetry/profile/sync.ts +276 -0
  229. package/src/telemetry/routes.ts +183 -0
  230. package/src/telemetry/scheduler.ts +386 -0
  231. package/src/telemetry/sender.ts +97 -0
  232. package/src/telemetry/state.ts +334 -0
  233. package/src/types/combo-jev-effort-mode.ts +11 -0
  234. package/src/types/config.ts +3 -0
  235. package/src/types/provider.ts +11 -1
  236. package/src/types/request.ts +2 -0
  237. package/src/types/telemetry.ts +15 -0
  238. package/src/types/wire.ts +10 -0
  239. package/src/types.ts +5 -0
  240. package/src/update/index.ts +7 -1
  241. package/src/update/minisign.d.mts +17 -0
  242. package/src/update/minisign.mjs +88 -0
  243. package/src/update/signed-supply.d.mts +59 -0
  244. package/src/update/signed-supply.mjs +289 -0
  245. package/src/update/trust-root.json +38 -0
  246. package/src/update/update-bounded-json.d.mts +4 -0
  247. package/src/update/update-bounded-json.mjs +113 -0
  248. package/src/update/update-bytes.d.mts +2 -0
  249. package/src/update/update-bytes.mjs +23 -0
  250. package/src/update/update-candidate-id.d.mts +2 -0
  251. package/src/update/update-candidate-id.mjs +23 -0
  252. package/src/update/update-checkpoint-codec.d.mts +33 -0
  253. package/src/update/update-checkpoint-codec.mjs +217 -0
  254. package/src/update/update-contracts.d.mts +24 -0
  255. package/src/update/update-contracts.mjs +207 -0
  256. package/src/update/update-signature-threshold.d.mts +12 -0
  257. package/src/update/update-signature-threshold.mjs +47 -0
  258. package/src/update/update-signed-version.d.mts +5 -0
  259. package/src/update/update-signed-version.mjs +25 -0
  260. package/src/update/update-trust-anchor.d.mts +2 -0
  261. package/src/update/update-trust-anchor.mjs +2 -0
  262. package/src/usage/cache-diagnostic.ts +195 -50
  263. package/src/usage/expected-prices.ts +20 -2
  264. package/src/usage/filter-index.ts +1469 -0
  265. package/src/usage/ledger-scanner.ts +245 -4
  266. package/src/usage/source-filter.ts +10 -2
  267. package/src/usage/summary.ts +16 -0
  268. package/src/web-search/parse.ts +265 -38
  269. package/gui/dist/assets/App-BepstgEN.js +0 -59
  270. package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
  271. package/gui/dist/assets/brand-mark-wzPe3R-J.js +0 -1
  272. package/gui/dist/assets/index-C-9X2yaI.js +0 -94
  273. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  274. package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
  275. package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
  276. package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
@@ -97,6 +97,7 @@ import { clientWireOf } from "./inference/client-wire";
97
97
  import { directEncodersApply } from "./inference/client-encoder-delivery";
98
98
  import type { ClientEncoderOption } from "./responses/core-options";
99
99
  import { handleResponses } from "./responses";
100
+ import { resolveComboId } from "../combos";
100
101
  import { previewXaiOauthWireModel } from "./responses/core-normalize";
101
102
  import { upstreamWireForAdapter } from "../protocols/contract";
102
103
  import { createProtocolEnvelope, type ProtocolEnvelope } from "../protocols/envelope";
@@ -650,6 +651,7 @@ async function handleClaudeMessagesWithBudget(
650
651
  }
651
652
  // Model resolution reads this view; every other claudeCode setting keeps reading `config`.
652
653
  const cc = claudeCodeForIngress(config.claudeCode, ingress.claudeIntercept === true);
654
+ let nativeComboSource = false;
653
655
 
654
656
  let anthropicBody: unknown;
655
657
  let internalBody: Rec;
@@ -742,7 +744,12 @@ async function handleClaudeMessagesWithBudget(
742
744
  // proxy-owned `speed` + beta (anthropic-speed wire) and its usage.speed observation would be
743
745
  // silently skipped. Translation reaches the adapter, which owns both.
744
746
  const messagesBody = anthropicBody;
745
- if (isRec(messagesBody) && resolveProtocolSettings(config).unrepresentable === "reject") {
747
+ // An effort override rewrites the body below, so only an unrewritten body is a replay source;
748
+ // the envelope then keeps it by reference and charges no ingress copy.
749
+ nativeComboSource = !effortOverride && isRec(messagesBody) && typeof messagesBody.model === "string"
750
+ && resolveComboId(config, resolveInboundModel(messagesBody.model, cc)) !== null
751
+ && Object.keys(config.providers).some(name => resolveProtocolSettings(config, name).rollout.managedMessagesNative);
752
+ if (isRec(messagesBody) && (resolveProtocolSettings(config).unrepresentable === "reject" || nativeComboSource)) {
746
753
  envelope = createProtocolEnvelope({ inbound: "messages", body: messagesBody, translatorBudget });
747
754
  }
748
755
  const sourceEnvelope = envelope;
@@ -1127,7 +1134,8 @@ async function handleClaudeMessagesWithBudget(
1127
1134
  });
1128
1135
  }
1129
1136
  // Combo and policy children are judged per candidate (PF-07); an unknown model has no route.
1130
- if (envelope && settledRoute && !settledRoute.combo && settledRoute.routeKind !== "policy") {
1137
+ if (envelope && resolveProtocolSettings(config).unrepresentable === "reject"
1138
+ && settledRoute && !settledRoute.combo && settledRoute.routeKind !== "policy") {
1131
1139
  const verdict = checkRepresentable({
1132
1140
  inbound: "messages",
1133
1141
  requestPath: requestPathForLane(
@@ -1147,7 +1155,8 @@ async function handleClaudeMessagesWithBudget(
1147
1155
  }
1148
1156
  // PF-10: opaque thinking state reaches only first-party Anthropic; under `reject` a native
1149
1157
  // route to anyone else refuses the request instead of sending it without that state.
1150
- if (envelope && nativeMessagesRoute && !credentialDomainFor(nativeMessagesRoute.provider)?.firstPartyAnthropic
1158
+ if (envelope && resolveProtocolSettings(config).unrepresentable === "reject"
1159
+ && nativeMessagesRoute && !credentialDomainFor(nativeMessagesRoute.provider)?.firstPartyAnthropic
1151
1160
  && messagesBodyHasOpaqueState(anthropicBody as Rec)) {
1152
1161
  markProtocolBlocked(logCtx, { inbound: "messages", reasonCodes: ["feature-unrepresentable", "opaque-state-stripped"], features: messagesFeatures });
1153
1162
  logCtx.errorCode = "unsupported_feature";
@@ -1262,6 +1271,22 @@ async function handleClaudeMessagesWithBudget(
1262
1271
  // over, and TTL-less breakpoints take the destination default.
1263
1272
  cacheRetention: config.cacheRetention ?? callerCacheRetention(anthropicBody),
1264
1273
  }, logCtx, {
1274
+ ...(nativeComboSource && envelope && settledRoute?.combo ? {
1275
+ protocolSource: (await import("./messages-native")).createNativeMessagesComboSource({
1276
+ req, config, logCtx, envelope, requestedModel, translatorBudget, selector: nativeSelector,
1277
+ echoModel: clientFacingModelText(clientModelLabel),
1278
+ modelScope: resolveAdmissionModelScope(config, logIds?.admission),
1279
+ callerAnthropicBeta: req.headers.get("anthropic-beta"),
1280
+ clientIdentity: captureAnthropicClientIdentity(req.headers),
1281
+ sessionKey: anthropicSessionKeyFromParts({
1282
+ sessionIdHeader: req.headers.get("session_id")?.trim() || req.headers.get("x-claude-code-session-id"),
1283
+ threadIdHeader: req.headers.get("thread_id"),
1284
+ clientThreadId: logCtx.conversationId,
1285
+ promptCacheKey: typeof internalBody.prompt_cache_key === "string" ? internalBody.prompt_cache_key : null,
1286
+ promptCacheKeyIsSharedCohort: cacheKeySource === "system",
1287
+ }),
1288
+ }),
1289
+ } : {}),
1265
1290
  // Routing keeps Claude-only sidecar overrides; admission policy must follow the live owner.
1266
1291
  codexAuthPolicy: config,
1267
1292
  ...(logIds?.admission ? { admission: logIds.admission } : {}),
@@ -1309,6 +1334,8 @@ async function handleClaudeMessagesWithBudget(
1309
1334
  ? { directRequest: messagesDirectRequestOption(directPlan, anthropicBody, cc, translatorBudget) }
1310
1335
  : {}),
1311
1336
  });
1337
+ // Native combo children report through gated callbacks, not the Responses log inspector.
1338
+ if (clientWireOf(upstream) === "messages" && upstream.ok && settledRoute?.combo) return upstream;
1312
1339
  const response = logIds ? responseWithDeferredRequestLog(upstream, logIds.requestId, logIds.start, logCtx) : upstream;
1313
1340
  // Already in the Messages wire (direct encoder): no conversion.
1314
1341
  if (clientWireOf(upstream) === "messages") return response;
@@ -306,6 +306,18 @@ export function closeLiveSideband(ws: ServerWebSocket<WsData>, code = 1000, reas
306
306
  }
307
307
  }
308
308
 
309
+ /** Only dictation opts in: a validated close gets a separate bounded drain window. */
310
+ export function beginAudioFinalization(ws: ServerWebSocket<WsData>, raw: string | Buffer): void {
311
+ if (ws.data.liveFinalizationMs === undefined || ws.data.liveFinalizing || ws.data.liveClosing) return;
312
+ // The frame validator has already accepted this JSON text frame.
313
+ if (typeof raw !== "string" || JSON.parse(raw).type !== "session.close") return;
314
+ ws.data.liveFinalizing = true;
315
+ if (ws.data.liveSessionTimer !== undefined) clearTimeout(ws.data.liveSessionTimer);
316
+ ws.data.liveSessionTimer = setTimeout(() => {
317
+ closeLiveSideband(ws, 1000, "audio finalization expired");
318
+ }, ws.data.liveFinalizationMs);
319
+ }
320
+
309
321
  /**
310
322
  * Dial the upstream sideband and report whether its handshake reached 101.
311
323
  *
@@ -505,7 +517,9 @@ export function attachLiveSidebandUpstream(
505
517
  ws.data.liveOutcome = "timeout";
506
518
  closeLiveSideband(ws, 1011, "audio connection timed out");
507
519
  }, 10_000);
508
- ws.data.liveSessionTimer = setTimeout(() => closeLiveSideband(ws, 1000, "audio session expired"), ws.data.liveMaxSessionMs);
520
+ ws.data.liveSessionTimer = setTimeout(() => {
521
+ closeLiveSideband(ws, 1000, "audio session expired");
522
+ }, ws.data.liveMaxSessionMs);
509
523
  }
510
524
 
511
525
  upstream.addEventListener("close", (event) => {
@@ -0,0 +1,515 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import {
3
+ chmodSync,
4
+ linkSync,
5
+ lstatSync,
6
+ mkdirSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ renameSync,
10
+ unlinkSync,
11
+ writeFileSync,
12
+ type BigIntStats,
13
+ } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import type { Server } from "bun";
16
+ import { isLoopbackHostname } from "../../codex/loopback-target";
17
+ import { withLockClaim } from "../../codex/prompt-lock-claim";
18
+ import { ownEvidence, ownerDefaults, ownerState, type OwnerEvidence } from "../../codex/prompt-lock-owner";
19
+ import { getConfigDir } from "../../config/paths";
20
+ import { ConfigOwnershipLockError, registerOwnedConfigPath } from "../../lib/config-ownership";
21
+ import { assertNotRealHomeUnderTest } from "../../lib/test-home-guard";
22
+ import {
23
+ isPrivateSocketDir,
24
+ localControlLeasePath,
25
+ localControlPrivateSocketPath,
26
+ localControlSocketDir,
27
+ localControlSocketPath,
28
+ localControlSocketPathFits,
29
+ localControlSocketSupported,
30
+ } from "../../lib/local-control-socket";
31
+ import type { OcxConfig } from "../../types";
32
+
33
+ /**
34
+ * The one request the local control socket serves (#8184). `ocx link status` needs admin-token
35
+ * authority on trusted loopback ingress, which a hub whose public listener is not loopback cannot
36
+ * give it: the hub management listener is reached through Tailscale Serve, so it must never count
37
+ * as trusted loopback (#6913). The socket is a separate ingress with that trust, limited to this
38
+ * read and still requiring the admin token.
39
+ */
40
+ export function localControlRouteAllowed(url: URL, req: Request): boolean {
41
+ return req.method === "GET" && url.pathname === "/api/link/status" && !req.headers.has("upgrade");
42
+ }
43
+
44
+ /** A loopback public listener already gives the CLI trusted ingress; only other binds need this. */
45
+ export function localControlSocketWanted(config: Pick<OcxConfig, "hostname">): boolean {
46
+ return localControlSocketSupported() && !isLoopbackHostname(config.hostname ?? "127.0.0.1");
47
+ }
48
+
49
+ export interface LocalControlStartContext<T> {
50
+ config: OcxConfig;
51
+ publicPort: number;
52
+ dispatch: (req: Request, server: Server<T>) => Promise<Response>;
53
+ configDir?: string;
54
+ }
55
+
56
+ export interface LocalControlListener<T> {
57
+ ownsListener(server: Server<T>): boolean;
58
+ socketPath(): string | null;
59
+ start(ctx: LocalControlStartContext<T>): void;
60
+ /**
61
+ * Synchronous teardown for a startup that failed after this listener started. `startServer` is
62
+ * synchronous, so the ownership record has to go before the startup error propagates; an
63
+ * awaited `stop()` would leave a live lease nobody serves.
64
+ */
65
+ abort(): void;
66
+ stop(): Promise<void>;
67
+ }
68
+
69
+ function preparePrivateDir(dir: string): void {
70
+ assertNotRealHomeUnderTest(dirname(dir));
71
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
72
+ const stat = lstatSync(dir);
73
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid!()) {
74
+ throw new Error("socket directory is not a directory owned by this user");
75
+ }
76
+ chmodSync(dir, 0o700);
77
+ if (!isPrivateSocketDir(dir)) throw new Error("socket directory could not be made private");
78
+ }
79
+
80
+ /** Inode identity as the kernel reports it. Bigint keeps every bit of a Windows file ID. */
81
+ interface FileIdentity { dev: bigint; ino: bigint }
82
+
83
+ /**
84
+ * The per-port ownership record. `host` and `processStart` come from the shared owner evidence
85
+ * (`src/codex/prompt-lock-owner.ts`), so a record from another machine, or from a pid that has
86
+ * been reused, is never mistaken for a crashed predecessor.
87
+ */
88
+ interface LocalControlLease extends OwnerEvidence { token: string }
89
+
90
+ type LeaseRead =
91
+ | { kind: "absent" }
92
+ | { kind: "record"; lease: LocalControlLease }
93
+ | { kind: "unsafe" };
94
+
95
+ type LeaseDecision =
96
+ | { kind: "acquired" }
97
+ | { kind: "held" }
98
+ | { kind: "unsafe" }
99
+ | { kind: "contended" }
100
+ | { kind: "failed"; error: unknown };
101
+
102
+ const PUBLISH_ATTEMPTS = 4;
103
+ /** `withLockClaim` is a try-lock; a contender retries a bounded number of times and then refuses. */
104
+ const LEASE_LOCK_ATTEMPTS = 8;
105
+ const LEASE_LOCK_RETRY_MS = 2;
106
+ /** A release is on the shutdown path, so it retries longer than the acquire does. */
107
+ const RELEASE_ATTEMPTS = 12;
108
+ const RELEASE_RETRY_MS = 5;
109
+ /** Filesystems without hard links reject `link` with one of these; the socket cannot be published. */
110
+ const HARD_LINK_UNSUPPORTED = new Set(["EPERM", "EOPNOTSUPP", "ENOTSUP", "ENOSYS", "EXDEV", "EMLINK"]);
111
+ const HARD_LINK_WARNING = "[local-control] the socket directory's filesystem does not support hard links; ocx link status will use the TCP listener";
112
+
113
+ function isCode(error: unknown, code: string): boolean {
114
+ return !!error && typeof error === "object" && (error as { code?: unknown }).code === code;
115
+ }
116
+
117
+ function hardLinkUnsupported(error: unknown): boolean {
118
+ const code = (error as { code?: unknown } | null)?.code;
119
+ return typeof code === "string" && HARD_LINK_UNSUPPORTED.has(code);
120
+ }
121
+
122
+ function messageOf(error: unknown): string {
123
+ return error instanceof Error ? error.message : String(error);
124
+ }
125
+
126
+ /** A fresh identity per listener instance, so a same-pid restart never reuses a name or a record. */
127
+ function randomToken(): string {
128
+ return randomBytes(8).toString("hex");
129
+ }
130
+
131
+ /**
132
+ * Record the run directory as state uninstall may remove. Another runtime may hold the ownership
133
+ * lock for a moment, and refusing the socket over that transient would silently drop the only
134
+ * ingress `ocx link status` has on a hub, so a busy lock is retried briefly.
135
+ */
136
+ function registerRunDirectory(root: string, dir: string): void {
137
+ for (let attempt = 0; ; attempt += 1) {
138
+ try {
139
+ if (registerOwnedConfigPath(root, dir) === "full") {
140
+ console.warn("[local-control] the config ownership manifest is full; the run directory may survive uninstall");
141
+ }
142
+ return;
143
+ } catch (error) {
144
+ if (!(error instanceof ConfigOwnershipLockError) || attempt >= 2) throw error;
145
+ Bun.sleepSync(5);
146
+ }
147
+ }
148
+ }
149
+
150
+ function identityOf(path: string): FileIdentity | null {
151
+ try {
152
+ const stat = lstatSync(path, { bigint: true });
153
+ return { dev: stat.dev, ino: stat.ino };
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ function sameIdentity(path: string, identity: FileIdentity): boolean {
160
+ const current = identityOf(path);
161
+ return current !== null && current.dev === identity.dev && current.ino === identity.ino;
162
+ }
163
+
164
+ /**
165
+ * A record that exists but cannot be read is `unsafe`, never `absent`: treating a corrupt lease
166
+ * as "no owner" is how a live runtime gets displaced by a reader that could not parse it.
167
+ */
168
+ function readLease(path: string): LeaseRead {
169
+ let body: string;
170
+ try {
171
+ body = readFileSync(path, "utf8");
172
+ } catch (error) {
173
+ return isCode(error, "ENOENT") ? { kind: "absent" } : { kind: "unsafe" };
174
+ }
175
+ try {
176
+ const parsed = JSON.parse(body) as Partial<LocalControlLease>;
177
+ if (typeof parsed.token !== "string" || parsed.token.length === 0) return { kind: "unsafe" };
178
+ return { kind: "record", lease: parsed as LocalControlLease };
179
+ } catch {
180
+ return { kind: "unsafe" };
181
+ }
182
+ }
183
+
184
+ /** Replace the record in one rename, so no reader ever sees a half-written lease. */
185
+ function writeLease(path: string, lease: LocalControlLease): void {
186
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
187
+ try {
188
+ writeFileSync(temp, JSON.stringify(lease), { mode: 0o600 });
189
+ renameSync(temp, path);
190
+ } finally {
191
+ try { unlinkSync(temp); } catch { /* renamed or never written */ }
192
+ }
193
+ }
194
+
195
+ /** Remove the record only when it is still this instance's; the caller holds the claim mutex. */
196
+ function removeOwnedLease(path: string, token: string): void {
197
+ const current = readLease(path);
198
+ if (current.kind !== "record" || current.lease.token !== token) return;
199
+ try { unlinkSync(path); } catch { /* already gone */ }
200
+ }
201
+
202
+ /**
203
+ * Remove a private socket left by a runtime that died before it could clean up. The lease is ours,
204
+ * so every other `.c<port>.*` socket is a crashed predecessor's; a live owner would have kept the
205
+ * lease and this code would never run.
206
+ */
207
+ function removeOrphanPrivateSockets(port: number, configDir: string | undefined): void {
208
+ const dir = localControlSocketDir(configDir);
209
+ let entries: string[];
210
+ try { entries = readdirSync(dir); } catch { return; }
211
+ const prefix = `.c${port}.`;
212
+ for (const name of entries) {
213
+ if (!name.startsWith(prefix)) continue;
214
+ const candidate = join(dir, name);
215
+ try {
216
+ const stat = lstatSync(candidate);
217
+ if (stat.isSocket() && stat.uid === process.getuid!()) unlinkSync(candidate);
218
+ } catch { /* raced with another cleanup */ }
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Publish the private socket at the public path with an atomic hard link. The caller holds the
224
+ * lease, so a same-user socket already there can only be a crashed predecessor's and is removed;
225
+ * any other file is left alone and the socket is not served.
226
+ */
227
+ function publishPublicLink(target: string, privateTarget: string): void {
228
+ for (let attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt += 1) {
229
+ try {
230
+ linkSync(privateTarget, target);
231
+ return;
232
+ } catch (error) {
233
+ if (!isCode(error, "EEXIST")) throw error;
234
+ }
235
+ let existing: BigIntStats;
236
+ try {
237
+ existing = lstatSync(target, { bigint: true });
238
+ } catch (error) {
239
+ if (isCode(error, "ENOENT")) continue;
240
+ throw error;
241
+ }
242
+ if (!existing.isSocket() || existing.uid !== BigInt(process.getuid!())) throw new Error("socket path is occupied");
243
+ unlinkSync(target);
244
+ }
245
+ throw new Error("socket path is occupied");
246
+ }
247
+
248
+ /**
249
+ * Read the record, decide, and publish, all inside the shared claim mutex
250
+ * (`withLockClaim`, `src/codex/prompt-lock-claim.ts`). The mutex is what makes this a decision
251
+ * rather than a recheck: no other runtime can be between its own read and its own write, so a
252
+ * record judged stale cannot be replaced by a live one before this runtime publishes.
253
+ */
254
+ function acquireLease(leasePath: string, token: string, publish: () => void): LeaseDecision {
255
+ for (let attempt = 0; attempt < LEASE_LOCK_ATTEMPTS; attempt += 1) {
256
+ const outcome = withLockClaim(leasePath, token, ownerDefaults, (): LeaseDecision => {
257
+ const current = readLease(leasePath);
258
+ if (current.kind === "unsafe") return { kind: "unsafe" };
259
+ if (current.kind === "record") {
260
+ const state = ownerState(current.lease, ownerDefaults);
261
+ if (state !== "dead") return { kind: state === "live" ? "held" : "unsafe" };
262
+ }
263
+ // Absent, or provably a crashed predecessor: this runtime owns the port now.
264
+ writeLease(leasePath, { ...ownEvidence(ownerDefaults), token });
265
+ try {
266
+ publish();
267
+ } catch (error) {
268
+ removeOwnedLease(leasePath, token);
269
+ return { kind: "failed", error };
270
+ }
271
+ return { kind: "acquired" };
272
+ });
273
+ if (outcome.ok) return outcome.value;
274
+ if (attempt + 1 < LEASE_LOCK_ATTEMPTS) Bun.sleepSync(LEASE_LOCK_RETRY_MS);
275
+ }
276
+ return { kind: "contended" };
277
+ }
278
+
279
+ /** The record and the paths one runtime published, kept until the release actually succeeds. */
280
+ interface OwnedSocket {
281
+ leasePath: string;
282
+ token: string;
283
+ publicPath: string | null;
284
+ privatePath: string | null;
285
+ identity: FileIdentity | null;
286
+ }
287
+
288
+ type ReleaseOutcome =
289
+ | { kind: "released" }
290
+ | { kind: "contended" }
291
+ | { kind: "failed"; error: unknown };
292
+
293
+ /**
294
+ * A stop that could not give the port back. The record stays on the listener, so a later stop()
295
+ * or start() retries it; this error is how the caller learns the socket may still be live.
296
+ */
297
+ export class LocalControlReleaseError extends Error {
298
+ readonly code = "LOCAL_CONTROL_RELEASE_FAILED";
299
+ constructor(readonly outcome: "contended" | "failed", cause?: unknown) {
300
+ super(outcome === "contended"
301
+ ? "another runtime held the control socket ownership record; the lease and socket were left in place"
302
+ : "the control socket ownership record could not be released", { cause });
303
+ this.name = "LocalControlReleaseError";
304
+ }
305
+ }
306
+
307
+ function releaseFailure(outcome: Exclude<ReleaseOutcome, { kind: "released" }>): string {
308
+ return outcome.kind === "contended"
309
+ ? "another runtime held the control socket ownership record"
310
+ : `the control socket ownership record could not be released: ${messageOf(outcome.error)}`;
311
+ }
312
+
313
+ /**
314
+ * Remove the published link and the lease, inside the claim mutex. The outcome is explicit: a
315
+ * lost mutex is contention the caller must retry, never a release that silently did nothing.
316
+ */
317
+ function releaseOwnedSocket(state: OwnedSocket): ReleaseOutcome {
318
+ try {
319
+ const outcome = withLockClaim(state.leasePath, state.token, ownerDefaults, () => {
320
+ if (state.publicPath && state.identity && sameIdentity(state.publicPath, state.identity)) unlinkSync(state.publicPath);
321
+ if (state.privatePath && state.identity && sameIdentity(state.privatePath, state.identity)) unlinkSync(state.privatePath);
322
+ removeOwnedLease(state.leasePath, state.token);
323
+ });
324
+ return outcome.ok ? { kind: "released" } : { kind: "contended" };
325
+ } catch (error) {
326
+ return { kind: "failed", error };
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Retry a contended release a bounded number of times. The wait is synchronous on purpose:
332
+ * stop() has to give the record up before it suspends on its own socket teardown, or a successor
333
+ * starting in the same turn reads a live lease and abandons a port nobody will serve. A
334
+ * same-process peer holds this mutex only inside a synchronous critical section, so a blocking
335
+ * wait always reaches it; a peer process makes progress on its own.
336
+ */
337
+ function releaseBlocking(state: OwnedSocket): ReleaseOutcome {
338
+ let outcome = releaseOwnedSocket(state);
339
+ for (let attempt = 1; attempt < RELEASE_ATTEMPTS && outcome.kind === "contended"; attempt += 1) {
340
+ Bun.sleepSync(RELEASE_RETRY_MS);
341
+ outcome = releaseOwnedSocket(state);
342
+ }
343
+ return outcome;
344
+ }
345
+
346
+ const notFound = () => Response.json(
347
+ { error: { code: "not_found", message: "The local control socket serves only GET /api/link/status." } },
348
+ { status: 404 },
349
+ );
350
+
351
+ export function createLocalControlListener<T>(): LocalControlListener<T> {
352
+ let server: Server<T> | null = null;
353
+ let publicPath: string | null = null;
354
+ let privatePath: string | null = null;
355
+ let identity: FileIdentity | null = null;
356
+ let leasePath: string | null = null;
357
+ let leaseToken: string | null = null;
358
+ /** A release that could not run yet. Retained so the next stop() or start() finishes it. */
359
+ let pendingRelease: OwnedSocket | null = null;
360
+
361
+ const liveState = (): OwnedSocket | null => leasePath && leaseToken
362
+ ? { leasePath, token: leaseToken, publicPath, privatePath, identity }
363
+ : null;
364
+
365
+ const clearLive = (): void => {
366
+ server = null;
367
+ publicPath = null;
368
+ privatePath = null;
369
+ identity = null;
370
+ leasePath = null;
371
+ leaseToken = null;
372
+ };
373
+
374
+ return {
375
+ ownsListener: candidate => server !== null && candidate === server,
376
+ socketPath: () => publicPath,
377
+ start(ctx) {
378
+ if (server || !localControlSocketWanted(ctx.config)) return;
379
+ // A previous stop could not give the port back; finish that before asking for it again,
380
+ // because the record it left names this pid and would read as a live owner.
381
+ if (pendingRelease) {
382
+ const previous = releaseBlocking(pendingRelease);
383
+ if (previous.kind !== "released") {
384
+ console.warn(`[local-control] ${releaseFailure(previous)}; leaving the previous record in place`);
385
+ return;
386
+ }
387
+ pendingRelease = null;
388
+ }
389
+ const target = localControlSocketPath(ctx.publicPort, ctx.configDir);
390
+ const leaseFile = localControlLeasePath(ctx.publicPort, ctx.configDir);
391
+ const token = randomToken();
392
+ const privateTarget = localControlPrivateSocketPath(ctx.publicPort, token, ctx.configDir);
393
+ if (!localControlSocketPathFits(target) || !localControlSocketPathFits(privateTarget)) {
394
+ console.warn("[local-control] socket path is too long; ocx link status will use the TCP listener");
395
+ return;
396
+ }
397
+ try {
398
+ preparePrivateDir(dirname(target));
399
+ } catch (error) {
400
+ console.warn(`[local-control] socket unavailable: ${messageOf(error)}`);
401
+ return;
402
+ }
403
+ try {
404
+ // The run directory is state this runtime creates inside the config home, so uninstall has
405
+ // to know about it. Only the directory is recorded: the sockets and the lease inside it are
406
+ // transient, and the ownership API refuses to adopt an entry it did not record.
407
+ registerRunDirectory(ctx.configDir ?? getConfigDir(), dirname(target));
408
+ } catch (error) {
409
+ console.warn(`[local-control] socket unavailable: ${messageOf(error)}`);
410
+ return;
411
+ }
412
+ let bound: Server<T> | null = null;
413
+ let published: FileIdentity | null = null;
414
+ const publish = (): void => {
415
+ removeOrphanPrivateSockets(ctx.publicPort, ctx.configDir);
416
+ // Bun binds a process-specific address, so its own stop() can only ever unlink this one.
417
+ bound = Bun.serve<T, never>({
418
+ unix: privateTarget,
419
+ maxRequestBodySize: 0,
420
+ fetch(req, requestServer) {
421
+ let url: URL;
422
+ try { url = new URL(req.url); } catch { return notFound(); }
423
+ return localControlRouteAllowed(url, req) ? ctx.dispatch(req, requestServer) : notFound();
424
+ },
425
+ });
426
+ // The private directory is the access boundary; the socket mode is a second fence.
427
+ chmodSync(privateTarget, 0o600);
428
+ const socketIdentity = identityOf(privateTarget);
429
+ if (!socketIdentity) throw new Error("socket identity unavailable");
430
+ publishPublicLink(target, privateTarget);
431
+ published = socketIdentity;
432
+ };
433
+ let decision: LeaseDecision;
434
+ try {
435
+ decision = acquireLease(leaseFile, token, publish);
436
+ } catch (error) {
437
+ if (bound) void (bound as Server<T>).stop(true).catch(() => {});
438
+ console.warn(hardLinkUnsupported(error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(error)}`);
439
+ return;
440
+ }
441
+ if (decision.kind === "failed") {
442
+ if (bound) void (bound as Server<T>).stop(true).catch(() => {});
443
+ // Publishing is where a hard-link-less filesystem actually fails, and that error is
444
+ // returned rather than thrown, so this branch is the one that has to classify it.
445
+ console.warn(hardLinkUnsupported(decision.error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(decision.error)}`);
446
+ return;
447
+ }
448
+ if (decision.kind === "held") {
449
+ console.warn("[local-control] another runtime owns this port's control socket; leaving it in place");
450
+ return;
451
+ }
452
+ if (decision.kind === "unsafe") {
453
+ console.warn("[local-control] the control socket ownership record is not this machine's; leaving it in place");
454
+ return;
455
+ }
456
+ if (decision.kind === "contended") {
457
+ console.warn("[local-control] could not take the control socket ownership record; leaving it in place");
458
+ return;
459
+ }
460
+ server = bound;
461
+ publicPath = target;
462
+ privatePath = privateTarget;
463
+ identity = published;
464
+ leasePath = leaseFile;
465
+ leaseToken = token;
466
+ },
467
+ abort() {
468
+ const running = server;
469
+ // Bun's own stop unlinks the private name, so this rollback leaves that one to it.
470
+ const live = liveState();
471
+ const state = pendingRelease ?? (live ? { ...live, privatePath: null } : null);
472
+ clearLive();
473
+ // startServer is synchronous, so this rollback cannot await. Bun begins closing the listen
474
+ // socket on the call itself and unlinks its own private name; the published link and the
475
+ // lease must go now, because a stranded live lease keeps the next runtime off a dead socket.
476
+ if (running) {
477
+ try { void running.stop(true).catch(() => {}); } catch { /* the startup error is the one to report */ }
478
+ }
479
+ if (!state) return;
480
+ const outcome = releaseBlocking(state);
481
+ if (outcome.kind === "released") { pendingRelease = null; return; }
482
+ // abort() runs inside startServer's catch, so it must not replace the startup error. The
483
+ // record is retained and reported here, and the next stop() or start() retries it.
484
+ pendingRelease = state;
485
+ console.warn(`[local-control] ${releaseFailure(outcome)}; the record is retained for the next start or stop`);
486
+ },
487
+ async stop() {
488
+ const running = server;
489
+ const state = pendingRelease ?? liveState();
490
+ clearLive();
491
+ // Give the record up BEFORE awaiting the socket teardown. A successor that starts while
492
+ // this stop is suspended must not read a live lease and abandon a port nobody will serve.
493
+ let releaseError: LocalControlReleaseError | null = null;
494
+ if (state) {
495
+ const outcome = releaseBlocking(state);
496
+ if (outcome.kind === "released") {
497
+ pendingRelease = null;
498
+ } else {
499
+ pendingRelease = state;
500
+ releaseError = new LocalControlReleaseError(outcome.kind, outcome.kind === "failed" ? outcome.error : undefined);
501
+ }
502
+ }
503
+ let failure: unknown;
504
+ try {
505
+ if (running) await running.stop(true);
506
+ } catch (error) {
507
+ failure = error;
508
+ }
509
+ // A record that could not be released is the failure worth reporting: the socket may live,
510
+ // and the caller's shutdown has to say so rather than look complete.
511
+ if (releaseError) throw releaseError;
512
+ if (failure) throw failure;
513
+ },
514
+ };
515
+ }