@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -18,7 +18,8 @@ import {
18
18
  withClientLifecycle, withClientLifecycleSync,
19
19
  type ClientLifecycleHeld, type ClientLifecycleLockDeps,
20
20
  } from "./lifecycle-lock";
21
- import { invalidateCodexModelsCache } from "../codex/catalog/sync";
21
+ import { invalidateCodexModelsCache, invalidateCodexModelsCacheWithPermit } from "../codex/catalog/sync";
22
+ import { withCatalogWriteSerialization } from "../codex/catalog-write-serialization";
22
23
  import {
23
24
  injectCodexConfig,
24
25
  currentExternalCodexModelProvider,
@@ -30,7 +31,7 @@ import {
30
31
  journalOwner,
31
32
  restoreJournalState,
32
33
  } from "../codex/journal";
33
- import { DEFAULT_CATALOG_PATH } from "../codex/paths";
34
+ import { DEFAULT_CATALOG_PATH, getCodexHome } from "../codex/paths";
34
35
  import {
35
36
  readServiceApiTokenState,
36
37
  readTokenBackupState,
@@ -95,6 +96,7 @@ import {
95
96
  import { hubStateCachePath } from "./hub-state";
96
97
  import { ClientLinkStateError, clearClientLinkState, readClientLinkState } from "./link-state";
97
98
  import { isLinkPort } from "../link/ports";
99
+ import { clientSyncRuntimeGuard, ClientSyncRuntimeError } from "./sync-runtime";
98
100
 
99
101
  class RotationRecoveryRequiredError extends Error {
100
102
  constructor(message: string, options?: ErrorOptions) {
@@ -901,7 +903,15 @@ async function syncConnectedClientUnlocked(
901
903
  if (state.kind !== "connected" || state.value.pendingOperation) throw new Error("client_sync_unavailable");
902
904
  const token = readServiceApiTokenState();
903
905
  if (token.kind !== "present" || token.fingerprint !== state.value.tokenFingerprint) throw new Error("client_token_changed");
904
- return { connection: state.value, token };
906
+ let assertRuntimeCurrent = () => {};
907
+ try { if (isLinkConnection(state.value)) assertRuntimeCurrent = clientSyncRuntimeGuard(); }
908
+ catch (error) {
909
+ if (options.expect && error instanceof ClientSyncRuntimeError && error.code === "client_runtime_stopping") {
910
+ throw new ClientSyncExpectationError(options.expect, "pending_operation");
911
+ }
912
+ throw error;
913
+ }
914
+ return { connection: state.value, token, assertRuntimeCurrent };
905
915
  }), deps.lifecycleLockDeps);
906
916
  let downloaded: Awaited<ReturnType<typeof downloadClientCatalog>> | undefined;
907
917
  let stale = false;
@@ -918,6 +928,7 @@ async function syncConnectedClientUnlocked(
918
928
  // they were, which is the known-good state.
919
929
  if (downloaded) assertClientCatalogCompatible(downloaded.body, deps.catalogCompatibility);
920
930
  const next = withClientLifecycleSync(() => withConfigMutationLockSync(() => {
931
+ initial.assertRuntimeCurrent();
921
932
  assertClientConnectionUnchanged(initial.connection);
922
933
  const token = readServiceApiTokenState();
923
934
  if (token.kind !== "present" || token.fingerprint !== initial.token.fingerprint) throw new Error("client_token_changed");
@@ -933,10 +944,12 @@ async function syncConnectedClientUnlocked(
933
944
  }), deps.lifecycleLockDeps);
934
945
  // Read-only: injection invokes this while N/C are held. Acquiring L here would invert C→L.
935
946
  const beforeClientWrite = () => {
947
+ initial.assertRuntimeCurrent();
936
948
  assertClientConnectionUnchanged(next);
937
949
  const token = readServiceApiTokenState();
938
950
  if (next.pendingOperation || token.kind !== "present" || token.fingerprint !== next.tokenFingerprint) throw new Error("client_token_changed");
939
951
  };
952
+ const withClientWrite = <T>(write: () => T): T => withConfigMutationLockSync(() => { beforeClientWrite(); return write(); });
940
953
  let injected = false;
941
954
  let homeSettings: HomeCodexSettingsSource | undefined;
942
955
  let appliedRecord: HomeCodexSettingsRecord | undefined;
@@ -945,12 +958,15 @@ async function syncConnectedClientUnlocked(
945
958
  let config = loadConfig();
946
959
  // #6957: a link Child applies the Home's OpenCodex-owned Codex settings with the catalog.
947
960
  if (isLinkConnection(next)) {
948
- homeSettings = await resolveHomeCodexSettings(next, initial.token.token, deps.linkHome);
961
+ homeSettings = await resolveHomeCodexSettings(next, initial.token.token, { ...deps.linkHome, withWriteGuard: withClientWrite });
949
962
  if (homeSettings.source !== "local") config = overlayHomeCodexSettings(config, homeSettings.document.settings);
950
963
  // About to write different settings: until their record commits, report no applied digest
951
964
  // rather than the previous one (OCX-6). A failed injection then reads "unknown", never a
952
965
  // digest of values Codex no longer has or never got.
953
- if (homeSettings.source === "home" && next.link) withdrawChangingHomeCodexSettingsRecord(next.link.linkId, homeSettings.document);
966
+ if (homeSettings.source === "home" && next.link) {
967
+ const { linkId } = next.link, { document } = homeSettings;
968
+ withClientWrite(() => withdrawChangingHomeCodexSettingsRecord(linkId, document));
969
+ }
954
970
  }
955
971
  const result = await injectCodexConfig(config.port, { ...config, syncResumeHistory: false }, {
956
972
  routingTarget: routingTarget(next.serverUrl, isLinkConnection(next) ? config.port : undefined, config), catalogPath: DEFAULT_CATALOG_PATH,
@@ -962,23 +978,24 @@ async function syncConnectedClientUnlocked(
962
978
  const linkId = next.link.linkId;
963
979
  const settings = homeSettings;
964
980
  try {
965
- appliedRecord = withClientLifecycleSync(() => {
966
- beforeClientWrite();
967
- return recordHomeCodexSettings(linkId, settings, deps.now) ?? readHomeCodexSettingsRecord(linkId) ?? undefined;
968
- }, deps.lifecycleLockDeps);
981
+ appliedRecord = withClientLifecycleSync(() => withClientWrite(() =>
982
+ recordHomeCodexSettings(linkId, settings, deps.now) ?? readHomeCodexSettingsRecord(linkId) ?? undefined), deps.lifecycleLockDeps);
969
983
  } catch (error) {
970
984
  // An ownership change is not a disk problem: report it as itself.
971
- if (error instanceof Error && (error.message === "client_token_changed" || error.message === "client_connection_changed")) throw error;
985
+ if (error instanceof ClientSyncRuntimeError || (error instanceof Error && (error.message === "client_token_changed" || error.message === "client_connection_changed"))) throw error;
972
986
  // The injection committed, so the cache refresh below still runs; the caller reports this.
973
- try { clearHomeCodexSettingsRecord(); } catch { /* status already reads no recorded apply or reports the write */ }
987
+ try { withClientWrite(clearHomeCodexSettingsRecord); } catch { /* status already reads no recorded apply or reports the write */ }
974
988
  applyRecordFailed = true;
975
989
  }
976
990
  }
977
991
  }
978
992
  const cacheSynced = withClientLifecycleSync(() => {
979
- beforeClientWrite();
980
- // Cache invalidation acquires K itself (N -> K -> C); never call it while C is held.
981
- return invalidateCodexModelsCache({ allowWhenDesiredDisabled: true });
993
+ // Acquire K before the guarded C commit; never acquire K from inside C.
994
+ const owningHome = getCodexHome();
995
+ const result = withCatalogWriteSerialization(owningHome, permit => withClientWrite(() =>
996
+ invalidateCodexModelsCacheWithPermit(permit, owningHome, { allowWhenDesiredDisabled: true })),
997
+ { intent: "cache", writer: "cache-invalidate" });
998
+ return result.kind === "completed" && result.value;
982
999
  }, deps.lifecycleLockDeps);
983
1000
  return {
984
1001
  catalogWritten: downloaded !== undefined, cacheSynced, injected, stale,
@@ -299,7 +299,7 @@ export type HomeCodexSettingsSource =
299
299
  export async function resolveHomeCodexSettings(
300
300
  connection: LinkHomeConnection,
301
301
  admissionKey: string,
302
- deps: LinkHomeDeps & { now?: () => Date } = {},
302
+ deps: LinkHomeDeps & { now?: () => Date; withWriteGuard?: <T>(write: () => T) => T } = {},
303
303
  ): Promise<HomeCodexSettingsSource> {
304
304
  const linkId = connection.link?.linkId;
305
305
  if (!linkId) return { source: "local", reason: "not a Remote Link Child" };
@@ -308,7 +308,8 @@ export async function resolveHomeCodexSettings(
308
308
  return { source: "home", document: fetched.document, fetchedAt: (deps.now ?? (() => new Date()))().toISOString() };
309
309
  }
310
310
  if (fetched.kind === "unsupported") {
311
- clearHomeCodexSettingsRecord();
311
+ if (deps.withWriteGuard) deps.withWriteGuard(clearHomeCodexSettingsRecord);
312
+ else clearHomeCodexSettingsRecord();
312
313
  return { source: "local", reason: "the Home does not publish Codex settings; upgrade the Home" };
313
314
  }
314
315
  const cached = readHomeCodexSettingsRecord(linkId);
@@ -324,6 +324,9 @@ async function handleBoundRestart(
324
324
  );
325
325
  if (!authorized) return Response.json({ success: false, error: "restart capability required" }, { status: 401, headers: noStore });
326
326
  const admission = await restart.request();
327
+ if (admission.kind === "stopping") {
328
+ return Response.json({ success: false, error: { code: "runtime_stopping" } }, { status: 409, headers: noStore });
329
+ }
327
330
  if (admission.kind === "supervised") {
328
331
  return Response.json({
329
332
  success: false,
@@ -1,5 +1,6 @@
1
1
  import { withConfigMutationLockSync } from "../config";
2
2
  import { assertNoClientDisconnectPending, pendingClientConnectMayOwnToken, readClientConnectionState } from "./state";
3
+ import type { OcxClientConnectionConfig } from "../types";
3
4
 
4
5
  export type RestoreBoundaryOwnership = "restore" | "hub-owned" | "unproven";
5
6
  export type RestoreOwnershipRefusal = Exclude<RestoreBoundaryOwnership, "restore">;
@@ -21,8 +22,16 @@ export function inspectStopRestoreOwnership(read = readClientConnectionState): R
21
22
  } catch { return "unproven"; }
22
23
  }
23
24
 
25
+ function restoreConnectionSnapshot(connection: OcxClientConnectionConfig) {
26
+ // Normal sync changes these observations, not restoration ownership. All other
27
+ // fields, including priorCatalog and future connection fields, remain guarded.
28
+ const { catalogFingerprint: _fingerprint, catalogSyncedAt: _syncedAt, ...snapshot } = connection;
29
+ return snapshot;
30
+ }
31
+
24
32
  /** C is reentrant inside N/C; this never acquires L or N. No lease crosses an await. */
25
- export function stopRestoreWriteGuard() {
33
+ export function stopRestoreWriteGuard(expectedConnection?: OcxClientConnectionConfig) {
34
+ const expected = expectedConnection && restoreConnectionSnapshot(structuredClone(expectedConnection));
26
35
  let boundary: RestoreBoundaryOwnership = "restore";
27
36
  return {
28
37
  boundary: () => boundary,
@@ -32,6 +41,15 @@ export function stopRestoreWriteGuard() {
32
41
  return withConfigMutationLockSync(() => {
33
42
  entered = true;
34
43
  if (boundary === "restore") boundary = inspectStopRestoreOwnership();
44
+ if (boundary === "restore" && expected) {
45
+ try {
46
+ if (expected.pendingOperation) throw new Error("client_rotation_pending");
47
+ const current = readClientConnectionState();
48
+ if (current.kind !== "connected" || !Bun.deepEquals(restoreConnectionSnapshot(current.value), expected, true)) {
49
+ throw new Error("client_connection_changed");
50
+ }
51
+ } catch { boundary = "unproven"; }
52
+ }
35
53
  if (boundary !== "restore") throw new StopRestoreOwnershipError(boundary);
36
54
  return write();
37
55
  });
@@ -30,9 +30,12 @@ export type ClientRestartSupervisor = "service" | "desktop";
30
30
 
31
31
  export type ClientRestartAdmission =
32
32
  | { kind: "accepted"; alreadyRestarting: boolean }
33
+ | { kind: "stopping" }
33
34
  | { kind: "supervised"; supervisor: ClientRestartSupervisor };
34
35
 
35
36
  export interface ClientRestartIo {
37
+ /** A signal shutdown has claimed this runtime; it cannot admit a replacement. */
38
+ stopping?: () => boolean;
36
39
  /** Which supervisor owns this process, or null when it starts its own replacement. */
37
40
  supervisor(): Promise<ClientRestartSupervisor | null>;
38
41
  /** Stop the tunnel supervisor and the listener, giving in-flight requests up to `drainMs`. */
@@ -41,7 +44,7 @@ export interface ClientRestartIo {
41
44
  spawnReplacement(deadlineAt: number): Promise<void>;
42
45
  /** Serve again on this process: listener, fresh tunnel supervisor, records. */
43
46
  resume(): Promise<void>;
44
- exitProcess(code: number): void;
47
+ exitProcess(code: number): void | Promise<void>;
45
48
  now?: () => number;
46
49
  sleep?: (ms: number) => Promise<void>;
47
50
  warn?: (message: string) => void;
@@ -49,7 +52,9 @@ export interface ClientRestartIo {
49
52
 
50
53
  export interface ClientRestartController {
51
54
  request(): Promise<ClientRestartAdmission>;
52
- /** Settles when the restart in flight (if any) has finished or rolled back. Tests only. */
55
+ /** Only an accepted flight owns routing; a supervisor check does not. */
56
+ hasHandoff(): boolean;
57
+ /** Join the accepted flight before signal teardown; may reject on a failed exit callback. */
53
58
  settled(): Promise<void>;
54
59
  }
55
60
 
@@ -81,16 +86,19 @@ export function createClientRestartController(io: ClientRestartIo): ClientRestar
81
86
  await io.resume();
82
87
  } catch (resumeError) {
83
88
  warn(`[client] restart: this runtime could not serve again (${failureCode(resumeError)}); run 'ocx start'`);
84
- io.exitProcess(1);
89
+ await io.exitProcess(1);
85
90
  }
86
91
  return;
87
92
  }
88
- io.exitProcess(0);
93
+ await io.exitProcess(0);
89
94
  };
90
95
 
91
96
  return {
97
+ hasHandoff: () => flight !== null,
92
98
  async request() {
99
+ if (io.stopping?.()) return { kind: "stopping" };
93
100
  const supervisor = await io.supervisor();
101
+ if (io.stopping?.()) return { kind: "stopping" };
94
102
  if (supervisor) return { kind: "supervised", supervisor };
95
103
  if (flight) return { kind: "accepted", alreadyRestarting: true };
96
104
  flight = run(now()).finally(() => { flight = null; });
@@ -5,6 +5,7 @@ import { siblingRuntimeField, withSiblingMarker } from "../codex/sibling-start";
5
5
  import { issueSiblingHandoff } from "../codex/sibling-handoff";
6
6
  import { loadConfig } from "../config";
7
7
  import { removePid, removeRuntimePort, writePid, writeRuntimePort, type RuntimePortState } from "../config/process-state";
8
+ import { currentServingCommand } from "../config/serving-runtimes";
8
9
  import { installCrashGuards } from "../lib/crash-guard";
9
10
  import { observeLocalCredentials } from "../local-credentials/runtime-observation";
10
11
  import { verifiedHomeConnection } from "./link-connection";
@@ -31,12 +32,17 @@ import { isLinkConnection, readClientConnectionState } from "./state";
31
32
  import { withClientLifecycleSync } from "./lifecycle-lock";
32
33
  import { clientRestartRollbackAction, clientRestartSupervisor, createClientRestartController, type ClientRestartController } from "./runtime-restart";
33
34
  import { createLinkParityReporter, type LinkParityReporter } from "./link-parity-reporter";
35
+ import { restoreLinkClientRouting } from "./stop-routing";
36
+ import { markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime";
34
37
 
35
38
  let activeServer: Server<unknown> | null = null;
36
39
  let activePort: number | null = null;
37
40
  let activeSupervisor: ClientLinkSupervisor | null = null;
38
41
  let activeReporter: LinkParityReporter | null = null;
39
42
  let recycleScheduled = false;
43
+ let recycleTimer: ReturnType<typeof setTimeout> | undefined;
44
+ let recycleFlight: Promise<void> | null = null;
45
+ let clientStopping = false;
40
46
 
41
47
  /**
42
48
  * When this runtime's process started (OCX-6, P5): what `/healthz` reports as `startedAt` and the
@@ -94,7 +100,9 @@ export function clientRuntimeRecord(
94
100
  port: number,
95
101
  attestationSecret: string = createLocalAttestationSecret(),
96
102
  ): RuntimePortState {
97
- return { pid, port, hostname: "127.0.0.1", attestationSecret, ...siblingRuntimeField() };
103
+ let command: string[] | undefined;
104
+ try { command = currentServingCommand(); } catch { /* no reliable relaunch identity; update admission fails closed */ }
105
+ return { pid, port, hostname: "127.0.0.1", attestationSecret, ...(command ? { command } : {}), ...siblingRuntimeField(), ...(clientStopping ? { clientStopping: true as const } : {}) };
98
106
  }
99
107
 
100
108
  export function standaloneRecycleEnv(
@@ -123,12 +131,15 @@ export function standaloneRecycleEnv(
123
131
  }
124
132
 
125
133
  export function scheduleStandaloneRecycle(disconnectedTokenFingerprint: string): void {
126
- if (recycleScheduled) return;
134
+ if (recycleScheduled || clientStopping) return;
127
135
  recycleScheduled = true;
128
- const timer = setTimeout(() => {
129
- void recycleStandalone(disconnectedTokenFingerprint);
136
+ recycleTimer = setTimeout(() => {
137
+ recycleTimer = undefined;
138
+ if (clientStopping) return;
139
+ recycleFlight = recycleStandalone(disconnectedTokenFingerprint).finally(() => { recycleFlight = null; });
140
+ void recycleFlight.catch(error => { if (!clientStopping) throw error; });
130
141
  }, 50);
131
- if (typeof timer === "object" && "unref" in timer) timer.unref();
142
+ if (typeof recycleTimer === "object" && "unref" in recycleTimer) recycleTimer.unref();
132
143
  }
133
144
 
134
145
  function configuredTcpPort(): number | undefined {
@@ -418,7 +429,9 @@ export async function startClientRuntime(
418
429
  try { await server.stop(true); } catch { /* already closed */ }
419
430
  };
420
431
 
432
+ let shuttingDown = false;
421
433
  const restartController: ClientRestartController = createClientRestartController({
434
+ stopping: () => shuttingDown,
422
435
  supervisor: io.restartSupervisor ?? clientRestartSupervisor,
423
436
  stop: stopServing,
424
437
  spawnReplacement: async deadlineAt => {
@@ -442,8 +455,8 @@ export async function startClientRuntime(
442
455
  }
443
456
  },
444
457
  exitProcess: async code => {
445
- await flushLinkDiagnostics();
446
- process.exit(code);
458
+ try { await flushLinkDiagnostics(); }
459
+ finally { process.exit(code); }
447
460
  },
448
461
  });
449
462
 
@@ -452,11 +465,24 @@ export async function startClientRuntime(
452
465
  await serve();
453
466
  options.afterPublish?.();
454
467
 
455
- let shuttingDown = false;
456
468
  const shutdown = (signal?: NodeJS.Signals) => {
457
469
  if (shuttingDown) return;
458
470
  shuttingDown = true;
471
+ clientStopping = true;
472
+ if (recycleTimer) { clearTimeout(recycleTimer); recycleTimer = undefined; }
473
+ const fenceSync = () => {
474
+ if (!linkMode) return true;
475
+ try { markClientRuntimeStopping({ pid: process.pid, port: servedPort, attestationSecret }); return true; }
476
+ catch { return false; }
477
+ };
478
+ let syncFenced = fenceSync();
459
479
  void (async () => {
480
+ // An accepted restart owns its replacement and rollback. A successful handoff exits
481
+ // inside that flight; a rollback finishes before this signal tears the runtime down.
482
+ if (restartController.hasHandoff()) await restartController.settled().catch(() => {});
483
+ if (recycleFlight) await recycleFlight.catch(() => {});
484
+ // A rollback may have republished its runtime record while shutdown joined it.
485
+ syncFenced = !linkMode || await markClientRuntimeStoppingWithRetry({ pid: process.pid, port: servedPort, attestationSecret });
460
486
  credentialObservation?.stop();
461
487
  credentialObservation = null;
462
488
  activeReporter?.stop();
@@ -467,15 +493,18 @@ export async function startClientRuntime(
467
493
  console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`);
468
494
  }
469
495
  activeSupervisor = null;
496
+ const restored = linkMode ? restoreLinkClientRouting(state.value, { syncFenced }) : null;
497
+ if (restored && !restored.success) console.error(`[client] ${restored.message}`);
470
498
  try {
471
499
  activeServer?.stop(true);
472
500
  } catch (error) {
473
501
  console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`);
474
502
  } finally {
475
- cleanup();
476
- await flushLinkDiagnostics();
503
+ // Keep stopping admission visible through the last await. Cleanup and exit are adjacent.
504
+ try { await flushLinkDiagnostics(); } finally { cleanup(); }
477
505
  // launchd relaunches only unsuccessful exits; an external signal must still count.
478
- process.exit(handledSignalExitCode(signal));
506
+ if (restored?.success === false) process.exit(1);
507
+ else process.exit(handledSignalExitCode(signal));
479
508
  }
480
509
  })();
481
510
  };
@@ -0,0 +1,62 @@
1
+ import { existsSync } from "node:fs";
2
+ import { restoreNativeCodex } from "../codex/inject";
3
+ import { hasInjectedCodexRouting } from "../codex/injected-marker";
4
+ import { readBoundedCodexConfig } from "../codex/inject/bounded-config-reader";
5
+ import { journalOwner, JOURNAL_PATH } from "../codex/journal";
6
+ import { CODEX_CONFIG_PATH } from "../codex/paths";
7
+ import { siblingOfLivePort, siblingSkipMessage } from "../codex/sibling-start";
8
+ import type { OcxClientConnectionConfig } from "../types";
9
+ import { pendingTeardownOutstanding } from "../config/pending-teardown";
10
+ import { stripGrokConfig } from "../grok/inject";
11
+ import { isDesktopSupervised } from "../lib/system-restart-contract";
12
+ import { serviceEnvironmentOwnedHere } from "../service/guards";
13
+ import { stopRestoreWriteGuard } from "./restore-ownership";
14
+ import { isLinkConnection } from "./state";
15
+
16
+ export type LinkRoutingRestoreResult = { success: boolean; restored: boolean; message: string };
17
+
18
+ const resumeGuidance = "After starting the Child again, run `ocx sync --restart-codex` to restore its Home routing.";
19
+ const refusal = (reason: string): LinkRoutingRestoreResult => ({
20
+ success: false, restored: false,
21
+ message: `Link Child Codex routing restore refused: ${reason}. No further writes; inspect remaining recovery evidence.`,
22
+ });
23
+
24
+ /** Unsupervised signal cleanup; explicit parent stop and restart retain their own restoration. */
25
+ export function restoreLinkClientRouting(expected: OcxClientConnectionConfig, options: { syncFenced: boolean }): LinkRoutingRestoreResult {
26
+ if (siblingOfLivePort() !== null) return { success: true, restored: false, message: siblingSkipMessage() };
27
+ if (!isLinkConnection(expected)) {
28
+ return { success: true, restored: false, message: "Hub connection-owned integrations preserved." };
29
+ }
30
+ const preserve = () => process.env.OCX_SERVICE === "1" || isDesktopSupervised()
31
+ || pendingTeardownOutstanding();
32
+ if (preserve()) return { success: true, restored: false, message: "Supervised restart or pending teardown owns the client integrations." };
33
+ if (options?.syncFenced !== true) return refusal("the runtime sync fence could not be verified");
34
+ const guard = stopRestoreWriteGuard(expected);
35
+ const withWriteGuard = <T>(write: () => T): T => guard.run(() => {
36
+ if (preserve()) throw new Error("restart or teardown ownership changed");
37
+ const owner = journalOwner({ readOnly: true });
38
+ if (existsSync(JOURNAL_PATH) && (owner?.kind !== "client" || owner.apiKeyId !== expected.apiKeyId)) {
39
+ throw new Error("the Codex journal belongs to another owner or is unverified");
40
+ }
41
+ return write();
42
+ });
43
+ try {
44
+ withWriteGuard(() => {
45
+ const owner = journalOwner({ readOnly: true });
46
+ if (owner === null) {
47
+ const config = readBoundedCodexConfig(CODEX_CONFIG_PATH);
48
+ if (existsSync(JOURNAL_PATH) || (config !== null && hasInjectedCodexRouting(config))) throw new Error("the client journal is missing or unverified");
49
+ }
50
+ });
51
+ const result = restoreNativeCodex({ withWriteGuard });
52
+ if (result.artifacts.config.state === "failed" || result.historyPreflightRefusal) {
53
+ return refusal("native Codex restoration was not authorized or could not complete");
54
+ }
55
+ const grok = serviceEnvironmentOwnedHere() ? withWriteGuard(() => stripGrokConfig()) : { ok: true, changed: false };
56
+ if (!result.success || !grok.ok) return refusal("native Codex or managed Grok restoration did not complete");
57
+ return { success: true, restored: result.artifacts.config.changed || result.artifacts.catalog.changed || grok.changed,
58
+ message: `Link Child native Codex and managed Grok restored; connection credentials preserved. ${resumeGuidance}` };
59
+ } catch (error) {
60
+ return refusal(error instanceof Error ? error.message : "restoration failed");
61
+ }
62
+ }
@@ -0,0 +1,65 @@
1
+ /** Cross-process admission for Link sync while its local runtime shuts down. */
2
+ import { lstatSync } from "node:fs";
3
+ import { ConfigMutationLockError, withConfigMutationLockSync } from "../config";
4
+ import { getRuntimePortPath, isValidRuntimePortState, writeRuntimePort, type RuntimePortState } from "../config/process-state";
5
+ import { readBoundedRegularFileSync } from "../lib/bounded-file-read";
6
+
7
+ export class ClientSyncRuntimeError extends Error {
8
+ constructor(readonly code: "client_runtime_stopping" | "client_runtime_changed" | "client_runtime_unverified") {
9
+ super(`${code}: retry sync after the Child has started; ocx start/stop can reconcile a stale runtime record`);
10
+ }
11
+ }
12
+
13
+ function readSyncRuntime(): RuntimePortState | null {
14
+ const path = getRuntimePortPath();
15
+ try { lstatSync(path); }
16
+ catch (error) {
17
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
18
+ throw new ClientSyncRuntimeError("client_runtime_unverified");
19
+ }
20
+ try {
21
+ const value: unknown = JSON.parse(readBoundedRegularFileSync(path, 16 * 1024).toString("utf8"));
22
+ if (!isValidRuntimePortState(value)) throw new Error("invalid runtime record");
23
+ return value;
24
+ } catch { throw new ClientSyncRuntimeError("client_runtime_unverified"); }
25
+ }
26
+
27
+ /** Capture and recheck under C. Proven no-runtime sync keeps its existing offline behavior. */
28
+ export function clientSyncRuntimeGuard(): () => void {
29
+ const expected = readSyncRuntime();
30
+ if (expected?.clientStopping) throw new ClientSyncRuntimeError("client_runtime_stopping");
31
+ return () => {
32
+ const current = readSyncRuntime();
33
+ if (current?.clientStopping) throw new ClientSyncRuntimeError("client_runtime_stopping");
34
+ if (!Bun.deepEquals(current, expected, true)) throw new ClientSyncRuntimeError("client_runtime_changed");
35
+ };
36
+ }
37
+
38
+ /** The same C transaction excludes every sync commit; never mark a replacement runtime. */
39
+ export function markClientRuntimeStopping(expected: Required<Pick<RuntimePortState, "pid" | "port" | "attestationSecret">>): void {
40
+ withConfigMutationLockSync(() => {
41
+ const current = readSyncRuntime();
42
+ if (!current || current.pid !== expected.pid || current.port !== expected.port
43
+ || current.attestationSecret !== expected.attestationSecret) {
44
+ throw new ClientSyncRuntimeError("client_runtime_changed");
45
+ }
46
+ if (!current.clientStopping) writeRuntimePort({ ...current, clientStopping: true });
47
+ });
48
+ }
49
+
50
+ /** Yield only for proved SQLite contention; storage/identity failures remain immediate refusals. */
51
+ export async function markClientRuntimeStoppingWithRetry(
52
+ expected: Required<Pick<RuntimePortState, "pid" | "port" | "attestationSecret">>,
53
+ deps: { mark?: () => void; sleep?: (ms: number) => Promise<unknown> } = {},
54
+ ): Promise<boolean> {
55
+ for (let attempt = 0; attempt < 20; attempt += 1) {
56
+ try { (deps.mark ?? (() => markClientRuntimeStopping(expected)))(); return true; }
57
+ catch (error) {
58
+ const cause = error instanceof ConfigMutationLockError ? error.cause : undefined;
59
+ const code = cause && typeof cause === "object" && "code" in cause ? cause.code : undefined;
60
+ if ((code !== "SQLITE_BUSY" && code !== "SQLITE_LOCKED") || attempt === 19) return false;
61
+ await (deps.sleep ?? Bun.sleep)(50);
62
+ }
63
+ }
64
+ return false;
65
+ }
@@ -60,7 +60,7 @@ export { buildRaycastClientConfig, summarizeRaycast, buildRaycastContribution }
60
60
  export { droidHomeDir, droidConfigPath, buildDroidClientConfig, summarizeDroid, buildDroidContribution, droidReasoningModels, droidDefaultsFromOwnedRows, validateDroidReasoningDefaults } from "./config-export/droid";
61
61
  export type { DroidModelEntry, DroidGeneratedConfig } from "./config-export/droid";
62
62
 
63
- import type { OpencodeLaunchEnv, OpencodeCatalogModel, ExportContext, PiModelEntry, ManagedContribution, ManagedFragment, ExportClientId, ExportClientSpec } from "./config-export/contracts";
63
+ import type { ExportModel, OpencodeLaunchEnv, OpencodeCatalogModel, ExportContext, PiModelEntry, ManagedContribution, ManagedFragment, ExportClientId, ExportClientSpec } from "./config-export/contracts";
64
64
  import { OPENCODE_API_KEY_ENV_REF, OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG, OPENCODE_CONFIG_SCHEMA, OPENCODE_PROVIDER_ID, PI_API_DIALECT, LOOPBACK_API_KEY_PLACEHOLDER, HERMES_API_KEY_ENV_REF, OPENCLAW_API_KEY_ENV_REF, OPENCODE_API_KEY_ENV, HERMES_API_KEY_ENV, OPENCLAW_API_KEY_ENV, KILO_API_KEY_ENV } from "./config-export/constants";
65
65
  import { exportModelLabel, authoritativeContextWindow, outputBudgetFor, inputBudgetFor, normalizeExportModels, inputModalitiesForClient, opencodeModelCapabilities, proxyAdmissionHeaders, singleFragment } from "./config-export/model-metadata";
66
66
  import { exportReasoningEfforts, exportDefaultReasoningEffort, legacyReasoningMetadata, type LegacyEffortVariant } from "./config-export/reasoning-metadata";
@@ -974,13 +974,36 @@ export interface KimiProviderBlock {
974
974
  * authoritative context window is omitted from the document entirely rather
975
975
  * than guessed at. Catalog image input becomes `image_in`; other capabilities
976
976
  * are not inferred from routed model names.
977
+ * A declared effort ladder becomes `support_efforts` (limited to Kimi Code's
978
+ * documented levels) plus the `thinking` capability, and a declared default in
979
+ * that ladder becomes `default_effort` (#8095).
977
980
  */
978
981
  export interface KimiModelBlock {
979
982
  provider: string;
980
983
  model: string;
981
984
  max_context_size: number;
982
985
  display_name?: string;
983
- capabilities?: ["image_in"];
986
+ capabilities?: Array<"thinking" | "image_in">;
987
+ support_efforts?: KimiEffort[];
988
+ default_effort?: KimiEffort;
989
+ }
990
+
991
+ /** Kimi Code's thinking efforts, in its documented order; anything else fails its config validation. */
992
+ const KIMI_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"] as const;
993
+ type KimiEffort = typeof KIMI_EFFORT_ORDER[number];
994
+
995
+ function kimiEfforts(model: ExportModel): { support_efforts?: KimiEffort[]; default_effort?: KimiEffort } {
996
+ // An explicit "no reasoning" declaration outranks any ladder that reached the exporter.
997
+ if (model.supportsReasoning === false || model.supportsReasoningEffort === false) return {};
998
+ const offered = new Set((model.reasoningEfforts ?? [])
999
+ .filter((effort): effort is string => typeof effort === "string")
1000
+ .map(effort => effort.trim().toLowerCase()));
1001
+ const support = KIMI_EFFORT_ORDER.filter(effort => offered.has(effort));
1002
+ if (support.length === 0) return {};
1003
+ const declared = typeof model.defaultReasoningEffort === "string"
1004
+ ? model.defaultReasoningEffort.trim().toLowerCase() : undefined;
1005
+ const fallback = support.find(effort => effort === declared);
1006
+ return { support_efforts: support, ...(fallback ? { default_effort: fallback } : {}) };
984
1007
  }
985
1008
 
986
1009
  export interface KimiGeneratedConfig {
@@ -1176,12 +1199,18 @@ function buildKimiClientConfig(ctx: ExportContext): KimiGeneratedConfig {
1176
1199
  // so a model without an authoritative window is left out rather than
1177
1200
  // shipped with a number we invented.
1178
1201
  if (context === undefined) continue;
1202
+ const efforts = kimiEfforts(model);
1203
+ const capabilities: Array<"thinking" | "image_in"> = [
1204
+ ...(efforts.support_efforts ? ["thinking" as const] : []),
1205
+ ...(model.inputModalities?.includes("image") ? ["image_in" as const] : []),
1206
+ ];
1179
1207
  models[kimiModelAlias(model.namespaced)] = {
1180
1208
  provider: OPENCODE_PROVIDER_ID,
1181
1209
  model: model.namespaced,
1182
1210
  max_context_size: context,
1183
1211
  ...(model.displayName ? { display_name: model.displayName } : {}),
1184
- ...(model.inputModalities?.includes("image") ? { capabilities: ["image_in"] as ["image_in"] } : {}),
1212
+ ...(capabilities.length > 0 ? { capabilities } : {}),
1213
+ ...efforts,
1185
1214
  };
1186
1215
  }
1187
1216
  return {
@@ -92,6 +92,7 @@ function isCredential(value: unknown): value is CodexAccountCredentials {
92
92
  && typeof value.refreshToken === "string"
93
93
  && typeof value.expiresAt === "number"
94
94
  && typeof value.chatgptAccountId === "string"
95
+ && value.chatgptAccountId.trim().length > 0
95
96
  && (hasNoSource || hasCompleteSource);
96
97
  }
97
98
 
@@ -0,0 +1,15 @@
1
+ import type { OcxProviderConfig } from "../types";
2
+
3
+ export type OcxRuntimeProviderConfig = OcxProviderConfig & {
4
+ _codexAccountOverride?: { accessToken: string; chatgptAccountId: string; kind?: "pool" | "main-pool" };
5
+ _codexAccountRequired?: boolean;
6
+ };
7
+
8
+ export function stripCodexRuntimeProviderFields(provider: OcxProviderConfig): OcxProviderConfig {
9
+ const {
10
+ _codexAccountOverride: _override,
11
+ _codexAccountRequired: _required,
12
+ ...safeProvider
13
+ } = provider as OcxRuntimeProviderConfig;
14
+ return safeProvider;
15
+ }