@bitkyc08/opencodex 2.92.0 → 2.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/bin/ocx.mjs +10 -5
  2. package/gui/dist/assets/{App-sUf_8afJ.js → App-CizjBqyk.js} +18 -18
  3. package/gui/dist/assets/{Tray-BSsxznDm.js → Tray-DamiMqcX.js} +1 -1
  4. package/gui/dist/assets/{index-BlFE_VB_.js → index-DQsht3vH.js} +12 -12
  5. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  6. package/gui/dist/assets/{quota-summary-BRlbXgw0.js → quota-summary-BXu4zE8H.js} +1 -1
  7. package/gui/dist/index.html +2 -2
  8. package/package.json +5 -5
  9. package/src/adapters/anthropic.ts +28 -5
  10. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  11. package/src/adapters/coding-agent/profile.ts +54 -16
  12. package/src/adapters/coding-agent/turn.ts +30 -2
  13. package/src/adapters/command-code.ts +114 -7
  14. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  15. package/src/adapters/devin/live-models.ts +4 -0
  16. package/src/adapters/google-wire-compiler.ts +1 -2
  17. package/src/adapters/kiro/reasoning.ts +2 -0
  18. package/src/adapters/kiro-refusal.ts +6 -1
  19. package/src/adapters/kiro-wire.ts +1 -1
  20. package/src/adapters/openai-chat/messages.ts +8 -2
  21. package/src/adapters/openai-chat/passthrough.ts +35 -14
  22. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  23. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  24. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  25. package/src/adapters/openai-chat.ts +7 -8
  26. package/src/adapters/openai-responses/passthrough.ts +7 -4
  27. package/src/adapters/openai-responses/reasoning.ts +13 -0
  28. package/src/adapters/openai-responses/request-strips.ts +1 -1
  29. package/src/adapters/qoder/adapter.ts +129 -8
  30. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  31. package/src/adapters/reasoning-controls.ts +16 -0
  32. package/src/adapters/tool-call-id.ts +1 -3
  33. package/src/bridge/errors.ts +27 -0
  34. package/src/bridge.ts +1 -1
  35. package/src/chat/inbound.ts +4 -1
  36. package/src/chat/outbound.ts +9 -2
  37. package/src/chat/reasoning-details.ts +28 -5
  38. package/src/claude/desktop-first-party.ts +54 -4
  39. package/src/claude/desktop-picker.ts +11 -8
  40. package/src/claude/first-party-settings.ts +3 -1
  41. package/src/claude/inbound.ts +2 -1
  42. package/src/claude/intercept/local-ca.ts +2 -1
  43. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  44. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  45. package/src/claude/intercept/picker-models.ts +6 -3
  46. package/src/claude/intercept/picker-runtime.ts +3 -2
  47. package/src/claude/intercept/runtime.ts +6 -3
  48. package/src/claude/model-info.ts +31 -8
  49. package/src/cli/account-api.ts +11 -0
  50. package/src/cli/capabilities-agents-routing.ts +2 -2
  51. package/src/cli/capabilities-base.ts +7 -1
  52. package/src/cli/capabilities-observe-system.ts +10 -0
  53. package/src/cli/claude-desktop.ts +9 -8
  54. package/src/cli/claude.ts +3 -2
  55. package/src/cli/codex-shim-autorestore.ts +9 -0
  56. package/src/cli/combo-result.ts +7 -0
  57. package/src/cli/combo.ts +18 -0
  58. package/src/cli/cross-home-owner.ts +13 -1
  59. package/src/cli/dispatch.ts +25 -6
  60. package/src/cli/ensure-desired-integrations.ts +8 -6
  61. package/src/cli/export-command.ts +4 -1
  62. package/src/cli/help.ts +2 -1
  63. package/src/cli/index.ts +45 -45
  64. package/src/cli/integration-plan-dto.ts +4 -0
  65. package/src/cli/opencode.ts +20 -9
  66. package/src/cli/registry.ts +6 -4
  67. package/src/cli/root.ts +9 -0
  68. package/src/cli/status.ts +59 -1
  69. package/src/cli/stop-restore.ts +113 -0
  70. package/src/cli/sync-expectation.ts +60 -0
  71. package/src/cli/uninstall-integrations.ts +41 -7
  72. package/src/client/connect.ts +40 -3
  73. package/src/client/link-home.ts +10 -1
  74. package/src/client/machine-api.ts +3 -1
  75. package/src/client/sync-expectation.ts +118 -0
  76. package/src/clients/config-export/agent-clients.ts +96 -0
  77. package/src/clients/config-export/contracts.ts +25 -7
  78. package/src/clients/config-export/qoder.ts +38 -23
  79. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  80. package/src/clients/config-export.ts +12 -0
  81. package/src/clients/lazycodex.ts +7 -2
  82. package/src/clients/reasoning-controls.ts +49 -0
  83. package/src/codex/auth-api/account-identity.ts +14 -0
  84. package/src/codex/auth-api/account-list.ts +29 -2
  85. package/src/codex/auth-api/http.ts +13 -0
  86. package/src/codex/auth-api/main-account-probe.ts +2 -2
  87. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  88. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  89. package/src/codex/auth-context.ts +15 -12
  90. package/src/codex/catalog/build-entries.ts +22 -0
  91. package/src/codex/catalog/configured-tiers.ts +70 -0
  92. package/src/codex/catalog/effort.ts +44 -10
  93. package/src/codex/catalog/gather-capture.ts +1 -0
  94. package/src/codex/catalog/heal-observation.ts +155 -13
  95. package/src/codex/catalog/metadata.ts +6 -0
  96. package/src/codex/catalog/model-hints.ts +60 -11
  97. package/src/codex/catalog/model-visibility.ts +3 -2
  98. package/src/codex/catalog/native-models.ts +18 -3
  99. package/src/codex/catalog/parsing.ts +10 -8
  100. package/src/codex/catalog/pinned-models.ts +2 -1
  101. package/src/codex/catalog/provider-models.ts +4 -5
  102. package/src/codex/catalog/retained-sync.ts +2 -1
  103. package/src/codex/catalog/routed-gather.ts +19 -20
  104. package/src/codex/catalog/write-audit.ts +3 -2
  105. package/src/codex/catalog-self-heal.ts +43 -23
  106. package/src/codex/collision-identity.ts +30 -5
  107. package/src/codex/convergence.ts +4 -3
  108. package/src/codex/data/roster-pinned-models.json +177 -1
  109. package/src/codex/desired-state.ts +6 -1
  110. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  111. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  112. package/src/codex/desktop-compatibility/usage-controller.ts +2 -0
  113. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  114. package/src/codex/inject/config-toml.ts +0 -18
  115. package/src/codex/inject/plan.ts +18 -3
  116. package/src/codex/inject/remove.ts +6 -2
  117. package/src/codex/inject.ts +1 -1
  118. package/src/codex/journal.ts +61 -1
  119. package/src/codex/model-entitlements.ts +1 -1
  120. package/src/codex/native-main-owner.ts +27 -1
  121. package/src/codex/native-profile-store.ts +2 -1
  122. package/src/codex/pool-credit-policy.ts +35 -1
  123. package/src/codex/quota-types.ts +3 -0
  124. package/src/codex/quota.ts +24 -4
  125. package/src/codex/role-auto-assign.ts +6 -2
  126. package/src/codex/subagent-defaults.ts +49 -4
  127. package/src/combos/failover.ts +17 -2
  128. package/src/combos/jev-decision-contract.ts +22 -1
  129. package/src/combos/jev-service-exchange.ts +3 -1
  130. package/src/combos/jev.ts +95 -9
  131. package/src/combos/resolve.ts +45 -1
  132. package/src/combos/types.ts +24 -0
  133. package/src/config/load-degrade.ts +5 -0
  134. package/src/config/paths.ts +19 -3
  135. package/src/config/pending-teardown.ts +22 -1
  136. package/src/config/provider-validation.ts +15 -4
  137. package/src/config/removed-opencode-free.ts +11 -0
  138. package/src/config/schema/leaf-validators.ts +5 -0
  139. package/src/generated/compatibility-version.json +314 -230
  140. package/src/generated/model-metadata.ts +5 -5
  141. package/src/images/loop.ts +16 -2
  142. package/src/integrations/catalog-refresh.ts +1 -1
  143. package/src/integrations/hermes-profiles.ts +251 -0
  144. package/src/integrations/merge.ts +8 -0
  145. package/src/integrations/mutation-plan.ts +19 -4
  146. package/src/integrations/registry.ts +5 -0
  147. package/src/integrations/state.ts +36 -1
  148. package/src/integrations/writer.ts +18 -4
  149. package/src/lib/bun-path-runtime.mjs +2 -1
  150. package/src/lib/errors.ts +62 -0
  151. package/src/lib/eventstream-decoder.ts +81 -37
  152. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  153. package/src/lib/pinned-http.ts +35 -2
  154. package/src/lib/process-control.ts +13 -1
  155. package/src/lib/socks5-fetch.ts +59 -64
  156. package/src/lib/socks5-upload-waiter.ts +50 -0
  157. package/src/lib/sse-decoder.ts +7 -2
  158. package/src/lib/state-store-sweeper.ts +40 -14
  159. package/src/lib/windows-native-principal-worker.ts +14 -0
  160. package/src/lib/windows-native-principal.ts +188 -0
  161. package/src/lib/windows-secret-acl.ts +39 -3
  162. package/src/lib/windows-user-principal.ts +62 -18
  163. package/src/link/ssh-config.ts +35 -3
  164. package/src/providers/account-quota-disk.ts +12 -4
  165. package/src/providers/codebuddy-models.ts +6 -0
  166. package/src/providers/codex-capacity.ts +3 -1
  167. package/src/providers/derive.ts +28 -0
  168. package/src/providers/kiro-models.ts +3 -0
  169. package/src/providers/mimo-thinking.ts +12 -0
  170. package/src/providers/model-rename-fields.ts +1 -0
  171. package/src/providers/model-rename-migration.ts +10 -0
  172. package/src/providers/openai-sidecar-credit.ts +2 -2
  173. package/src/providers/reasoning-capabilities.ts +76 -0
  174. package/src/providers/registry/entries-core.ts +14 -12
  175. package/src/providers/registry/entries-extended.ts +63 -20
  176. package/src/providers/registry/model-ids.ts +2 -0
  177. package/src/providers/registry/model-seeds.ts +93 -28
  178. package/src/providers/registry/types.ts +10 -1
  179. package/src/providers/resolved-model-policy.ts +26 -6
  180. package/src/providers/routed-config.ts +9 -1
  181. package/src/providers/stale-model-roster-migration.ts +44 -7
  182. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  183. package/src/responses/compaction-summary.ts +45 -0
  184. package/src/responses/muse-tool-name-alias.ts +1 -2
  185. package/src/responses/parser.ts +3 -2
  186. package/src/responses/schema.ts +1 -0
  187. package/src/responses/thought-signature-replay.ts +10 -2
  188. package/src/routing/capability.ts +8 -2
  189. package/src/routing/history/ingest.ts +28 -3
  190. package/src/server/auth-cors.ts +3 -2
  191. package/src/server/chat-completions.ts +7 -0
  192. package/src/server/chat-native-eligibility.ts +7 -0
  193. package/src/server/chat-native-reasoning.ts +14 -4
  194. package/src/server/direct-local-http.ts +5 -2
  195. package/src/server/effort-policy.ts +5 -1
  196. package/src/server/index/live-sideband.ts +18 -15
  197. package/src/server/index/serve-options.ts +5 -4
  198. package/src/server/management/agent-settings-routes.ts +27 -15
  199. package/src/server/management/combo-routes.ts +4 -0
  200. package/src/server/management/config-routes.ts +2 -2
  201. package/src/server/management/decision-discovery.ts +12 -2
  202. package/src/server/management/hermes-profile-routes.ts +156 -0
  203. package/src/server/management/integration-routes.ts +85 -24
  204. package/src/server/management/model-routes.ts +2 -2
  205. package/src/server/management/model-row-export-metadata.ts +25 -6
  206. package/src/server/management/model-rows.ts +15 -20
  207. package/src/server/management/native-integration-routes.ts +11 -8
  208. package/src/server/management/route-registry.ts +4 -0
  209. package/src/server/management-api.ts +5 -0
  210. package/src/server/models-capabilities.ts +21 -3
  211. package/src/server/responses/adapter-delivery.ts +11 -1
  212. package/src/server/responses/adapter-dispatch.ts +2 -2
  213. package/src/server/responses/codex-ws-exchange.ts +39 -9
  214. package/src/server/responses/codex-ws-session.ts +38 -4
  215. package/src/server/responses/codex-ws-wire.ts +6 -1
  216. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  217. package/src/server/responses/combo-stream-preflight.ts +8 -1
  218. package/src/server/responses/compact.ts +4 -3
  219. package/src/server/responses/context-overflow.ts +8 -1
  220. package/src/server/responses/core-combo-failure.ts +10 -0
  221. package/src/server/responses/core-combo.ts +23 -15
  222. package/src/server/responses/core-lifetime.ts +3 -0
  223. package/src/server/responses/core-normalize.ts +11 -1
  224. package/src/server/responses/core-options.ts +2 -0
  225. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  226. package/src/server/responses/passthrough-delivery.ts +40 -2
  227. package/src/server/responses/policy-fallback.ts +6 -1
  228. package/src/server/responses/request-compression.ts +12 -7
  229. package/src/server/responses/request-prepare.ts +22 -2
  230. package/src/server/responses/request-sidecar-auth.ts +2 -0
  231. package/src/server/responses/response-effects.ts +22 -10
  232. package/src/server/responses/sidecar-execution.ts +11 -3
  233. package/src/server/stop-teardown.ts +36 -1
  234. package/src/server/ws-bridge.ts +1 -1
  235. package/src/service/desktop-supervision.d.mts +7 -4
  236. package/src/service/desktop-supervision.mjs +90 -13
  237. package/src/service/ownership-mutation-lease.mjs +21 -7
  238. package/src/types/config.ts +8 -2
  239. package/src/types/provider.ts +20 -6
  240. package/src/types/request.ts +10 -0
  241. package/src/types.ts +1 -0
  242. package/src/update/bind-probe.ts +29 -0
  243. package/src/update/job.ts +10 -29
  244. package/src/update/npm-install-job.ps1 +173 -0
  245. package/src/update/npm-install.mjs +70 -0
  246. package/src/update/stop-contract.d.mts +1 -0
  247. package/src/update/stop-contract.mjs +14 -0
  248. package/src/update/stop-decision.d.mts +1 -1
  249. package/src/update/stop-decision.mjs +13 -3
  250. package/src/update/teardown-handover.ts +166 -0
  251. package/src/update/transactional-install.d.mts +14 -3
  252. package/src/update/transactional-install.mjs +33 -7
  253. package/src/usage/expected-prices.ts +64 -31
  254. package/src/usage/timeline.ts +19 -9
  255. package/src/vision/eligibility.ts +15 -5
  256. package/src/vision/plan.ts +2 -2
  257. package/src/web-search/loop.ts +16 -2
  258. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
