@bitkyc08/opencodex 2.92.0 → 2.93.0-preview.20261027

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 (259) hide show
  1. package/bin/ocx.mjs +10 -5
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BSsxznDm.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/{index-BlFE_VB_.js → index-Xfct8owH.js} +12 -12
  6. package/gui/dist/assets/{quota-summary-BRlbXgw0.js → quota-summary-DxToX1rV.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/App-sUf_8afJ.js +0 -58
  259. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
@@ -1,5 +1,6 @@
1
1
  import { comboFailureDecision } from "../../combos/failover";
2
2
  import { readBoundedResponseBody } from "../../lib/bounded-body";
3
+ import { isVerifiedModelNotInPlanResponse } from "../../lib/errors";
3
4
  import { isNonReplayableResponse } from "../../lib/upstream-retry";
4
5
  import { finishRequestAttempt, type RequestLogContext } from "../request-log";
5
6
  import { linkRequestSessionLane } from "../request-log-conversation";
@@ -130,7 +131,11 @@ async function shouldHopPolicyCandidate(response: Response, signal?: AbortSignal
130
131
  try {
131
132
  const inspected = await readBoundedResponseBody(response.clone(), { signal });
132
133
  const text = inspected.displaySafe && !inspected.truncated ? inspected.text : "";
133
- return comboFailureDecision(response.status, text, { code: errorCodeFromText(text) }) === "hop";
134
+ return comboFailureDecision(response.status, text, {
135
+ code: errorCodeFromText(text),
136
+ // A passthrough candidate returns its upstream body unchanged, so the code is not provenance.
137
+ verifiedPlanRefusal: isVerifiedModelNotInPlanResponse(response),
138
+ }) === "hop";
134
139
  } catch {
135
140
  return false;
136
141
  }
@@ -1,5 +1,5 @@
1
1
  import { Buffer } from "node:buffer";
2
- import { constants, gzipSync, zstdCompressSync } from "node:zlib";
2
+ import { constants, zstdCompressSync } from "node:zlib";
3
3
  import type { OcxConfig } from "../../types";
4
4
 
5
5
  /**
@@ -49,13 +49,18 @@ export function currentUpstreamRequestCompression(): UpstreamRequestCompression
49
49
  return resolveUpstreamRequestCompression(boundConfig?.upstreamRequestCompression);
50
50
  }
51
51
 
52
- // ArrayBuffer-backed, which is what node:zlib returns and what a fetch BodyInit accepts.
52
+ // ArrayBuffer-backed bytes, accepted by fetch without another input conversion.
53
53
  type CodedBytes = Buffer<ArrayBuffer>;
54
- type Compressor = (mode: Exclude<UpstreamRequestCompression, "off">, bytes: Buffer) => CodedBytes;
54
+ type Compressor = (mode: Exclude<UpstreamRequestCompression, "off">, body: string) => CodedBytes;
55
55
 
56
- const defaultCompressor: Compressor = (mode, bytes) => mode === "gzip"
57
- ? gzipSync(bytes, { level: 1 }) as CodedBytes
58
- : zstdCompressSync(bytes, { params: { [constants.ZSTD_c_compressionLevel]: 3 } }) as CodedBytes;
56
+ const defaultCompressor: Compressor = (mode, body) => {
57
+ if (mode === "gzip") {
58
+ // Native string input avoids a full-body UTF-8 Buffer; only view the coded output as a Buffer.
59
+ const bytes = Bun.gzipSync(body, { level: 1 });
60
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
61
+ }
62
+ return zstdCompressSync(Buffer.from(body, "utf8"), { params: { [constants.ZSTD_c_compressionLevel]: 3 } }) as CodedBytes;
63
+ };
59
64
 
60
65
  let compressor: Compressor = defaultCompressor;
61
66
  let maxBodyBytes = MAX_COMPRESSIBLE_BODY_BYTES;
@@ -90,7 +95,7 @@ export function compressUpstreamRequestBody(
90
95
  const size = Buffer.byteLength(body, "utf8");
91
96
  if (size < MIN_COMPRESSIBLE_BODY_BYTES || size > maxBodyBytes) return null;
92
97
  try {
93
- return { body: compressor(mode, Buffer.from(body, "utf8")), encoding: mode };
98
+ return { body: compressor(mode, body), encoding: mode };
94
99
  } catch {
95
100
  // Deliberately silent: the error could only describe the body, and identity is still correct.
96
101
  return null;
@@ -163,7 +163,7 @@ import {
163
163
  import { acquireUpstreamHostAdmission } from "../../codex/upstream-host-health";
164
164
  import { applyCompactionRoutingOverride, compactionRoutingKeepsProviderIdentity } from "./compaction-routing";
165
165
  import { applyMainHardLockFallbackOverride } from "./main-hard-lock-routing";
166
- import { FallbackRefusedError } from "../../routing/fallback-policy";
166
+ import { FallbackRefusedError, guardFallbackHop } from "../../routing/fallback-policy";
167
167
  import { codexAuthContextLogLabel } from "../../codex/account-label";
168
168
  import {
169
169
  conversationStateBindingFromAuth,
@@ -665,7 +665,10 @@ export async function prepareResponsesRequest(
665
665
  if (candidate.combo?.target.metered && !admissionMayUseMeteredComboTargets(
666
666
  config, options.admission, config.combos?.[candidate.combo.comboId],
667
667
  )) {
668
- const pick = pickComboTarget(config, candidate.combo.comboId, { eligible: target => !target.metered });
668
+ const pick = pickComboTarget(config, candidate.combo.comboId, {
669
+ eligible: target => !target.metered,
670
+ allowCooldownReprobe: false,
671
+ });
669
672
  if (!pick) {
670
673
  throw new NoAvailableComboTargetsError(candidate.combo.comboId,
671
674
  comboExclusionReasons(config, candidate.combo.comboId, target => !target.metered));
@@ -778,6 +781,23 @@ export async function prepareResponsesRequest(
778
781
  if (parsed._compactionRequest === true || options.compactionRoutingOverride) parsed._cursorIsolateConversation = true;
779
782
  route = memoryRoute ?? shadowRoute ?? resolveRoute(options.policyFallbackCandidate
780
783
  ? `${options.policyFallbackCandidate.provider}/${options.policyFallbackCandidate.model}` : parsed.modelId);
784
+ // Selection-free hard-lock preflight grants no hop. Enforce the actual ranked destination
785
+ // against the locked source before admitting this first selection.
786
+ const hardLockProfileTrace = options.mainHardLockFallbackOverride ? route.routeDecision?.profile : undefined;
787
+ if (hardLockProfileTrace && options.mainHardLockFallbackOverride) {
788
+ const override = options.mainHardLockFallbackOverride;
789
+ const hop = guardFallbackHop(config, {
790
+ site: "routing-profile",
791
+ route: override.sourceModel,
792
+ aliases: [`policy/${hardLockProfileTrace.id}`],
793
+ from: { provider: OPENAI_CODEX_PROVIDER_ID, model: override.sourceModel },
794
+ to: { provider: route.providerName, model: route.modelId },
795
+ trigger: "hard_lock",
796
+ admission: options.admission,
797
+ });
798
+ if (!hop.ok) return hop.response;
799
+ hop.commit();
800
+ }
781
801
  leaveDirectLaneIfRerouted(options, route, parsed, logCtx);
782
802
  // Name the phase in the persisted route decision, so the request log says why this turn went to
783
803
  // the memory destination instead of leaving it looking like a plain user selection. Set here, on
@@ -52,6 +52,7 @@ export async function prepareResponsesSidecarAuth(
52
52
  const visionDescribeTerminal = options.visionDescribeTerminal === true;
53
53
  const routedCompaction = parsed._compactionRequest === true
54
54
  && (!supportsNativeResponsesCompactionTrigger(route.provider) || parsed._portableCompaction === true);
55
+ const preserveCompactionPrefix = routedCompaction && transportState.adapter.name === "anthropic";
55
56
  if (routedCompaction) parsed.context.messages = omitEarlierCompactionImages(parsed.context.messages);
56
57
  const needsOpenAiVision = !visionDescribeTerminal
57
58
  && shouldResolveOpenAiVisionSidecar(config, route.provider, route.modelId, parsed, route.providerName);
@@ -158,6 +159,7 @@ export async function prepareResponsesSidecarAuth(
158
159
  return {
159
160
  openAiSidecar,
160
161
  routedCompaction,
162
+ preserveCompactionPrefix,
161
163
  };
162
164
  }
163
165
 
@@ -1,3 +1,4 @@
1
+ import { requiresToolCall } from "../../types";
1
2
  import type { ResponsesRequestContext, ResponsesAdmissionState } from "./core-options";
2
3
  import type { PreparedResponsesRequest } from "./request-prepare";
3
4
  import type { ResponsesSidecarAuth } from "./request-sidecar-auth";
@@ -26,11 +27,11 @@ export function createResponsesEffects(
26
27
  | "route"
27
28
  | "substituteMainCredential"
28
29
  >,
29
- sidecarState: Pick<ResponsesSidecarAuth, "routedCompaction">,
30
+ sidecarState: Pick<ResponsesSidecarAuth, "routedCompaction"> & Partial<Pick<ResponsesSidecarAuth, "preserveCompactionPrefix">>,
30
31
  ) {
31
32
  const { options, req, config } = requestContext;
32
33
  const { parsed, poolAffinityKey, route, substituteMainCredential } = requestState;
33
- const { routedCompaction } = sidecarState;
34
+ const { routedCompaction, preserveCompactionPrefix } = sidecarState;
34
35
 
35
36
 
36
37
  const recordTerminalOutcomes = options.recordTerminalOutcomes !== false;
@@ -67,8 +68,8 @@ export function createResponsesEffects(
67
68
 
68
69
  // Remote compaction v2 on a ROUTED model: Codex sent `compaction_trigger` and requires exactly
69
70
  // one `{type:"compaction"}` output item (codex-rs compact_remote_v2.rs). Passthrough handles it
70
- // natively upstream; here we run the routed model as a plain summarizer — no tools, no web-search
71
- // sidecar — and the bridge appends the synthetic compaction item (src/responses/compaction.ts).
71
+ // natively upstream; here the routed model summarizes without sidecar execution, and the
72
+ // bridge appends the synthetic compaction item (src/responses/compaction.ts).
72
73
  // A Responses-shaped wire does not imply support for Codex's private
73
74
  // `compaction_trigger` item — only the canonical ChatGPT backend speaks that
74
75
  // contract. An API-key gateway would receive the trigger, answer with an ordinary
@@ -87,12 +88,21 @@ export function createResponsesEffects(
87
88
  }
88
89
  };
89
90
  if (routedCompaction) {
90
- delete parsed.context.tools;
91
91
  delete parsed._webSearch;
92
- delete parsed._anthropicServerTools;
93
- delete parsed._anthropicServerReplay;
94
- delete parsed.options.toolChoice;
95
- delete parsed.options.parallelToolCalls;
92
+ if (!preserveCompactionPrefix) {
93
+ delete parsed.context.tools;
94
+ delete parsed._anthropicServerTools;
95
+ delete parsed._anthropicServerReplay;
96
+ delete parsed.options.toolChoice;
97
+ delete parsed.options.parallelToolCalls;
98
+ } else if (parsed._anthropicServerTools?.length || requiresToolCall(parsed.options.toolChoice)) {
99
+ // Hosted tools execute upstream, and a mandatory choice would force a call the summary
100
+ // guard must reject. Keep the choice itself so the adapter derives the same tools and
101
+ // system bytes; the adapter replaces only the final wire tool_choice with "none".
102
+ // tool_choice changes invalidate message cache, not tools/system (Anthropic caching docs).
103
+ parsed._summaryProhibitsToolCalls = true;
104
+ }
105
+ // Client tool events are rejected by guardCompactionSummary before reaching Codex.
96
106
  // The compaction turn is a plain prose summary; a surviving structured-output format
97
107
  // would force schema-constrained JSON into the synthetic compaction item. The flag and
98
108
  // the raw `text` control go too: the key-mode openai-responses adapter builds from
@@ -105,7 +115,9 @@ export function createResponsesEffects(
105
115
  }
106
116
  parsed.context.messages = [
107
117
  ...parsed.context.messages,
108
- { role: "user", content: COMPACT_PROMPT, timestamp: Date.now() },
118
+ { role: "user", content: preserveCompactionPrefix
119
+ ? `${COMPACT_PROMPT}\n\nReturn only the handoff summary. Do not call tools or continue the task.`
120
+ : COMPACT_PROMPT, timestamp: Date.now() },
109
121
  ];
110
122
  }
111
123
 
@@ -34,6 +34,7 @@ import {
34
34
  } from "../../oauth/generic-account-failover";
35
35
  import { classifyKiroRefusal } from "../../adapters/kiro-refusal";
36
36
  import { isNonReplayableResponse, SendBudgetExhaustedError } from "../../lib/upstream-retry";
37
+ import { isVerifiedModelNotInPlanResponse, markVerifiedModelNotInPlanResponse } from "../../lib/errors";
37
38
  import { unwrapUpstreamRetryEvidenceError } from "../../codex/auth-context";
38
39
  import { AdmissionModelDeniedError, admissionModelDeniedResponse } from "../admission-model-scope";
39
40
  import { noteKiroMonthlyRefusal, noteKiroServedSuccess } from "../../providers/kiro-usage";
@@ -200,7 +201,7 @@ export async function executeResponsesSidecars(
200
201
  }
201
202
 
202
203
  // Image / web-search sidecars: plan once, then dispatch with runTurn-aware priority.
203
- // Routed-compaction turns must NOT hit the image bridge: compaction clears tools/_webSearch but
204
+ // Routed-compaction turns must NOT hit the image bridge: compaction disables tool execution but
204
205
  // leaves _imageGeneration, so planImageBridge would activate and return a normal Responses
205
206
  // completion instead of the synthetic compaction item Codex expects (#424).
206
207
  //
@@ -584,6 +585,7 @@ export async function executeResponsesSidecars(
584
585
  return fetch.unpacedFetch ?? fetch;
585
586
  },
586
587
  onRequestBuilt: request => {
588
+ if (typeof request.usageLog?.inputTokens === "number") logCtx.usageLogInputTokens = request.usageLog.inputTokens;
587
589
  recordAdapterReasoning(logCtx, request);
588
590
  recordAdapterTier(logCtx, request);
589
591
  },
@@ -630,10 +632,13 @@ export async function executeResponsesSidecars(
630
632
  if (imgResponse.body) {
631
633
  const imgTurnAc = new AbortController();
632
634
  imgTurnAc.signal.addEventListener("abort", cancelResponseCompletion, { once: true });
633
- return new Response(trackStreamLifetime(imgResponse.body, imgTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
635
+ const tracked = new Response(trackStreamLifetime(imgResponse.body, imgTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
634
636
  status: imgResponse.status,
635
637
  headers: imgResponse.headers,
636
638
  });
639
+ // The wrapper is a new object; a verified plan refusal keeps its provenance across it.
640
+ if (isVerifiedModelNotInPlanResponse(imgResponse)) markVerifiedModelNotInPlanResponse(tracked);
641
+ return tracked;
637
642
  }
638
643
  releaseSearchProbeLease();
639
644
  return imgResponse;
@@ -694,6 +699,7 @@ export async function executeResponsesSidecars(
694
699
  abortSignal: options.abortSignal,
695
700
  onFirstOutput: noteSidecarOutput,
696
701
  onRequestBuilt: request => {
702
+ if (typeof request.usageLog?.inputTokens === "number") logCtx.usageLogInputTokens = request.usageLog.inputTokens;
697
703
  recordAdapterReasoning(logCtx, request);
698
704
  recordAdapterTier(logCtx, request);
699
705
  },
@@ -749,10 +755,12 @@ export async function executeResponsesSidecars(
749
755
  if (wsResponse.body) {
750
756
  const wsTurnAc = new AbortController();
751
757
  wsTurnAc.signal.addEventListener("abort", cancelResponseCompletion, { once: true });
752
- return new Response(trackStreamLifetime(wsResponse.body, wsTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
758
+ const tracked = new Response(trackStreamLifetime(wsResponse.body, wsTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
753
759
  status: wsResponse.status,
754
760
  headers: wsResponse.headers,
755
761
  });
762
+ if (isVerifiedModelNotInPlanResponse(wsResponse)) markVerifiedModelNotInPlanResponse(tracked);
763
+ return tracked;
756
764
  }
757
765
  releaseSearchProbeLease();
758
766
  return wsResponse;
@@ -15,9 +15,18 @@ import type { ManagementPrincipal } from "./management-auth";
15
15
 
16
16
  export type GrokStripResult = { ok: boolean; changed: boolean; message: string };
17
17
 
18
+ /** Read-only promise covering API teardown and the CLI runtime's signal/manager exit cleanup. */
19
+ export function stopCapabilities() {
20
+ return { schema: "ocx-stop-capabilities/1", connectedClientOwnership: true, pid: process.pid };
21
+ }
22
+
18
23
  export type StopTeardownIo = {
19
24
  /** Does the nonce this request carries name a readable obligation on disk? */
20
25
  ownsReceipt?: (nonce: string | null) => boolean;
26
+ /** Does that obligation hand the teardown to the proxy an update restarts (#7423)? */
27
+ isHandoverReceipt?: (nonce: string | null) => boolean;
28
+ /** Keep Codex, Grok and env fences in place when this process exits. */
29
+ keepClientConfigOnExit?: () => void;
21
30
  restoreNativeCodex?: () => Promise<CodexNativeRestoreResult>;
22
31
  stripGrok?: () => GrokStripResult;
23
32
  };
@@ -25,7 +34,7 @@ export type StopTeardownIo = {
25
34
  export type StopTeardownBody = {
26
35
  success: boolean;
27
36
  message: string;
28
- /** `not-owned`: a sibling instance, whose shared client routing belongs to the live owner. */
37
+ /** `not-owned`: shared routing belongs to a live sibling owner or a client connection. */
29
38
  sharedTeardown: "deferred" | "performed" | "not-owned";
30
39
  };
31
40
 
@@ -79,8 +88,34 @@ export async function performStopTeardown(url: URL, io: StopTeardownIo = {}): Pr
79
88
  if (siblingOfLivePort() !== null) {
80
89
  return { success: true, message: `Proxy stopping. ${siblingSkipMessage()}`, sharedTeardown: "not-owned" };
81
90
  }
91
+ // A connection owns its integrations across stop/start, even for a successful API stop.
92
+ // This is persisted authority, not a caller's request to skip an obligation it owns.
93
+ const connection = (await import("../client/state")).readClientConnectionState();
94
+ if (connection.kind === "connected") {
95
+ return {
96
+ success: true,
97
+ message: "Proxy stopping; connection-owned Codex routing, catalog and Grok config preserved. Run `ocx disconnect` to release them.",
98
+ sharedTeardown: "not-owned",
99
+ };
100
+ }
82
101
  const ownsReceipt = io.ownsReceipt ?? deferralMatchesReceipt;
83
102
  if (deferralHonored(url, ownsReceipt)) {
103
+ // A handover outlives this process: the exit cleanup would otherwise restore native
104
+ // Codex and put the pristine catalog back right after the stop kept them (#7423).
105
+ // Exiting as a recycle leaves them for the replacement, as a dashboard restart does.
106
+ const nonce = url.searchParams.get("teardownNonce");
107
+ const handover = io.isHandoverReceipt
108
+ ? io.isHandoverReceipt(nonce)
109
+ : (await import("../config/pending-teardown")).isUpdateHandoverReceipt(nonce);
110
+ if (handover) {
111
+ if (io.keepClientConfigOnExit) io.keepClientConfigOnExit();
112
+ else (await import("./lifecycle")).markRecyclingForExit();
113
+ return {
114
+ success: true,
115
+ message: "Proxy stopping; Codex routing and catalog kept for the updated proxy.",
116
+ sharedTeardown: "deferred",
117
+ };
118
+ }
84
119
  // Not "native Codex restored": nothing was restored here, and claiming otherwise
85
120
  // would be a success message the operator cannot verify.
86
121
  return {
@@ -64,7 +64,7 @@ export interface WsData {
64
64
  liveUpstreamHandoff?: LiveSidebandUpstreamHandoff;
65
65
  /** Once teardown starts, ignore new client frames until the upstream closes. */
66
66
  liveClosing?: boolean;
67
- /** Schedules one bounded close retry without surrendering native-main ownership. */
67
+ /** Terminates a stalled close without releasing ownership before transport closure. */
68
68
  liveCloseFallback?: ReturnType<typeof setTimeout>;
69
69
  /** Turn/account ownership retained for the complete sideband socket lifetime. */
70
70
  liveTurnAdmissionLease?: AdmissionLease;
@@ -27,18 +27,18 @@ export interface WindowsProcessReadOptions {
27
27
  /** Called with the parent image before row validation, so partial Desktop evidence keeps its veto. */
28
28
  onExecutable?: (path: string) => void;
29
29
  timeoutMs?: number;
30
- env?: NodeJS.ProcessEnv;
30
+ resolveSystemDirectory?: () => string;
31
31
  }
32
32
 
33
33
  export interface DesktopSupervisionDeps {
34
34
  targetPid?: number;
35
35
  platform?: NodeJS.Platform;
36
- run?: (command: string, args: string[], timeoutMs?: number) => string;
36
+ run?: (command: string, args: string[], timeoutMs?: number, env?: NodeJS.ProcessEnv) => string;
37
37
  proc?: ProcReader;
38
38
  readPid?: () => number | null;
39
39
  readRuntimePortPid?: () => number | null;
40
40
  windowsProcesses?: (pid: number, options: Pick<WindowsProcessReadOptions, "onExecutable" | "timeoutMs">) => WindowsProcessPair | null;
41
- env?: NodeJS.ProcessEnv;
41
+ resolveWindowsSystemDirectory?: () => string;
42
42
  now?: () => number;
43
43
  }
44
44
 
@@ -46,7 +46,10 @@ export function desktopSupervisionPaths(): { pid: string; runtimePort: string };
46
46
  export const procfs: ProcReader;
47
47
  export function processIdentity(pid: number, execute?: DesktopSupervisionDeps["run"], onExecutable?: (path: string) => void):
48
48
  { parent: number; executable: string } | null;
49
- export function windowsPowerShellPath(env?: NodeJS.ProcessEnv): string;
49
+ export function windowsPowerShellPath(resolveSystemDirectory?: () => string): string;
50
+ /** Pure consistency check over loaded-module paths; throws unless exactly one well-formed
51
+ * namesake per KnownDLL shares one parent directory. Exported for tests. */
52
+ export function windowsSystemDirectoryFromSharedObjects(loaded: unknown): string;
50
53
  export function windowsProcessPair(pid: number, execute?: DesktopSupervisionDeps["run"], options?: WindowsProcessReadOptions): WindowsProcessPair;
51
54
  export function inspectDesktopSupervision(deps?: DesktopSupervisionDeps): SupervisionEvidence;
52
55
  export function createSupervisionLatch(): { observe(evidence: SupervisionEvidence): boolean };
@@ -1,12 +1,14 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { accessSync, constants, readFileSync, readlinkSync, realpathSync } from "node:fs";
3
+ import { createRequire } from "node:module";
3
4
  import { homedir } from "node:os";
4
5
  import { basename, dirname, join, resolve, win32 } from "node:path";
5
6
 
6
7
  // Node >=18 also imports this module from bin/ocx.mjs; do not import TS or Bun APIs.
7
- function run(command, args, timeout = 750) {
8
+ function run(command, args, timeout = 750, env) {
8
9
  return execFileSync(command, args, {
9
- encoding: "utf8", timeout, maxBuffer: 128 * 1024, stdio: ["ignore", "pipe", "pipe"], windowsHide: true,
10
+ encoding: "utf8", timeout, env, maxBuffer: 128 * 1024,
11
+ stdio: ["ignore", "pipe", "pipe"], windowsHide: true,
10
12
  }).trim();
11
13
  }
12
14
 
@@ -80,22 +82,95 @@ const WINDOWS_ACQUISITION_TIMEOUT_MS = 3_000;
80
82
  const WINDOWS_MIN_ACQUISITION_MS = 250;
81
83
  const WINDOWS_DESKTOP_IMAGE = "opencodex-desktop.exe";
82
84
 
83
- /** Mirrors src/update/npm-invocation.mjs: plain ESM cannot reach the FFI system-directory resolver. */
84
- export function windowsPowerShellPath(env = process.env) {
85
- const root = env.SystemRoot ?? env.windir;
86
- const base = root && /^[A-Za-z]:\\/.test(root.replaceAll("/", "\\")) ? root : "C:\\Windows";
87
- return win32.join(base, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
85
+ /** Bun resolves the system directory via FFI; the Node lane derives it from loaded KnownDLL paths. */
86
+ export function windowsPowerShellPath(resolveSystemDirectory = resolveWindowsSystemDirectory) {
87
+ const system = resolveSystemDirectory();
88
+ return win32.join(system, "WindowsPowerShell", "v1.0", "powershell.exe");
89
+ }
90
+
91
+ const WINDOWS_REPORT_PATH_LIMIT = 260; // Node's module-name buffer is WCHAR[MAX_PATH] (src/debug_utils.cc).
92
+ const WINDOWS_KNOWN_DLLS = ["kernel32.dll", "ntdll.dll"];
93
+
94
+ // A resolved system directory is stable for the process lifetime; only success is
95
+ // memoized, so failures keep the existing retry-on-next-call recovery contract.
96
+ let windowsSystemDirectoryCache = null;
97
+
98
+ function resolveWindowsSystemDirectory() {
99
+ if (process.platform !== "win32") throw new Error("trusted Windows resolver unavailable");
100
+ if (windowsSystemDirectoryCache !== null) return windowsSystemDirectoryCache;
101
+ const directory = process.versions.bun ? resolveWindowsSystemDirectoryViaFfi() : resolveWindowsSystemDirectoryViaSharedObjects();
102
+ return (windowsSystemDirectoryCache = directory);
103
+ }
104
+
105
+ function resolveWindowsSystemDirectoryViaFfi() {
106
+ const { dlopen, ptr } = createRequire(import.meta.url)("bun:ffi");
107
+ const lib = dlopen("kernel32.dll", { GetSystemDirectoryW: { args: ["ptr", "u32"], returns: "u32" } });
108
+ try {
109
+ let size = 260;
110
+ for (let attempt = 0; attempt < 4; attempt++) {
111
+ const buffer = new Uint16Array(size);
112
+ const written = lib.symbols.GetSystemDirectoryW(ptr(buffer.buffer), size);
113
+ if (written === 0) throw new Error("GetSystemDirectoryW failed");
114
+ if (written >= size) { size = written + 1; continue; }
115
+ return String.fromCharCode(...buffer.subarray(0, written)).replace(/[/\\]+$/, "");
116
+ }
117
+ throw new Error("Windows system directory is too long");
118
+ } finally {
119
+ lib.close();
120
+ }
121
+ }
122
+
123
+ /** Pure consistency check over loaded-module paths — no env, no filesystem. Exported for tests. */
124
+ export function windowsSystemDirectoryFromSharedObjects(loaded) {
125
+ if (!Array.isArray(loaded)) throw new Error("trusted Windows resolver unavailable");
126
+ const parents = new Map(); // lowercased -> first-seen casing (kernel32 is processed first)
127
+ for (const known of WINDOWS_KNOWN_DLLS) {
128
+ // Collect every raw namesake first: a malformed or truncated namesake must
129
+ // cause rejection, not disappear behind a format filter.
130
+ const namesakes = loaded.filter(path => typeof path === "string" && win32.basename(path).toLowerCase() === known);
131
+ for (const candidate of namesakes) {
132
+ if (candidate.length >= WINDOWS_REPORT_PATH_LIMIT || !/^[A-Za-z]:[\\/]/.test(candidate))
133
+ throw new Error("trusted Windows resolver unavailable");
134
+ }
135
+ if (namesakes.length !== 1) throw new Error("trusted Windows resolver unavailable");
136
+ const parent = win32.dirname(win32.normalize(namesakes[0]));
137
+ if (!parents.has(parent.toLowerCase())) parents.set(parent.toLowerCase(), parent);
138
+ }
139
+ if (parents.size !== 1) throw new Error("trusted Windows resolver unavailable");
140
+ return [...parents.values()][0];
141
+ }
142
+
143
+ // The report object carries environment secrets: read .sharedObjects only — never
144
+ // log, serialize, store or pass it on. Existence checks stay outside the pure validator.
145
+ // An unavailable or ambiguous report stays the bounded unknown residual.
146
+ function resolveWindowsSystemDirectoryViaSharedObjects() {
147
+ const loaded = process.report?.getReport?.()?.sharedObjects;
148
+ const directory = windowsSystemDirectoryFromSharedObjects(loaded);
149
+ for (const required of [...WINDOWS_KNOWN_DLLS, win32.join("WindowsPowerShell", "v1.0", "powershell.exe")]) {
150
+ try { accessSync(win32.join(directory, required), constants.F_OK); }
151
+ catch { throw new Error("trusted Windows resolver unavailable"); }
152
+ }
153
+ return directory;
154
+ }
155
+
156
+ function windowsPowerShellEnv(systemDirectory) {
157
+ const root = win32.dirname(systemDirectory);
158
+ return { SystemRoot: root, WINDIR: root, PATH: systemDirectory, PATHEXT: ".COM;.EXE;.BAT;.CMD" };
88
159
  }
89
160
 
90
161
  function windowsProcessScript(pid) {
91
162
  // pid is a validated safe integer; it only ever reaches a numeric WQL filter.
92
163
  return [
93
164
  "$ErrorActionPreference='Stop'",
165
+ "$PSModuleAutoLoadingPreference='None'",
166
+ // Utility loads first: the CimCmdlets manifest needs Set-Alias, which autoload 'None' cannot supply.
167
+ "Import-Module ([IO.Path]::Combine($PSHOME,'Modules','Microsoft.PowerShell.Utility','Microsoft.PowerShell.Utility.psd1')) -Force",
168
+ "Import-Module ([IO.Path]::Combine($PSHOME,'Modules','CimCmdlets','CimCmdlets.psd1')) -Force",
94
169
  "function Row($p) { if ($null -eq $p) { return $null }; [ordered]@{ pid=[string]$p.ProcessId; parent=[string]$p.ParentProcessId; exe=$p.ExecutablePath; session=[string]$p.SessionId; created=$(if ($p.CreationDate) { [string]$p.CreationDate.ToUniversalTime().Ticks } else { $null }) } }",
95
- `$c=Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}'`,
170
+ `$c=CimCmdlets\\Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}'`,
96
171
  "$p=$null",
97
- "if ($c -and [uint32]$c.ParentProcessId -gt 0) { $p=Get-CimInstance -ClassName Win32_Process -Filter ('ProcessId=' + [uint32]$c.ParentProcessId) }",
98
- "[ordered]@{ child=(Row $c); parent=(Row $p) } | ConvertTo-Json -Compress",
172
+ "if ($c -and [uint32]$c.ParentProcessId -gt 0) { $p=CimCmdlets\\Get-CimInstance -ClassName Win32_Process -Filter ('ProcessId=' + [uint32]$c.ParentProcessId) }",
173
+ "[ordered]@{ child=(Row $c); parent=(Row $p) } | Microsoft.PowerShell.Utility\\ConvertTo-Json -Compress",
99
174
  ].join("; ");
100
175
  }
101
176
 
@@ -120,9 +195,11 @@ function windowsRow(row) {
120
195
  /** One bounded Win32_Process read of a process and its parent. */
121
196
  export function windowsProcessPair(pid, execute = run, options = {}) {
122
197
  if (!validPid(pid)) throw new Error("invalid pid");
123
- const output = execute(windowsPowerShellPath(options.env), [
198
+ const resolveSystemDirectory = options.resolveSystemDirectory ?? resolveWindowsSystemDirectory;
199
+ const systemDirectory = resolveSystemDirectory();
200
+ const output = execute(windowsPowerShellPath(() => systemDirectory), [
124
201
  "-NoProfile", "-NoLogo", "-NonInteractive", "-Command", windowsProcessScript(pid),
125
- ], options.timeoutMs ?? WINDOWS_ACQUISITION_TIMEOUT_MS);
202
+ ], options.timeoutMs ?? WINDOWS_ACQUISITION_TIMEOUT_MS, windowsPowerShellEnv(systemDirectory));
126
203
  const raw = JSON.parse(output);
127
204
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid process pair");
128
205
  // A Desktop parent seen before a later field fails validation must keep its veto.
@@ -154,7 +231,7 @@ export function inspectDesktopSupervision(deps = {}) {
154
231
  const now = deps.now ?? Date.now;
155
232
  const deadline = now() + WINDOWS_INSPECTION_BUDGET_MS;
156
233
  const readWindowsPair = deps.windowsProcesses
157
- ?? ((pid, options) => windowsProcessPair(pid, execute, { ...options, env: deps.env }));
234
+ ?? ((pid, options) => windowsProcessPair(pid, execute, { ...options, resolveSystemDirectory: deps.resolveWindowsSystemDirectory }));
158
235
  function identity(pid, parent = false) {
159
236
  if (platform === "darwin") return processIdentity(pid, execute, parent ? seen : undefined);
160
237
  const executable = proc.exe(pid);
@@ -174,6 +174,18 @@ export function ownershipMutationLeaseStatusLine(statePaths, options = {}) {
174
174
  + `opencodex waits for it to start or change service state, and ${RECLAIM_HINT}.`;
175
175
  }
176
176
 
177
+ function createLeaseHandle(path, generation, token, options) {
178
+ let released = false;
179
+ return {
180
+ token,
181
+ release: () => {
182
+ if (released) return;
183
+ released = true;
184
+ release(path, generation, options);
185
+ },
186
+ };
187
+ }
188
+
177
189
  function reclaim(path, now, alive) {
178
190
  const observed = readOwner(path);
179
191
  const incomplete = observed ? null : readIncompleteOwner(path);
@@ -201,7 +213,7 @@ export function acquireOwnershipMutationLease(
201
213
  const nested = held.get(path);
202
214
  if (nested) {
203
215
  nested.depth += 1;
204
- return { token: nested.snapshot.record.token, release: () => release(path, options) };
216
+ return createLeaseHandle(path, nested.generation, nested.snapshot.record.token, options);
205
217
  }
206
218
  const now = options.now ?? Date.now;
207
219
  const alive = options.processAlive ?? processAlive;
@@ -213,8 +225,9 @@ export function acquireOwnershipMutationLease(
213
225
  if (owner?.record.token === joinToken && alive(owner.record.pid)) {
214
226
  delegatedTokens.set(path, joinToken);
215
227
  if (envJoinToken === joinToken) delete process.env[OWNERSHIP_MUTATION_LEASE_TOKEN_ENV];
216
- held.set(path, { depth: 1, snapshot: owner, delegated: true });
217
- return { token: joinToken, release: () => release(path, options) };
228
+ const generation = {};
229
+ held.set(path, { depth: 1, snapshot: owner, delegated: true, generation });
230
+ return createLeaseHandle(path, generation, joinToken, options);
218
231
  }
219
232
  delegatedTokens.delete(path);
220
233
  if (envJoinToken === joinToken) delete process.env[OWNERSHIP_MUTATION_LEASE_TOKEN_ENV];
@@ -238,8 +251,9 @@ export function acquireOwnershipMutationLease(
238
251
  descriptor = null;
239
252
  const snapshot = readOwner(path);
240
253
  if (!snapshot || snapshot.record.token !== record.token) throw new Error("ownership mutation lease could not be verified");
241
- held.set(path, { depth: 1, snapshot, delegated: false });
242
- return { token: record.token, release: () => release(path, options) };
254
+ const generation = {};
255
+ held.set(path, { depth: 1, snapshot, delegated: false, generation });
256
+ return createLeaseHandle(path, generation, record.token, options);
243
257
  } catch (error) {
244
258
  if (descriptor !== null) { try { closeSync(descriptor); } catch { /* stale recovery owns uncertain cleanup */ } }
245
259
  if (madeDirectory) {
@@ -261,9 +275,9 @@ export function acquireOwnershipMutationLease(
261
275
  }
262
276
  }
263
277
 
264
- function release(path, options) {
278
+ function release(path, generation, options) {
265
279
  const currentHeld = held.get(path);
266
- if (!currentHeld) return;
280
+ if (!currentHeld || currentHeld.generation !== generation) return;
267
281
  currentHeld.depth -= 1;
268
282
  if (currentHeld.depth > 0) return;
269
283
  held.delete(path);
@@ -234,9 +234,9 @@ export interface OcxClaudeCodeConfig {
234
234
  /** Optional roster-style model forced on subagents at the next routed Claude Code launch. */
235
235
  subagentModelForce?: string;
236
236
  /** Claude-originated web-search override. Unset fields inherit the global sidecar settings. */
237
- webSearchSidecar?: { backend?: "openai" | "anthropic" | "xai" | "gemini" | "exa"; model?: string; anthropicInstance?: AnthropicInstanceId };
237
+ webSearchSidecar?: { enabled?: boolean; backend?: "openai" | "anthropic" | "xai" | "gemini" | "exa"; model?: string; anthropicInstance?: AnthropicInstanceId };
238
238
  /** Claude-originated vision override. Unset fields inherit the global sidecar settings. */
239
- visionSidecar?: { backend?: "openai" | "anthropic" | "routed"; model?: string; anthropicInstance?: AnthropicInstanceId };
239
+ visionSidecar?: { enabled?: boolean; backend?: "openai" | "anthropic" | "routed"; model?: string; anthropicInstance?: AnthropicInstanceId };
240
240
  /** Persisted Claude Desktop four-family routing profile. */
241
241
  desktopProfile?: OcxClaudeDesktopProfile;
242
242
  /**
@@ -1435,6 +1435,12 @@ export interface OcxComboConfig {
1435
1435
  cooldownMs?: number;
1436
1436
  /** Maximum wait for an eligible target cooldown to expire before failing closed. Default 0; range 0..600000, per selection attempt. */
1437
1437
  waitForCooldownMs?: number;
1438
+ /** Opt-in retry pass when all otherwise eligible targets are cooling. Disabled by default. */
1439
+ cooldownReprobe?: {
1440
+ enabled: boolean;
1441
+ /** Minimum interval between recovery passes, in milliseconds. Default 300000; range 1000..86400000. */
1442
+ intervalMs?: number;
1443
+ };
1438
1444
  /**
1439
1445
  * `before-last-resort` defers targets marked `lastResort` while a normal
1440
1446
  * target is merely cooling and that cooldown can be waited out inside