@@ -2,6 +2,16 @@ import type { Capability } from "./capability-types";
2
2
 
3
3
  /** Verified existing handlers only; local operations never claim management routes. */
4
4
  export const OBSERVE_SYSTEM_CAPABILITIES: readonly Capability[] = [
5
+ {
6
+ command: ["stop"],
7
+ usage: "ocx stop [--json]",
8
+ summary: "Stop the proxy; preserve connected-client integrations, restore native Codex config for standalone owners.",
9
+ routes: [{ method: "GET", path: "/api/stop" }, { method: "POST", path: "/api/stop" }],
10
+ flags: [{ name: "--json", value: "boolean", summary: "Emit one structured stop summary; human output moves to stderr." }],
11
+ mutates: true,
12
+ json: "envelope",
13
+ details: ["Connected clients verify runtime preservation support before stopping; unavailable or unsupported live targets refuse without stopping the service. Proven-stopped clients remain successful when the manager is inactive.", "Siblings and connected clients preserve shared integrations. Standalone owners restore native Codex configuration and remove the managed Grok block.", "JSON uses ocx-stop/1 and retains the same exit codes: 0, 1, 79 (history cleanup incomplete), 80 (teardown deferred)."],
14
+ },
5
15
  {"command": ["logs", "filter"], "summary": "Select a bounded log snapshot with dashboard filters.", "usage": "ocx logs filter [--surface <all|codex|claude|grok>] [--model <id>] [--provider <name>] [--status <all|success|errors>] [--time-window <all|15m|1h|24h>] [--min-tok-per-sec <n>] [--max-tok-per-sec <n>] [--intercepted-only] [--protocol-mode <all|native|translated|legacy-bridge|blocked|none>] [--conversation <id>] [--scan-limit <1-2000>] [--limit <1-2000>] [--json|--jsonl]", "routes": [{"method": "GET", "path": "/api/logs"}], "flags": [{"name": "--surface", "value": "string", "summary": "all | codex | claude | grok."}, {"name": "--model", "value": "string", "summary": "Case-insensitive exact identity across requested, resolved, served and attempted models."}, {"name": "--provider", "value": "string", "summary": "Case-insensitive provider or failover attempt identity."}, {"name": "--status", "value": "string", "summary": "all | success (200-299) | errors (400-599)."}, {"name": "--time-window", "value": "string", "summary": "all | 15m | 1h | 24h, relative to observation time."}, {"name": "--min-tok-per-sec", "value": "number", "summary": "Inclusive minimum observed token speed."}, {"name": "--max-tok-per-sec", "value": "number", "summary": "Exclusive maximum observed token speed."}, {"name": "--intercepted-only", "value": "boolean", "summary": "Rows carrying an observed rewrite marker."}, {"name": "--protocol-mode", "value": "string", "summary": "all | native | translated | legacy-bridge | blocked | none."}, {"name": "--conversation", "value": "string", "summary": "Conversation ID or stored hash."}, {"name": "--conversationId", "value": "string", "summary": "Alias of --conversation."}, {"name": "--scan-limit", "value": "number", "summary": "1-2000 raw rows inspected; default 2000."}, {"name": "--limit", "value": "number", "summary": "1-2000 matching rows returned; default 200."}, {"name": "--json", "value": "boolean", "summary": "Versioned view with filters, cursor and observed-window counts."}, {"name": "--jsonl", "value": "boolean", "summary": "Matching rows only; exclusive with --json."}], "mutates": false, "json": "envelope", "details": ["One snapshot: filters run locally over the raw server window before the output limit. No follow/events; existing logs behavior remains available.", "JSON schemaVersion1 reports scanLimit, loaded, matched, returned and limit for this observed window only. Cursor is not a resumable filter token.", "Empty matches succeed; malformed, refused, oversized or unavailable responses fail. SIGINT130/SIGTERM143 preserve cancellation."]},
6
16
  {"command": ["observe", "logs", "filter"], "summary": "Select a bounded log snapshot with dashboard filters.", "usage": "ocx observe logs filter [--surface <all|codex|claude|grok>] [--model <id>] [--provider <name>] [--status <all|success|errors>] [--time-window <all|15m|1h|24h>] [--min-tok-per-sec <n>] [--max-tok-per-sec <n>] [--intercepted-only] [--protocol-mode <all|native|translated|legacy-bridge|blocked|none>] [--conversation <id>] [--scan-limit <1-2000>] [--limit <1-2000>] [--json|--jsonl]", "routes": [{"method": "GET", "path": "/api/logs"}], "flags": [{"name": "--surface", "value": "string", "summary": "all | codex | claude | grok."}, {"name": "--model", "value": "string", "summary": "Case-insensitive exact identity across requested, resolved, served and attempted models."}, {"name": "--provider", "value": "string", "summary": "Case-insensitive provider or failover attempt identity."}, {"name": "--status", "value": "string", "summary": "all | success (200-299) | errors (400-599)."}, {"name": "--time-window", "value": "string", "summary": "all | 15m | 1h | 24h, relative to observation time."}, {"name": "--min-tok-per-sec", "value": "number", "summary": "Inclusive minimum observed token speed."}, {"name": "--max-tok-per-sec", "value": "number", "summary": "Exclusive maximum observed token speed."}, {"name": "--intercepted-only", "value": "boolean", "summary": "Rows carrying an observed rewrite marker."}, {"name": "--protocol-mode", "value": "string", "summary": "all | native | translated | legacy-bridge | blocked | none."}, {"name": "--conversation", "value": "string", "summary": "Conversation ID or stored hash."}, {"name": "--conversationId", "value": "string", "summary": "Alias of --conversation."}, {"name": "--scan-limit", "value": "number", "summary": "1-2000 raw rows inspected; default 2000."}, {"name": "--limit", "value": "number", "summary": "1-2000 matching rows returned; default 200."}, {"name": "--json", "value": "boolean", "summary": "Versioned view with filters, cursor and observed-window counts."}, {"name": "--jsonl", "value": "boolean", "summary": "Matching rows only; exclusive with --json."}], "mutates": false, "json": "envelope", "details": ["One snapshot: filters run locally over the raw server window before the output limit. No follow/events; existing logs behavior remains available.", "JSON schemaVersion1 reports scanLimit, loaded, matched, returned and limit for this observed window only. Cursor is not a resumable filter token.", "Empty matches succeed; malformed, refused, oversized or unavailable responses fail. SIGINT130/SIGTERM143 preserve cancellation."]},
7
17
  {"command": ["companion", "usage"], "summary": "Read today and 30-day totals using saved companion filters.", "usage": "ocx companion usage [--json]", "routes": [{"method": "GET", "path": "/api/companion/settings"}, {"method": "GET", "path": "/api/usage"}], "flags": [{"name": "--json", "value": "boolean", "summary": "Versioned filtered ranges, settings provenance and partial status."}], "mutates": false, "json": "envelope", "details": ["Reads saved settings then two usage ranges on the same runtime; this is not an atomic snapshot. No connected-client management relay or local fallback.", "Preserves null/default/corrupt settings provenance, missing measurements and incomplete reports. Filters follow saved model and hidden-provider preferences.", "Any unavailable range yields partial:true and exit1 while preserving the other result. Both available yields exit0 even when incomplete. SIGINT130/SIGTERM143 emit no late report."]},
@@ -1,7 +1,7 @@
1
1
  import { recordCommittedDesktopGateway } from "../claude/desktop-gateway-state";
2
2
  import { readFileSync, writeFileSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
- import { getConfigDir } from "../config/paths";
4
+ import { getConfigDir, withConfigDirHardeningSettled } from "../config/paths";
5
5
  import { loadConfig, mutatePersistedConfig, withConfigMutationLockSync } from "../config";
6
6
  import { claudeDesktopIntegrationEnabledNow, setIntegrationEnabled } from "../codex/desired-state";
7
7
  import { readClientConnectionState, assertClientConnectionUnchanged, assertNoClientDisconnectPending, type ClientConnectionState } from "../client/state";
@@ -19,12 +19,12 @@ import {
19
19
  } from "../claude/desktop-profile";
20
20
  import { inspectDesktop3pConfigLibrary, removeDesktop3pStandardPivot, writeDesktop3pConfig, type Desktop3pConfigMode, parseDesktop3pModeArgs } from "../claude/desktop-3p";
21
21
  import {
22
- applyDesktopFirstParty,
22
+ applyDesktopFirstParty, withFirstPartySecretsSettled,
23
23
  captureDesktopFirstPartyRollback,
24
24
  isClaudeDesktopMode,
25
25
  observeClaudeDesktopMode,
26
26
  recordClaudeDesktopMode,
27
- removeDesktopFirstParty,
27
+ removeDesktopFirstParty, removeDesktopFirstPartySettled,
28
28
  resolveClaudeDesktopMode,
29
29
  resolveClaudeDesktopApplyMode,
30
30
  type ClaudeDesktopModeObservation,
@@ -99,6 +99,7 @@ type DesktopApplyResult = {
99
99
  warning?: string;
100
100
  picker?: DesktopPickerStatus;
101
101
  delegated?: boolean;
102
+ diagnostic?: import("../claude/desktop-first-party").InterceptSecretDiagnostic;
102
103
  };
103
104
 
104
105
  type PickerRouteResponse = {
@@ -155,7 +156,7 @@ async function trustPickerLocally(
155
156
  ): Promise<{ ok: true; callerAddedTrust: boolean; caPath: string; sha1: string } | { ok: false; reason: string }> {
156
157
  try {
157
158
  const configDir = getConfigDir();
158
- const paths = pickerTrustPaths(deps, configDir);
159
+ const paths = await withConfigDirHardeningSettled(configDir, () => pickerTrustPaths(deps, configDir));
159
160
  if (!acceptsPickerAuthority(paths.certPem)) return { ok: false, reason: "ca_unverified" };
160
161
  if (!deps.ensurePickerCaImpl) {
161
162
  // The bytes in ca.pem are only safe to trust when they match the authority the running
@@ -426,14 +427,14 @@ async function applyFirstPartyDesktop(
426
427
  // Establish the replacement before deleting the working gateway. A refused
427
428
  // cleanup restores only our managed env keys, preserving unrelated settings.
428
429
  const rollback = captureDesktopFirstPartyRollback(config);
429
- const applied = applyDesktopFirstParty(config);
430
- if (!applied.ok) return { ok: false, path: applied.path, reason: applied.reason };
430
+ const applied = await withFirstPartySecretsSettled(getConfigDir(), () => applyDesktopFirstParty(config));
431
+ if (!applied.ok) return { ok: false, path: applied.path, reason: applied.reason, ...(applied.diagnostic ? { diagnostic: applied.diagnostic } : {}) };
431
432
  const appliedFingerprint = config.claudeCode?.desktopProfile?.appliedFingerprint ?? null;
432
433
  const library = inspectDesktop3pConfigLibrary({ appliedFingerprint });
433
434
  if (library.kind === "gateway_ours" || library.kind === "gateway_drifted") {
434
435
  const removed = removeDesktop3pStandardPivot({ appliedFingerprint, replaceWhileEnabled: true });
435
436
  if (!removed.ok) {
436
- const restored = removed.changed || !applied.changed || rollback();
437
+ const restored = removed.changed || !applied.changed || await withConfigDirHardeningSettled(getConfigDir(), rollback);
437
438
  const modeSaved = !removed.changed || saveDesktopMode("first-party", deps);
438
439
  const warning = [restored ? "" : "first-party settings rollback did not complete",
439
440
  modeSaved ? "" : "first-party is active but its mode marker was not saved"].filter(Boolean).join("; ");
@@ -462,7 +463,7 @@ export async function applyDesktop(
462
463
  const modeSaved = saveDesktopMode("gateway", deps);
463
464
  const warning = [result.warning, modeSaved ? "" : "desktop mode marker was not saved"].filter(Boolean).join(" ");
464
465
  // The gateway mode is committed before retiring first-party settings.
465
- const removed = removeDesktopFirstParty(loadConfig());
466
+ const removed = await removeDesktopFirstPartySettled(loadConfig);
466
467
  if (!removed.ok) return { ok: false, path: removed.path, reason: "first_party_settings_unreadable",
467
468
  warning: ["gateway applied; first-party cleanup remains incomplete", warning].filter(Boolean).join(" ") };
468
469
  if (removed.retainedFor === "cli") {
package/src/cli/claude.ts CHANGED
@@ -32,7 +32,7 @@ import { DEFAULT_CATALOG_PATH } from "../codex/paths";
32
32
  import { readFileSync } from "node:fs";
33
33
  import { join } from "node:path";
34
34
  import { aliasForNative, aliasForRoute, legacyAliasForNative, legacyAliasForRoute } from "../claude/alias";
35
- import { desktop3pAlias, isRealDesktop3pModelId, resolveDesktop3pAlias } from "../claude/desktop-3p";
35
+ import { desktop3pAlias, isRealDesktop3pModelId, legacyDesktop3pAlias, resolveDesktop3pAlias } from "../claude/desktop-3p";
36
36
  import { desktopProfileWireAlias, legacyDesktopProfileWireAlias } from "../claude/desktop-profile";
37
37
  import { inspectDesktopFirstParty } from "../claude/desktop-first-party";
38
38
  import { isClaudeInterceptProxyUrl, type ClaudeInterceptSettingsState } from "../claude/intercept/settings";
@@ -633,7 +633,8 @@ export function nativeClaudeModelIds(config: OcxConfig): string[] {
633
633
  const alias = assignments[route]!.alias;
634
634
  const slash = route.indexOf("/");
635
635
  return [alias, desktopProfileWireAlias(alias), legacyDesktopProfileWireAlias(alias),
636
- desktop3pAlias(route.slice(0, slash), route.slice(slash + 1))];
636
+ desktop3pAlias(route.slice(0, slash), route.slice(slash + 1)),
637
+ legacyDesktop3pAlias(route.slice(0, slash), route.slice(slash + 1))];
637
638
  }));
638
639
  // The configured default is a genuine declaration too: the catalog seeds it for static
639
640
  // providers, so it must be recognized here even without a server registry.
@@ -34,6 +34,10 @@ export function skipsCodexShimAutoRestore(command: string | undefined, args: str
34
34
  // The desktop's approval-bound stop must validate its snapshot before any unrelated
35
35
  // CLI repair changes the installation it was approved against.
36
36
  if (command === "stop" && args.some(arg => arg.startsWith("--expect-"))) return true;
37
+ // A pinned sync (#7694) must change nothing when its expected Home or hub key does not hold,
38
+ // so the root preflight may not repair the shim first; the sync runner repairs it only after
39
+ // the locked identity check passed (runCodexShimAutoRestore in src/cli/dispatch.ts).
40
+ if (command === "sync" && args.some(arg => /^--expect-(link|hub-key)(=|$)/.test(arg))) return true;
37
41
  // The entire updater-inspection namespace is zero-effect, including malformed
38
42
  // or future actions. A later `apply` implementation must own its preflight.
39
43
  if (command === "system" && args[1] === "codex-cli-update") return true;
@@ -47,6 +51,11 @@ export function maybeAutoRestoreCodexShim(
47
51
  deps: CodexShimAutoRestoreCliDeps = DEFAULT_DEPS,
48
52
  ): void {
49
53
  if (skipsCodexShimAutoRestore(command, args)) return;
54
+ runCodexShimAutoRestore(deps);
55
+ }
56
+
57
+ /** The repair itself, without the command gate: for a caller that deferred it past its own check. */
58
+ export function runCodexShimAutoRestore(deps: CodexShimAutoRestoreCliDeps = DEFAULT_DEPS): void {
50
59
  try {
51
60
  const result = deps.restore({
52
61
  enabled: () => codexShimAutoRestoreEnabled(deps.readConfig().config, deps.env),
@@ -40,6 +40,13 @@ function publicCombo(value: unknown): Record<string, unknown> {
40
40
  if (!tiers) invalid();
41
41
  result[key] = tiers;
42
42
  continue;
43
+ } else if (key === "cooldownReprobe") {
44
+ if (!record(child) || typeof child.enabled !== "boolean"
45
+ || Object.keys(child).some(field => field !== "enabled" && field !== "intervalMs")) invalid();
46
+ if (child.intervalMs !== undefined && (typeof child.intervalMs !== "number"
47
+ || !Number.isSafeInteger(child.intervalMs) || child.intervalMs < 1000 || child.intervalMs > 86_400_000)) invalid();
48
+ result[key] = { enabled: child.enabled, ...(child.intervalMs !== undefined ? { intervalMs: child.intervalMs } : {}) };
49
+ continue;
43
50
  } else if (key === "sessionPin") {
44
51
  const pin = normalizeJevSessionPin(child);
45
52
  if (!pin) invalid();
package/src/cli/combo.ts CHANGED
@@ -24,6 +24,7 @@ const USAGE = `Usage:
24
24
  ocx combo show <id> [--json]
25
25
  ocx combo set <id> [--targets <provider/model[:weight],...> | --targets-file <FILE|->]
26
26
  [--strategy <failover|round-robin|random|least-used|reset-window|jev>] [--sticky <1-100|->]
27
+ [--cooldown-reprobe <on|off>] [--cooldown-reprobe-interval <ms>]
27
28
  [--effort <low|medium|high|xhigh|max|ultra|->] [--effort-mode <fallback|force|->]
28
29
  (force overrides valid client effort and can increase cost/latency) [--alias <name|->]
29
30
  [--native-alias [on|off]] [--allow-metered-targets <on|off>] [--display-name <label|->]
@@ -114,6 +115,16 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise<number> {
114
115
  throw new CliUsageError("--sticky must be an integer from 1 to 100, or -", USAGE);
115
116
  }
116
117
  if (stickyLimit !== undefined && stickyLimit > 100) throw new CliUsageError("--sticky must be <= 100", USAGE);
118
+ const reprobe = takeOption(args, "--cooldown-reprobe");
119
+ const reprobeInterval = takeOption(args, "--cooldown-reprobe-interval");
120
+ if (reprobe !== undefined && reprobe !== "on" && reprobe !== "off") {
121
+ throw new CliUsageError("--cooldown-reprobe must be on or off", USAGE);
122
+ }
123
+ const reprobeIntervalMs = reprobeInterval === undefined ? undefined : Number(reprobeInterval);
124
+ if (reprobeIntervalMs !== undefined && (!Number.isSafeInteger(reprobeIntervalMs)
125
+ || reprobeIntervalMs < 1000 || reprobeIntervalMs > 86_400_000)) {
126
+ throw new CliUsageError("--cooldown-reprobe-interval must be an integer from 1000 to 86400000 ms", USAGE);
127
+ }
117
128
  const effort = takeOption(args, "--effort");
118
129
  const effortMode = takeOption(args, "--effort-mode");
119
130
  if (effortMode !== undefined && effortMode !== "fallback" && effortMode !== "force" && effortMode !== "-") {
@@ -180,6 +191,13 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise<number> {
180
191
  const combo: Record<string, unknown> = existing
181
192
  ? Object.fromEntries(Object.entries(existing).filter(([, value]) => value !== null))
182
193
  : { strategy, stickyLimit: stickyLimit ?? 1 };
194
+ if (reprobe !== undefined || reprobeIntervalMs !== undefined) {
195
+ const previous = (combo.cooldownReprobe ?? {}) as { enabled?: boolean; intervalMs?: number };
196
+ combo.cooldownReprobe = { ...previous,
197
+ enabled: reprobe === undefined ? previous.enabled === true : reprobe === "on",
198
+ ...(reprobeIntervalMs !== undefined ? { intervalMs: reprobeIntervalMs } : {}),
199
+ };
200
+ }
183
201
  delete combo.id;
184
202
  delete combo.model;
185
203
  if (replacingTargets) combo.targets = additional.targets ?? parsedTargets;
@@ -9,6 +9,9 @@ import { detectCodexRoutingDrift } from "../codex/routing-drift";
9
9
  import { readBoundedCodexConfig } from "../codex/inject/bounded-config-reader";
10
10
  import { currentExternalCodexModelProvider } from "../codex/inject";
11
11
  import { reconcileJournal } from "../codex/journal";
12
+ import { shouldSyncCodexOnStart } from "../codex/desired-state";
13
+ import { loadConfig } from "../config";
14
+ import { updateTeardownHandoverPending } from "../update/teardown-handover";
12
15
  import { markSiblingStart, siblingOfLivePort } from "../codex/sibling-start";
13
16
  import { readClientConnectionState } from "../client/state";
14
17
  import { findManagedRegion, resolveGrokHome } from "../grok/inject";
@@ -350,5 +353,14 @@ export function reconcileStartupJournal(): void {
350
353
  const clientState = readClientConnectionState();
351
354
  reconcileJournal(clientState.kind === "connected"
352
355
  ? { activeClientApiKeyId: clientState.value.apiKeyId }
353
- : undefined);
356
+ : { adoptUpdateHandover: updateTeardownHandoverPending() && startupSyncEnabled() });
357
+ }
358
+
359
+ /**
360
+ * #7423: adoption keeps routing only for a startup that will re-publish it. A user who has
361
+ * since turned the Codex integration off gets the ordinary recovery, even with a stale
362
+ * handover receipt on disk; an unreadable config is treated the same way.
363
+ */
364
+ function startupSyncEnabled(): boolean {
365
+ try { return shouldSyncCodexOnStart(loadConfig()); } catch { return false; }
354
366
  }
@@ -404,6 +404,14 @@ const commandRunners: Record<string, CommandRunner> = {
404
404
  },
405
405
  sync: async deps => {
406
406
  const syncArgs = deps.args.slice(1);
407
+ // #7694: parse the expected identity before anything else reads or writes state.
408
+ const { parseSyncExpectation, reportSyncExpectationMismatch, SYNC_EXPECTATION_USAGE_EXIT } = await import("./sync-expectation");
409
+ const parsedExpectation = parseSyncExpectation(syncArgs);
410
+ if (!parsedExpectation.ok) {
411
+ console.error(parsedExpectation.message);
412
+ return SYNC_EXPECTATION_USAGE_EXIT;
413
+ }
414
+ const expectation = parsedExpectation.expectation;
407
415
  const restartScope = readRestartScope(syncArgs, console);
408
416
  // The wire field keeps APP-SERVER-ONLY meaning and is deliberately not widened. A
409
417
  // remote hub must not end a local user's conversations because a field name acquired
@@ -412,15 +420,24 @@ const commandRunners: Record<string, CommandRunner> = {
412
420
  const restartCodex = restartScope.appServers;
413
421
  const { readClientConnectionState } = await import("../client/state");
414
422
  const clientState = readClientConnectionState();
415
- if (clientState.kind === "invalid" || clientState.kind === "mismatched") {
423
+ // With an expectation the unlocked read decides nothing: the connected sync re-reads under its
424
+ // lock and refuses there, so a state that changes in between can never reach the local path.
425
+ if (!expectation && (clientState.kind === "invalid" || clientState.kind === "mismatched")) {
416
426
  console.error(`Client state is ${clientState.kind}: ${clientState.reason}`);
417
427
  return 1;
418
428
  }
419
- if (clientState.kind === "connected") {
429
+ if (expectation || clientState.kind === "connected") {
420
430
  try {
421
431
  const { syncConnectedClient } = await import("../client/connect");
422
- const result = await syncConnectedClient({ restartCodex });
423
- const link = clientState.value.transport === "link";
432
+ const result = await syncConnectedClient(expectation ? { restartCodex, expect: expectation } : { restartCodex });
433
+ if (expectation) {
434
+ // The root preflight skipped the shim repair for a pinned sync; the identity held, so
435
+ // run it now, as an unpinned sync would have.
436
+ const { runCodexShimAutoRestore } = await import("./codex-shim-autorestore");
437
+ runCodexShimAutoRestore();
438
+ }
439
+ // The connection the sync ran under, read inside its lock; the read above may be stale.
440
+ const link = result.connection.transport === "link";
424
441
  console.log(result.stale
425
442
  ? `${link ? "Home" : "Hub"} unavailable; retained and applied the last-known-good remote catalog (stale).`
426
443
  : link ? "Remote Link Home catalog synchronized." : "Remote hub catalog synchronized.");
@@ -445,7 +462,7 @@ const commandRunners: Record<string, CommandRunner> = {
445
462
  if (link && result.appliedRecord) {
446
463
  const { applyRestartMessage, restartRuntimeAfterApply } = await import("./link-apply-restart");
447
464
  const { sameClientConnectionOwner } = await import("../client/state");
448
- const applied = clientState.value;
465
+ const applied = result.connection;
449
466
  const outcome = await restartRuntimeAfterApply(result.appliedRecord, {
450
467
  restart: startWhenStopped => deps.handleProxyRestart(startWhenStopped),
451
468
  recoveryStart: recovering => deps.handleRestartStartWhenStopped(recovering),
@@ -470,6 +487,8 @@ const commandRunners: Record<string, CommandRunner> = {
470
487
  // types it as `number | string`; only a numeric code means anything here.
471
488
  return typeof process.exitCode === "number" ? process.exitCode : 0;
472
489
  } catch (error) {
490
+ const { ClientSyncExpectationError } = await import("../client/sync-expectation");
491
+ if (error instanceof ClientSyncExpectationError) return reportSyncExpectationMismatch(error, console);
473
492
  // The refresh path reaches the same hub catalog `ocx connect` validates, so a rejected
474
493
  // reasoning level arrives here as hub-supplied text. Rendering it through the shared
475
494
  // terminal boundary is what keeps the routine refresh from forging output; the domain
@@ -527,7 +546,7 @@ const commandRunners: Record<string, CommandRunner> = {
527
546
  },
528
547
  config,
529
548
  port: live.port,
530
- }, ["mcode", "pi", "raycast", "omo", "cline", "commandcode", "droid", "opencode", "kilo", "qoder"]));
549
+ }, ["mcode", "pi", "raycast", "omo", "cline", "commandcode", "droid", "opencode", "kilo", "qoder", "qoder-cn", "workbuddy", "workbuddy-ai"]));
531
550
  } catch (error) {
532
551
  console.warn(`Client integrations were not refreshed: ${error instanceof Error ? error.message : String(error)}`);
533
552
  }
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { loadConfig } from "../config";
12
12
  import { cliFirstPartyDesired, firstPartyDesired, reconcileClaudeFirstPartySettings } from "../claude/first-party-settings";
13
+ import { getConfigDir } from "../config/paths";
13
14
  import { claudeInterceptEnabled } from "../claude/intercept/runtime";
14
15
  import { removeDesktopPickerArtifacts } from "../claude/desktop-picker";
15
16
  import { findLiveProxy } from "../server/proxy-liveness";
@@ -17,10 +18,10 @@ import { runtimeRequest } from "./runtime-api";
17
18
  import { stripGrokConfig, type GrokInjectResult } from "../grok/inject";
18
19
  import { inspectDesktop3pConfigLibrary, removeDesktop3pStandardPivot } from "../claude/desktop-3p";
19
20
  import {
20
- applyDesktopFirstParty,
21
+ applyDesktopFirstParty, withFirstPartySecretsSettled,
21
22
  inspectDesktopFirstParty,
22
23
  observeClaudeDesktopMode,
23
- removeDesktopFirstParty,
24
+ removeDesktopFirstParty, removeDesktopFirstPartySettled,
24
25
  resolveClaudeDesktopMode,
25
26
  } from "../claude/desktop-first-party";
26
27
  import {
@@ -154,8 +155,9 @@ export async function ensureClaudeDesktopMatchesDesired(
154
155
  if (cliFirstPartyDesired(config)) {
155
156
  const seen = (deps.inspectDesktopFirstParty ?? inspectDesktopFirstParty)(config);
156
157
  if (seen.settings.kind === "absent" || seen.stale || !claudeInterceptEnabled(config)) {
157
- const result = (deps.reconcileClaudeFirstPartySettings ?? reconcileClaudeFirstPartySettings)(config,
158
- firstPartyDesired(config, (deps.observeClaudeDesktopMode ?? observeClaudeDesktopMode)(config)));
158
+ const result = await withFirstPartySecretsSettled(getConfigDir(), () =>
159
+ (deps.reconcileClaudeFirstPartySettings ?? reconcileClaudeFirstPartySettings)(config,
160
+ firstPartyDesired(config, (deps.observeClaudeDesktopMode ?? observeClaudeDesktopMode)(config))));
159
161
  if (result.ok && result.changed) log(` + Claude CLI first-party env refreshed (${result.path})`);
160
162
  else if (!result.ok) error(`⚠️ Claude CLI first-party env refresh skipped: ${result.reason}.`);
161
163
  }
@@ -173,7 +175,7 @@ export async function ensureClaudeDesktopMatchesDesired(
173
175
  }
174
176
  const seen = (deps.inspectDesktopFirstParty ?? inspectDesktopFirstParty)(config);
175
177
  if (!seen.stale) return;
176
- const applied = (deps.applyDesktopFirstParty ?? applyDesktopFirstParty)(config);
178
+ const applied = await withFirstPartySecretsSettled(getConfigDir(), () => (deps.applyDesktopFirstParty ?? applyDesktopFirstParty)(config));
177
179
  if (applied.ok && applied.changed) log(` + Claude Desktop first-party env refreshed (${applied.path})`);
178
180
  else if (!applied.ok) error(`⚠️ Claude Desktop first-party env refresh skipped: ${applied.reason}.`);
179
181
  return;
@@ -196,7 +198,7 @@ export async function ensureClaudeDesktopMatchesDesired(
196
198
  error(`⚠️ Claude Desktop picker cleanup skipped: ${detail}.`);
197
199
  }
198
200
  try {
199
- const env = (deps.removeDesktopFirstParty ?? removeDesktopFirstParty)(deps.loadConfig());
201
+ const env = await removeDesktopFirstPartySettled(deps.loadConfig, {}, deps.removeDesktopFirstParty ?? removeDesktopFirstParty);
200
202
  if (env.ok && env.changed) log(" ↩️ Claude Desktop first-party env removed.");
201
203
  else if (env.ok && env.retainedFor === "cli") log(" = Shared first-party env retained for Claude Code CLI.");
202
204
  else if (!env.ok) error(`⚠️ Claude Desktop first-party env cleanup skipped: ${env.reason} (${env.path}).`);
@@ -94,6 +94,9 @@ export function exportModelsFromProxyRows(
94
94
  if (entry.maxTokens !== undefined) model.maxTokens = entry.maxTokens;
95
95
  if (entry.maxInputTokens !== undefined) model.maxInputTokens = entry.maxInputTokens;
96
96
  if (entry.reasoningEfforts !== undefined) model.reasoningEfforts = [...entry.reasoningEfforts];
97
+ if (entry.supportsThinkingToggle !== undefined) model.supportsThinkingToggle = entry.supportsThinkingToggle;
98
+ if (entry.supportsReasoningEffort !== undefined) model.supportsReasoningEffort = entry.supportsReasoningEffort;
99
+ if (entry.defaultThinkingEnabled !== undefined) model.defaultThinkingEnabled = entry.defaultThinkingEnabled;
97
100
  if (entry.defaultReasoningEffort) model.defaultReasoningEffort = entry.defaultReasoningEffort;
98
101
  if (entry.inputModalities && entry.inputModalities.length > 0) {
99
102
  model.inputModalities = [...entry.inputModalities];
@@ -169,7 +172,7 @@ export async function handleExportCommand(argv: string[], deps: ExportCommandDep
169
172
  const spec = EXPORT_CLIENTS[client];
170
173
  const root = await runtimeBaseUrl(deps);
171
174
  let built: { document: unknown; text: string };
172
- if (client === "raycast" || client === "droid" || client === "qoder") {
175
+ if (client === "raycast" || client === "droid" || client === "qoder" || client === "qoder-cn" || client === "workbuddy" || client === "workbuddy-ai") {
173
176
  // The dial address alone cannot distinguish a wildcard authenticated bind
174
177
  // from loopback. Let the live server resolve its admission/listener policy;
175
178
  // saved config can differ from the process serving this request.
package/src/cli/help.ts CHANGED
@@ -49,6 +49,7 @@ Usage:
49
49
  ocx remote-workspace <sub> Pair/run an OCX-only remote execution computer
50
50
  ocx disconnect Restore local state and clear the hub connection
51
51
  ocx sync [--restart-codex] Fetch models from providers and inject into Codex config
52
+ --expect-link <id> | --expect-hub-key <id>: only from that Home/hub key (exit 5 otherwise)
52
53
  ocx sync-cache [--restart-codex]
53
54
  Refresh Codex's model cache from the active catalog
54
55
  ocx catalog pull <https-url> Install a validated remote catalog and refresh the Codex cache
@@ -93,7 +94,7 @@ Usage:
93
94
  ocx api-key <sub> Alias of ocx access key
94
95
  ocx access <sub> External API keys and endpoint information
95
96
  ocx api <sub> Protocol paths: vocabulary, request-path preview, and policy
96
- ocx export --client <id> Print a client config wired to the running proxy (20 clients)
97
+ ocx export --client <id> Print a client config wired to the running proxy (23 clients)
97
98
  ocx integration client <sub> Enable, disable, inspect or roll back a client integration
98
99
  ocx grok <sub> Grok Build model selection and apply
99
100
  ocx system <sub> Runtime settings, startup, sync, OpenCodex updates, and Codex CLI inspection
package/src/cli/index.ts CHANGED
@@ -42,7 +42,8 @@ import {
42
42
  type RetainedCodexProviderTable,
43
43
  } from "../codex/inject/restore";
44
44
  import { stripGrokConfig } from "../grok/inject";
45
- import { STOP_HISTORY_DEFERRED_EXIT_CODE, STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "../update/stop-contract.mjs";
45
+ import { STOP_HISTORY_DEFERRED_EXIT_CODE, STOP_HISTORY_INCOMPLETE_EXIT_CODE, STOP_TEARDOWN_HANDED_OVER_EXIT_CODE } from "../update/stop-contract.mjs";
46
+ import { announceStopHandover, completeUpdateTeardownHandover, forgetUpdateTeardownHandover, stopHandsTeardownOver, updateTeardownHandoverRequested } from "../update/teardown-handover";
46
47
  import {
47
48
  describeHistoryJobFailure,
48
49
  resolveCodexHistoryJobTarget,
@@ -77,7 +78,7 @@ import {
77
78
  pendingTeardownsAreExactly,
78
79
  quarantinePendingTeardown,
79
80
  } from "../config/pending-teardown";
80
- import { collectStatus, deadProxyRoutingAdviceLines, detectMissingCodexCatalogPath, hubStatusLines, missingCodexCatalogLines, remoteHubBannerLine, remoteHubStatusLines, runtimeSupervisorLine, unusedProxyWarningLines } from "./status";
81
+ import { collectStatus, detectMissingCodexCatalogPath, hubStatusLines, missingCodexCatalogLines, remoteHubBannerLine, remoteHubStatusLines, runtimeSupervisorLine, statusDeadProxyLines, statusProxyUp, statusUnusedProxyLines } from "./status";
81
82
  import { endpointsToProve, everyEndpointProvenDownAsync, sharedTeardownAuthorized, type UninstallObservation } from "./uninstall-plan";
82
83
  import { takeFlag } from "./runtime-api";
83
84
  import { parseStartOptions, StartArgsError } from "./start-args";
@@ -127,6 +128,7 @@ import { inspectGuardedManagerTarget, observeGuardedManagerStopped } from "../se
127
128
  import { summarizeStopRun, type StopOutcome, type StopRunRecord } from "./stop-report";
128
129
  import { runCli } from "./root";
129
130
  import { isProcessAlive, ProxyOwnershipRefusedError, refusalNextStep, stopProxy } from "../lib/process-control";
131
+ import { directLocalHttpFetch } from "../server/direct-local-http";
130
132
  import { startupDataPlaneToken } from "../lib/service-secrets";
131
133
  import { assertNotAdminToken, diagnoseService, isServiceOwnershipError, proxyStillLiveAfterStop, serviceCommand, serviceEnvironmentOwnedHere, serviceStartableFromTray, serviceStatePaths, serviceStatusSummary, stopServiceIfInstalledDetailed, uninstallServiceIfInstalled, uninstallServiceDetailed } from "../service";
132
134
  import { acquireOwnershipMutationLease } from "../service/ownership-mutation-lease.mjs";
@@ -142,7 +144,7 @@ import {
142
144
  StartOwnershipRollbackUncertainError,
143
145
  } from "./start-ownership-publication";
144
146
  import { syncModelsToCodex } from "../codex/sync";
145
- import { localClientSkipReason, shouldSyncGrokOnStart, syncCodexOnStartIfEnabled } from "../codex/desired-state";
147
+ import { localClientSkipReason, shouldSyncCodexOnStart, shouldSyncGrokOnStart, syncCodexOnStartIfEnabled } from "../codex/desired-state";
146
148
  import { honorSiblingMarker, markSiblingStart, siblingOfLivePort, siblingRuntimeField, siblingStopFoundOwner, withoutSiblingMarker } from "../codex/sibling-start";
147
149
  import { consumeSiblingHandoff } from "../codex/sibling-handoff";
148
150
  import {
@@ -162,7 +164,7 @@ import { removeOwnedConfigAfterDesktopCleanup } from "./uninstall-client-state";
162
164
  import { withProcessRuntimeProvenance } from "../lib/bun-runtime";
163
165
  import { startArgv } from "../lib/self-launch-argv";
164
166
  import { initializeNodeLauncherContext } from "./launcher-context";
165
- import { restoreSharedClientStateAfterStop } from "./stop-restore";
167
+ import { assertConnectedClientStopSupported, connectedClientStopSkipLine, preflightConnectedClientStop, preserveConnectedClientRoutingOnExit, restoreSharedClientStateAfterStop } from "./stop-restore";
166
168
  import { startClientRuntimeUnderOwnershipLease } from "./client-start-fence";
167
169
  import { recoverStartStateUnderOwnershipLease } from "./start-owner-fence";
168
170
  import { handledSignalExitCode } from "../lib/handled-signal-exit";
@@ -383,6 +385,7 @@ async function findProxyOwnerBeforeJournalRecovery(
383
385
  }
384
386
 
385
387
  async function handleStart(options: { block?: boolean } = {}) {
388
+ forgetUpdateTeardownHandover(); // #7423: a recovery start must not pass the marker to its update workers
386
389
  updateRestartChild?.check();
387
390
  // A supervised service child defers to a foreign recorded owner before doing
388
391
  // anything else. 'ocx service start' refuses this activation path already, but
@@ -654,7 +657,7 @@ async function handleStart(options: { block?: boolean } = {}) {
654
657
  try { healthSentinel?.stop(); } catch { /* best-effort */ }
655
658
  // Dashboard drain-and-restart (#563) must not tear down injection: the replacement
656
659
  // process expects Codex/Grok/env fences to still be in place. A sibling owns none of them.
657
- const teardown = decideStartExitTeardown({ sibling: siblingStart, recycling: isRecyclingForExit(), ocxService: process.env.OCX_SERVICE });
660
+ const teardown = preserveConnectedClientRoutingOnExit(decideStartExitTeardown({ sibling: siblingStart, recycling: isRecyclingForExit(), ocxService: process.env.OCX_SERVICE }));
658
661
  if (teardown.revertSystemEnv) {
659
662
  try { revertSystemEnv(); } catch { /* best-effort */ }
660
663
  }
@@ -751,6 +754,8 @@ async function handleStart(options: { block?: boolean } = {}) {
751
754
  },
752
755
  );
753
756
  if (!startupSync.ran) console.log(startupLeftCodexNativeLine(localClientSkipReason(config), server.port ?? port));
757
+ // #7423: routing an update kept in place for this proxy is ours once the startup sync published.
758
+ if (!siblingStart && startupSync.published) completeUpdateTeardownHandover(pid => isProcessAlive(pid) && isLikelyOcxProcess(pid));
754
759
  await refreshOwnedRaycastCatalog(config, port);
755
760
  if (!cleaned && !shuttingDown) healthSentinel = startServiceHealthSentinel(config); // after startup reconciliation; never mid-boot or mid-drain
756
761
  // #1046: one warning per startup, after BOTH writes. The server's cache
@@ -995,8 +1000,6 @@ async function handleRestartStartWhenStopped(recoveringLiveRestart = false): Pro
995
1000
  return restartStartOutcome(false, child, error);
996
1001
  }
997
1002
  }
998
-
999
-
1000
1003
  async function handleStop(approval?: StopApproval) {
1001
1004
  const lease = acquireOwnershipMutationLease(serviceStatePaths());
1002
1005
  try {
@@ -1088,6 +1091,13 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
1088
1091
  // the record; a record left behind by a hard-killed sibling still says so.
1089
1092
  const siblingOfPort = readRuntimePort()?.siblingOfPort;
1090
1093
  const stoppingSibling = siblingOfPort !== undefined;
1094
+ const connectedClientSkip = stoppingSibling ? null : connectedClientStopSkipLine(readClientConnectionState());
1095
+ let connectedClientAlreadyStopped = false;
1096
+ if (connectedClientSkip) {
1097
+ const preflight = await preflightConnectedClientStop(snapshot?.approval);
1098
+ if (preflight === "already-stopped") connectedClientAlreadyStopped = true;
1099
+ else if (preflight) return preflight;
1100
+ }
1091
1101
  // Structured twin of the human lines below, for `ocx stop --json`: one document the
1092
1102
  // desktop shell can read across the process boundary (D4). Every field is assigned
1093
1103
  // where the corresponding boolean already flips — the summarizer never re-decides.
@@ -1124,10 +1134,14 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
1124
1134
  const inheritedTeardowns = listPendingTeardowns()
1125
1135
  .filter(read => isPendingTeardownAbandoned(read, teardownOwnerStillRunning));
1126
1136
  let teardownNonce: string | undefined;
1137
+ // #7423: an update that restarts the proxy asks this stop to leave Codex routing for the replacement.
1138
+ const handoverRequested = updateTeardownHandoverRequested(process.env, () => shouldSyncCodexOnStart(loadConfig())) && !stoppingSibling && !connectedClientSkip;
1139
+ let deferralHonoredByProxy = false;
1127
1140
  const claimTeardown = (endpoint: { hostname: string; port: number }, endpointSource: "exact" | "guessed") => {
1128
1141
  if (teardownNonce || stoppingSibling) return;
1142
+ if (connectedClientSkip) return;
1129
1143
  try {
1130
- teardownNonce = claimPendingTeardown(endpoint, endpointSource).nonce;
1144
+ teardownNonce = claimPendingTeardown(endpoint, endpointSource, process.pid, handoverRequested ? "update-restart" : undefined).nonce;
1131
1145
  } catch (err) {
1132
1146
  // Without a receipt the proxy performs its own teardown, which is the pre-#3008
1133
1147
  // behaviour: correct for every backend that cannot respawn, and merely early for
@@ -1135,33 +1149,17 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
1135
1149
  console.warn(`⚠️ Could not record the deferred-teardown receipt: ${err instanceof Error ? err.message : String(err)}`);
1136
1150
  }
1137
1151
  };
1138
- /**
1139
- * One stop target, used for BOTH the receipt and the request.
1140
- *
1141
- * Deriving them separately meant the receipt could name a different endpoint than the
1142
- * one actually contacted, and a proxy with no runtime record got no receipt at all —
1143
- * silently reopening the parent-crash window on the path where the stop is a hard kill
1144
- * and no child teardown runs at all.
1145
- *
1146
- * So the caller supplies the endpoint it discovered after the orphan listener proves
1147
- * possession of this home's runtime record, even when the pid file is gone.
1148
- *
1149
- * When nothing resolves, the graceful request cannot be made at all — `stopProxy` goes
1150
- * straight to the kill ladder, no child teardown runs, and there is no receipt to leave
1151
- * behind. A warning does not make that durable, so the receipt is claimed FIRST against
1152
- * the endpoint this process would restore anyway. It is the configured listen address,
1153
- * which is the same address every recovery probe would ask about, and an obligation
1154
- * recorded against it is strictly better than none: at worst the probe cannot confirm
1155
- * A guessed endpoint is NOT evidence, so the receipt records which kind it holds: a
1156
- * guessed one fails closed into manual recovery rather than letting a later probe read
1157
- * "the configured port refuses" as proof that the right proxy is down.
1158
- */
1152
+ // Resolve one target for receipt and request. Only a discovered endpoint may direct POST;
1153
+ // a configured guess records an obligation but is never evidence for orphan recovery.
1154
+ // Claim before any kill fallback so a parent crash leaves a durable teardown obligation.
1159
1155
  const stopWithDeferral = async (pid: number, discovered?: { hostname: string; port: number } | null): Promise<boolean> => {
1160
1156
  // Resolve ONCE. Reading the runtime record twice let the receipt name the configured
1161
1157
  // guess while the request went to a runtime endpoint that appeared in between.
1162
1158
  const exact = discovered ?? endpointOf(readRuntimePort(pid));
1159
+ if (connectedClientSkip) await assertConnectedClientStopSupported(exact ? { ...exact, pid } : null);
1163
1160
  claimTeardown(exact ?? configuredEndpoint(), exact ? "exact" : "guessed");
1164
1161
  const graceful = await stopProxy(pid, {
1162
+ fetchFn: connectedClientSkip ? directLocalHttpFetch as typeof fetch : undefined,
1165
1163
  deferSharedTeardownNonce: teardownNonce,
1166
1164
  // Only an exact endpoint may direct the request; the configured fallback is a guess
1167
1165
  // good enough to record an obligation against, not to POST a stop to.
@@ -1170,12 +1168,15 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
1170
1168
  // A valid receipt means the proxy deferred shared teardown to this process. If the
1171
1169
  // receipt could not be written, the proxy restores it itself and the caller must not
1172
1170
  // attempt a second restore after a graceful stop. A hard-kill always leaves restore
1173
- // to this process.
1171
+ // to this process. #7423: only a confirmed deferral kept the proxy's own exit cleanup off.
1172
+ if (graceful && teardownNonce) deferralHonoredByProxy = true;
1174
1173
  return graceful && !teardownNonce;
1175
1174
  };
1176
1175
  const approvedEndpoint = snapshot
1177
1176
  ? { hostname: probeHostname(snapshot.approval.hostname || undefined), port: snapshot.approval.port }
1178
1177
  : null;
1178
+ // Only an exact runtime endpoint may back a handover; without one the ordinary restore runs.
1179
+ const claimHandoverBeforeManager = () => { const exact = handoverRequested ? endpointOf(readRuntimePort()) : null; if (exact) claimTeardown(exact, "exact"); };
1179
1180
  let guardedStep: Awaited<ReturnType<typeof runGuardedManagerStep>> | null = null;
1180
1181
  try {
1181
1182
  const serviceStop = snapshot
@@ -1191,7 +1192,8 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
1191
1192
  })).service
1192
1193
  // A sibling never runs under a service manager: an installed one belongs to the live owner,
1193
1194
  // and its ownership check would fail this stop and skip the stale-record purge below.
1194
- : stoppingSibling ? "absent" : stopServiceIfInstalledDetailed();
1195
+ // #7423: a manager stop takes the proxy down itself, so a handover claims its receipt first.
1196
+ : stoppingSibling || connectedClientAlreadyStopped ? "absent" : (claimHandoverBeforeManager(), stopServiceIfInstalledDetailed());
1195
1197
  record.service = serviceStop;
1196
1198
  stoppedService = serviceStop === "stopped" || serviceStop === "stopped-respawnable";
1197
1199
  schedulerCanRespawn = serviceStop === "stopped-respawnable";
@@ -1430,10 +1432,14 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
1430
1432
  console.error(" The obligation is preserved; retry once the proxy is confirmed stopped.");
1431
1433
  }
1432
1434
  }
1433
- if (nativeRestoreHandledByProxy && !stoppingSibling) record.sharedTeardown = "performed-by-proxy";
1435
+ if (nativeRestoreHandledByProxy && !stoppingSibling && !connectedClientSkip) record.sharedTeardown = "performed-by-proxy";
1434
1436
  if (stoppingSibling) console.log(`↩️ Client routing stays on the proxy at port ${siblingOfPort}; this sibling had no shared teardown to run.`);
1435
- const restoreBlocked = ownershipBlocked || inheritedBlocks || nativeRestoreHandledByProxy || stoppingSibling;
1436
- if (!restoreBlocked) {
1437
+ if (connectedClientSkip) console.log(connectedClientSkip);
1438
+ const restoreBlocked = ownershipBlocked || inheritedBlocks || nativeRestoreHandledByProxy || stoppingSibling || connectedClientSkip !== null;
1439
+ const handedOver = stopHandsTeardownOver({ requested: handoverRequested, restoreBlocked, nonce: teardownNonce,
1440
+ stopFailed, recoveredCount: recoveredNonces.length, proxy: record.proxy, service: record.service, deferralHonored: deferralHonoredByProxy });
1441
+ if (handedOver) announceStopHandover();
1442
+ else if (!restoreBlocked) {
1437
1443
  if (recoveredNonces.length > 0) {
1438
1444
  // A previous deferred stop died before restoring, and the probe says its endpoint is
1439
1445
  // not answering. That is the whole point of leaving the receipt behind.
@@ -1511,6 +1517,7 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
1511
1517
  ? STOP_HISTORY_DEFERRED_EXIT_CODE
1512
1518
  : 1;
1513
1519
  }
1520
+ else if (handedOver) process.exitCode = STOP_TEARDOWN_HANDED_OVER_EXIT_CODE;
1514
1521
  const signals = {
1515
1522
  failed: stopFailed,
1516
1523
  historyOnly: historyOnlyFailure,
@@ -1735,7 +1742,7 @@ async function handleStatus() {
1735
1742
  // `(local)` only while connected: on a standalone install every line is local, and tagging
1736
1743
  // them all would be noise that trains the reader to skip the tag.
1737
1744
  const local = status.json.remoteHub.connected ? " (local)" : "";
1738
- if (status.json.proxy.pid || status.json.proxy.health.ok) {
1745
+ if (statusProxyUp(status.json)) {
1739
1746
  console.log(`✅ Proxy: ${status.proxyLabel}${local}`);
1740
1747
  } else {
1741
1748
  console.log(`❌ Proxy: ${status.proxyLabel}${local}`);
@@ -1752,14 +1759,10 @@ async function handleStatus() {
1752
1759
  if (status.json.versionSkew.warning) {
1753
1760
  console.log(` ⚠️ ${status.json.versionSkew.warning}`);
1754
1761
  }
1755
- for (const line of unusedProxyWarningLines({
1756
- proxyUp: Boolean(status.json.proxy.pid || status.json.proxy.health.ok),
1757
- routingKind: status.json.startup.routingKind,
1758
- })) {
1762
+ for (const line of statusUnusedProxyLines(status.json)) {
1759
1763
  console.log(` ${line}`);
1760
1764
  }
1761
- if (!(status.json.proxy.pid || status.json.proxy.health.ok)) {
1762
- console.log(" ↳ Not running — Codex/Claude requests will fail with connection errors.");
1765
+ if (!statusProxyUp(status.json)) {
1763
1766
  // The service summary a few lines below already tells a registered-but-not-serving
1764
1767
  // user to repair. Printing "install the persistent service" unconditionally
1765
1768
  // contradicted it in the same report, and install re-registers: UAC on Windows and a
@@ -1781,10 +1784,7 @@ async function handleStatus() {
1781
1784
  : " Restart with 'ocx start', or install the persistent service: 'ocx service install'.");
1782
1785
  // Restarting is only half the choice. A user who cannot sign in to Codex at all needs the
1783
1786
  // way out that does not require this proxy to come back (#5261).
1784
- for (const line of deadProxyRoutingAdviceLines({
1785
- proxyUp: false,
1786
- routingKind: status.json.startup.routingKind,
1787
- })) {
1787
+ for (const line of statusDeadProxyLines(status.json)) {
1788
1788
  console.log(` ${line}`);
1789
1789
  }
1790
1790
  }