@bitkyc08/opencodex 2.91.0 → 2.93.0-preview.20261027

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (360) hide show
  1. package/bin/ocx.mjs +47 -8
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BuLy7hL1.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/index-Xfct8owH.js +94 -0
  6. package/gui/dist/assets/quota-summary-DxToX1rV.js +1 -0
  7. package/gui/dist/index.html +2 -2
  8. package/gui/dist/provider-icons/workbuddy-color.svg +29 -0
  9. package/package.json +8 -7
  10. package/src/adapters/anthropic.ts +28 -5
  11. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  12. package/src/adapters/coding-agent/profile.ts +54 -16
  13. package/src/adapters/coding-agent/turn.ts +30 -2
  14. package/src/adapters/command-code.ts +114 -7
  15. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  16. package/src/adapters/devin/live-models.ts +4 -0
  17. package/src/adapters/google-vertex-endpoint.ts +9 -1
  18. package/src/adapters/google-vertex-key-project.ts +223 -0
  19. package/src/adapters/google-wire-compiler.ts +1 -2
  20. package/src/adapters/google.ts +13 -3
  21. package/src/adapters/kiro/reasoning.ts +2 -0
  22. package/src/adapters/kiro-refusal.ts +6 -1
  23. package/src/adapters/kiro-wire.ts +1 -1
  24. package/src/adapters/openai-chat/messages.ts +8 -2
  25. package/src/adapters/openai-chat/passthrough.ts +35 -14
  26. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  27. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  28. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  29. package/src/adapters/openai-chat/tool-name-registry.ts +3 -1
  30. package/src/adapters/openai-chat.ts +9 -10
  31. package/src/adapters/openai-responses/passthrough.ts +7 -4
  32. package/src/adapters/openai-responses/reasoning.ts +13 -0
  33. package/src/adapters/openai-responses/request-strips.ts +60 -0
  34. package/src/adapters/qoder/adapter.ts +129 -8
  35. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  36. package/src/adapters/reasoning-controls.ts +16 -0
  37. package/src/adapters/registry.ts +5 -0
  38. package/src/adapters/tool-call-id.ts +1 -3
  39. package/src/adapters/workbuddy-schema.ts +61 -0
  40. package/src/adapters/workbuddy.ts +68 -0
  41. package/src/bridge/errors.ts +27 -0
  42. package/src/bridge/response-json.ts +1 -1
  43. package/src/bridge/sse.ts +1 -1
  44. package/src/bridge.ts +1 -1
  45. package/src/chat/inbound.ts +4 -1
  46. package/src/chat/outbound.ts +20 -6
  47. package/src/chat/reasoning-details.ts +28 -5
  48. package/src/claude/desktop-first-party.ts +54 -4
  49. package/src/claude/desktop-picker.ts +11 -8
  50. package/src/claude/first-party-settings.ts +3 -1
  51. package/src/claude/inbound.ts +2 -1
  52. package/src/claude/intercept/local-ca.ts +2 -1
  53. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  54. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  55. package/src/claude/intercept/picker-models.ts +6 -3
  56. package/src/claude/intercept/picker-runtime.ts +3 -2
  57. package/src/claude/intercept/runtime.ts +6 -3
  58. package/src/claude/model-info.ts +31 -8
  59. package/src/cli/account-api.ts +11 -0
  60. package/src/cli/capabilities-agents-routing.ts +3 -3
  61. package/src/cli/capabilities-base.ts +7 -1
  62. package/src/cli/capabilities-observe-system.ts +10 -0
  63. package/src/cli/claude-desktop.ts +9 -8
  64. package/src/cli/claude.ts +3 -2
  65. package/src/cli/codex-cli-update.ts +8 -0
  66. package/src/cli/codex-shim-autorestore.ts +9 -0
  67. package/src/cli/combo-result.ts +13 -0
  68. package/src/cli/combo-stats.ts +3 -0
  69. package/src/cli/combo.ts +83 -41
  70. package/src/cli/cross-home-owner.ts +13 -1
  71. package/src/cli/dispatch.ts +25 -6
  72. package/src/cli/ensure-desired-integrations.ts +8 -6
  73. package/src/cli/export-command.ts +4 -1
  74. package/src/cli/help.ts +2 -1
  75. package/src/cli/index.ts +45 -45
  76. package/src/cli/integration-plan-dto.ts +4 -0
  77. package/src/cli/launcher-context.ts +49 -2
  78. package/src/cli/link.ts +45 -32
  79. package/src/cli/opencode.ts +20 -9
  80. package/src/cli/provider.ts +2 -1
  81. package/src/cli/registry.ts +6 -4
  82. package/src/cli/root.ts +9 -0
  83. package/src/cli/status.ts +59 -1
  84. package/src/cli/stop-restore.ts +113 -0
  85. package/src/cli/sync-expectation.ts +60 -0
  86. package/src/cli/uninstall-integrations.ts +41 -7
  87. package/src/cli/usage-compare.ts +68 -12
  88. package/src/client/connect.ts +40 -3
  89. package/src/client/link-home.ts +10 -1
  90. package/src/client/link-ingress.ts +1 -1
  91. package/src/client/link-readiness.ts +97 -0
  92. package/src/client/link-relay-transport.ts +79 -11
  93. package/src/client/link-relay.ts +74 -15
  94. package/src/client/link-tunnel.ts +45 -18
  95. package/src/client/machine-api.ts +3 -1
  96. package/src/client/machine-listener.ts +20 -2
  97. package/src/client/runtime.ts +20 -2
  98. package/src/client/sync-expectation.ts +118 -0
  99. package/src/clients/config-export/agent-clients.ts +96 -0
  100. package/src/clients/config-export/contracts.ts +25 -7
  101. package/src/clients/config-export/qoder.ts +38 -23
  102. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  103. package/src/clients/config-export.ts +12 -0
  104. package/src/clients/lazycodex.ts +7 -2
  105. package/src/clients/reasoning-controls.ts +49 -0
  106. package/src/codex/account-store.ts +17 -3
  107. package/src/codex/app-server-restart-service.ts +6 -5
  108. package/src/codex/auth-api/account-identity.ts +14 -0
  109. package/src/codex/auth-api/account-list.ts +29 -2
  110. package/src/codex/auth-api/http.ts +13 -0
  111. package/src/codex/auth-api/main-account-probe.ts +2 -2
  112. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  113. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  114. package/src/codex/auth-context.ts +15 -12
  115. package/src/codex/catalog/build-entries.ts +22 -0
  116. package/src/codex/catalog/configured-tiers.ts +70 -0
  117. package/src/codex/catalog/effort.ts +52 -11
  118. package/src/codex/catalog/gather-capture.ts +5 -2
  119. package/src/codex/catalog/heal-observation.ts +155 -13
  120. package/src/codex/catalog/metadata.ts +6 -0
  121. package/src/codex/catalog/model-hints.ts +60 -11
  122. package/src/codex/catalog/model-visibility.ts +3 -2
  123. package/src/codex/catalog/native-models.ts +18 -3
  124. package/src/codex/catalog/parsing.ts +10 -8
  125. package/src/codex/catalog/pinned-models.ts +2 -1
  126. package/src/codex/catalog/provider-models.ts +18 -13
  127. package/src/codex/catalog/retained-sync.ts +2 -1
  128. package/src/codex/catalog/routed-gather.ts +19 -20
  129. package/src/codex/catalog/write-audit.ts +3 -2
  130. package/src/codex/catalog-self-heal.ts +43 -23
  131. package/src/codex/chatgpt-refresh-failure.ts +6 -2
  132. package/src/codex/cli-install-provenance.ts +418 -0
  133. package/src/codex/cli-installation-targets.ts +5 -1
  134. package/src/codex/cli-update-plan.ts +43 -16
  135. package/src/codex/collision-identity.ts +30 -5
  136. package/src/codex/convergence.ts +4 -3
  137. package/src/codex/data/roster-pinned-models.json +177 -1
  138. package/src/codex/desired-state.ts +6 -1
  139. package/src/codex/desktop-app/picker-freshness.ts +10 -8
  140. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  141. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  142. package/src/codex/desktop-compatibility/usage-activation.ts +2 -1
  143. package/src/codex/desktop-compatibility/usage-controller.ts +9 -1
  144. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  145. package/src/codex/inject/config-toml.ts +0 -18
  146. package/src/codex/inject/plan.ts +18 -3
  147. package/src/codex/inject/remove.ts +6 -2
  148. package/src/codex/inject.ts +1 -1
  149. package/src/codex/journal.ts +61 -1
  150. package/src/codex/model-entitlements.ts +1 -1
  151. package/src/codex/native-main-owner.ts +27 -1
  152. package/src/codex/native-profile-store.ts +2 -1
  153. package/src/codex/pool-credit-policy.ts +35 -1
  154. package/src/codex/pool-refresh-backoff.ts +3 -1
  155. package/src/codex/quota-types.ts +3 -0
  156. package/src/codex/quota.ts +24 -4
  157. package/src/codex/role-auto-assign.ts +6 -2
  158. package/src/codex/subagent-defaults.ts +49 -4
  159. package/src/codex/user-identity.ts +35 -6
  160. package/src/codex/windows-current-sid.ts +162 -0
  161. package/src/combos/failover.ts +17 -2
  162. package/src/combos/jev-decision-contract.ts +22 -1
  163. package/src/combos/jev-quota-activation.ts +5 -1
  164. package/src/combos/jev-quota-route.ts +1 -1
  165. package/src/combos/jev-quota.ts +9 -1
  166. package/src/combos/jev-service-exchange.ts +3 -1
  167. package/src/combos/jev-session-pin-config.ts +51 -0
  168. package/src/combos/jev.ts +101 -9
  169. package/src/combos/resolve.ts +45 -1
  170. package/src/combos/types.ts +43 -0
  171. package/src/config/load-degrade.ts +5 -0
  172. package/src/config/paths.ts +19 -3
  173. package/src/config/pending-teardown.ts +22 -1
  174. package/src/config/provider-validation.ts +22 -4
  175. package/src/config/removed-opencode-free.ts +11 -0
  176. package/src/config/schema/leaf-validators.ts +6 -0
  177. package/src/generated/compatibility-version.json +467 -311
  178. package/src/generated/model-metadata.ts +5 -5
  179. package/src/images/loop.ts +16 -2
  180. package/src/integrations/catalog-refresh.ts +1 -1
  181. package/src/integrations/hermes-profiles.ts +251 -0
  182. package/src/integrations/merge.ts +8 -0
  183. package/src/integrations/mutation-plan.ts +19 -4
  184. package/src/integrations/registry.ts +5 -0
  185. package/src/integrations/state.ts +36 -1
  186. package/src/integrations/writer.ts +18 -4
  187. package/src/lib/bun-path-runtime.mjs +2 -1
  188. package/src/lib/decision-quota-sink.ts +10 -0
  189. package/src/lib/errors.ts +62 -0
  190. package/src/lib/eventstream-decoder.ts +81 -37
  191. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  192. package/src/lib/pinned-http.ts +35 -2
  193. package/src/lib/process-control.ts +13 -1
  194. package/src/lib/socks5-fetch.ts +59 -64
  195. package/src/lib/socks5-upload-waiter.ts +50 -0
  196. package/src/lib/sse-decoder.ts +7 -2
  197. package/src/lib/state-store-sweeper.ts +40 -14
  198. package/src/lib/translator-budget.ts +4 -4
  199. package/src/lib/upstream-retry.ts +4 -1
  200. package/src/lib/windows-native-principal-worker.ts +14 -0
  201. package/src/lib/windows-native-principal.ts +188 -0
  202. package/src/lib/windows-secret-acl.ts +39 -3
  203. package/src/lib/windows-user-principal.ts +62 -18
  204. package/src/link/diagnostics.ts +193 -0
  205. package/src/link/relay-auth.ts +6 -0
  206. package/src/link/ssh-config.ts +35 -3
  207. package/src/link/status-projection.ts +39 -0
  208. package/src/link/supervisor.ts +45 -12
  209. package/src/link/tunnel-history.ts +109 -0
  210. package/src/link/tunnel-state.ts +80 -17
  211. package/src/messaging/remote-files.ts +24 -1
  212. package/src/oauth/generic-account-failover.ts +91 -7
  213. package/src/oauth/index.ts +15 -0
  214. package/src/oauth/model-discovery-auth.ts +5 -0
  215. package/src/oauth/store.ts +4 -1
  216. package/src/oauth/token-guardian.ts +7 -0
  217. package/src/oauth/types.ts +9 -0
  218. package/src/oauth/workbuddy.ts +139 -0
  219. package/src/providers/account-quota-disk.ts +12 -4
  220. package/src/providers/antigravity-quota-identity.ts +37 -0
  221. package/src/providers/base-url-choices.ts +8 -5
  222. package/src/providers/codebuddy-models.ts +6 -0
  223. package/src/providers/codex-capacity.ts +3 -1
  224. package/src/providers/derive.ts +51 -3
  225. package/src/providers/kiro-models.ts +3 -0
  226. package/src/providers/mimo-thinking.ts +12 -0
  227. package/src/providers/model-discovery.ts +2 -0
  228. package/src/providers/model-rename-fields.ts +2 -0
  229. package/src/providers/model-rename-migration.ts +10 -0
  230. package/src/providers/openai-sidecar-credit.ts +2 -2
  231. package/src/providers/quota/account-cache.ts +3 -2
  232. package/src/providers/quota/antigravity.ts +25 -14
  233. package/src/providers/quota/report-cache.ts +13 -4
  234. package/src/providers/quota/vendor-probes-key.ts +60 -0
  235. package/src/providers/quota/workbuddy.ts +83 -0
  236. package/src/providers/quota-decision-antigravity.ts +64 -0
  237. package/src/providers/quota-decision-publication.ts +11 -0
  238. package/src/providers/quota-decision-snapshot.ts +21 -4
  239. package/src/providers/quota-types.ts +2 -0
  240. package/src/providers/quota.ts +3 -1
  241. package/src/providers/reasoning-capabilities.ts +76 -0
  242. package/src/providers/registry/entries-core.ts +23 -12
  243. package/src/providers/registry/entries-extended.ts +83 -27
  244. package/src/providers/registry/model-ids.ts +5 -0
  245. package/src/providers/registry/model-seeds.ts +120 -56
  246. package/src/providers/registry/types.ts +29 -2
  247. package/src/providers/resolved-model-policy.ts +30 -10
  248. package/src/providers/routed-config.ts +24 -1
  249. package/src/providers/stale-model-roster-migration.ts +123 -18
  250. package/src/providers/workbuddy-credit-balance.ts +81 -0
  251. package/src/providers/workbuddy-models.ts +37 -0
  252. package/src/providers/workbuddy.ts +60 -0
  253. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  254. package/src/responses/compaction-summary.ts +45 -0
  255. package/src/responses/muse-tool-name-alias.ts +1 -2
  256. package/src/responses/parser.ts +3 -2
  257. package/src/responses/reasoning-replay-cache.ts +18 -14
  258. package/src/responses/schema.ts +1 -0
  259. package/src/responses/thought-signature-replay.ts +10 -2
  260. package/src/router.ts +2 -0
  261. package/src/routing/analytics.ts +2 -3
  262. package/src/routing/capability.ts +8 -2
  263. package/src/routing/fallback-policy.ts +3 -3
  264. package/src/routing/history/ingest.ts +28 -3
  265. package/src/server/auth-cors.ts +4 -2
  266. package/src/server/chat-completions.ts +21 -1
  267. package/src/server/chat-native-eligibility.ts +7 -0
  268. package/src/server/chat-native-reasoning.ts +24 -7
  269. package/src/server/chat-native.ts +13 -2
  270. package/src/server/claude-messages.ts +3 -0
  271. package/src/server/direct-local-http.ts +5 -2
  272. package/src/server/effort-policy.ts +5 -1
  273. package/src/server/index/link-relay-sessions.ts +9 -5
  274. package/src/server/index/live-sideband.ts +18 -15
  275. package/src/server/index/optional-listeners.ts +4 -0
  276. package/src/server/index/serve-options.ts +5 -4
  277. package/src/server/local-management-read-client.ts +3 -1
  278. package/src/server/management/agent-settings-routes.ts +27 -15
  279. package/src/server/management/combo-routes.ts +14 -4
  280. package/src/server/management/config-routes.ts +2 -2
  281. package/src/server/management/decision-discovery.ts +12 -2
  282. package/src/server/management/hermes-profile-routes.ts +156 -0
  283. package/src/server/management/integration-routes.ts +85 -24
  284. package/src/server/management/link-routes.ts +5 -2
  285. package/src/server/management/model-routes.ts +2 -2
  286. package/src/server/management/model-row-export-metadata.ts +25 -6
  287. package/src/server/management/model-rows.ts +15 -20
  288. package/src/server/management/native-integration-routes.ts +11 -8
  289. package/src/server/management/provider-routes.ts +1 -1
  290. package/src/server/management/route-registry.ts +4 -0
  291. package/src/server/management-api.ts +5 -0
  292. package/src/server/models-capabilities.ts +21 -3
  293. package/src/server/port-reclaim.ts +51 -9
  294. package/src/server/request-log-conversation.ts +49 -0
  295. package/src/server/request-log.ts +2 -0
  296. package/src/server/responses/adapter-delivery.ts +11 -1
  297. package/src/server/responses/adapter-dispatch.ts +2 -2
  298. package/src/server/responses/anthropic-thinking-recovery.ts +1 -0
  299. package/src/server/responses/codex-ws-exchange.ts +39 -9
  300. package/src/server/responses/codex-ws-session.ts +38 -4
  301. package/src/server/responses/codex-ws-wire.ts +6 -1
  302. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  303. package/src/server/responses/combo-stream-preflight.ts +8 -1
  304. package/src/server/responses/compact.ts +14 -5
  305. package/src/server/responses/context-overflow.ts +8 -1
  306. package/src/server/responses/core-combo-failure.ts +10 -0
  307. package/src/server/responses/core-combo.ts +74 -44
  308. package/src/server/responses/core-lifetime.ts +5 -2
  309. package/src/server/responses/core-normalize.ts +17 -4
  310. package/src/server/responses/core-opaque-recovery.ts +1 -0
  311. package/src/server/responses/core-options.ts +7 -0
  312. package/src/server/responses/core-replay.ts +2 -1
  313. package/src/server/responses/jev-combo-choice.ts +39 -0
  314. package/src/server/responses/jev-session-pin.ts +203 -0
  315. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  316. package/src/server/responses/passthrough-delivery.ts +44 -2
  317. package/src/server/responses/policy-fallback.ts +6 -1
  318. package/src/server/responses/request-compression.ts +12 -7
  319. package/src/server/responses/request-prepare.ts +32 -7
  320. package/src/server/responses/request-sidecar-auth.ts +2 -0
  321. package/src/server/responses/request-transport.ts +25 -6
  322. package/src/server/responses/response-effects.ts +22 -10
  323. package/src/server/responses/run-turn-execution.ts +2 -4
  324. package/src/server/responses/sidecar-execution.ts +13 -7
  325. package/src/server/responses-phase-inference.ts +267 -0
  326. package/src/server/sse-payload-rewrite.ts +14 -1
  327. package/src/server/stop-teardown.ts +36 -1
  328. package/src/server/ws-bridge.ts +1 -1
  329. package/src/service/definition.ts +20 -8
  330. package/src/service/desktop-supervision.d.mts +7 -4
  331. package/src/service/desktop-supervision.mjs +90 -13
  332. package/src/service/ownership-mutation-lease.mjs +21 -7
  333. package/src/types/config.ts +14 -2
  334. package/src/types/provider.ts +29 -7
  335. package/src/types/request.ts +11 -0
  336. package/src/types/wire.ts +1 -0
  337. package/src/types.ts +1 -0
  338. package/src/update/bind-probe.ts +29 -0
  339. package/src/update/codex-cli-update-launch-policy.d.mts +9 -0
  340. package/src/update/codex-cli-update-launch-policy.mjs +30 -0
  341. package/src/update/job.ts +10 -29
  342. package/src/update/npm-install-job.ps1 +173 -0
  343. package/src/update/npm-install.mjs +70 -0
  344. package/src/update/stop-contract.d.mts +1 -0
  345. package/src/update/stop-contract.mjs +14 -0
  346. package/src/update/stop-decision.d.mts +1 -1
  347. package/src/update/stop-decision.mjs +13 -3
  348. package/src/update/teardown-handover.ts +166 -0
  349. package/src/update/transactional-install.d.mts +14 -3
  350. package/src/update/transactional-install.mjs +33 -7
  351. package/src/usage/expected-prices.ts +64 -31
  352. package/src/usage/jev-stats.ts +54 -14
  353. package/src/usage/timeline.ts +19 -9
  354. package/src/vision/eligibility.ts +15 -5
  355. package/src/vision/plan.ts +2 -2
  356. package/src/web-search/loop.ts +16 -2
  357. package/gui/dist/assets/App-nZ34cR5G.js +0 -58
  358. package/gui/dist/assets/index-DGXS51sp.js +0 -94
  359. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
  360. package/gui/dist/assets/quota-summary-DO1Sx5TM.js +0 -1
package/src/cli/status.ts CHANGED
@@ -715,12 +715,34 @@ export function resolveStatusPid(
715
715
  * unused", but startupHealthSummary already renders both as AT RISK with a
716
716
  * remedy command, and `custom-remote` is a deliberate operator choice. Warning
717
717
  * on all four would teach operators to skip the line that matters.
718
+ *
719
+ * A connected client (hub client or Remote Link Child) needs a different remedy (#7563): its
720
+ * runtime never writes Codex routing on start, so `ocx start` cannot re-point it — with the
721
+ * proxy up it only answers "already running". `ocx sync --restart-codex` writes the routing
722
+ * and restarts Codex. A client whose proxy is also down is told to start it first, because
723
+ * nothing else in the not-running report mentions that its routing is native.
718
724
  */
719
725
  export function unusedProxyWarningLines(input: {
720
726
  proxyUp: boolean;
721
727
  routingKind: StartupHealth["routingKind"];
728
+ connectedClient?: { transport: "hub" | "link"; serviceInstalled: boolean };
722
729
  }): string[] {
723
- if (!input.proxyUp || input.routingKind !== "native") return [];
730
+ if (input.routingKind !== "native") return [];
731
+ const client = input.connectedClient;
732
+ if (client) {
733
+ const peer = client.transport === "link" ? "the Home" : "the hub";
734
+ if (input.proxyUp) {
735
+ return [
736
+ "⚠️ Codex routing is native — this client's proxy is unused.",
737
+ ` Codex requests go to OpenAI, not ${peer}. Re-point with: ocx sync --restart-codex`,
738
+ ];
739
+ }
740
+ return [
741
+ `⚠️ Codex routing is native, so Codex requests go to OpenAI, not ${peer}.`,
742
+ ` Start this client's proxy with '${client.serviceInstalled ? "ocx service start" : "ocx start"}', then re-point with: ocx sync --restart-codex`,
743
+ ];
744
+ }
745
+ if (!input.proxyUp) return [];
724
746
  return [
725
747
  "⚠️ Codex routing is native — the running proxy is unused.",
726
748
  " Codex requests go to OpenAI, not this proxy. Re-point with: ocx start",
@@ -746,11 +768,47 @@ export function unusedProxyWarningLines(input: {
746
768
  export function deadProxyRoutingAdviceLines(input: {
747
769
  proxyUp: boolean;
748
770
  routingKind: StartupHealth["routingKind"];
771
+ /** #7563: on a connected client nothing but `ocx sync` writes the routing back after a restore. */
772
+ connectedClient?: boolean;
749
773
  }): string[] {
750
774
  if (input.proxyUp || input.routingKind !== "opencodex-local") return [];
751
775
  return [
752
776
  "Codex is still pointed at this proxy, so sign-in and model requests both fail while it is down.",
753
777
  "To hand Codex back to its own account and endpoints without starting anything: ocx restore",
778
+ ...(input.connectedClient ? ["After a restore, 'ocx sync --restart-codex' points Codex back at this client."] : []),
779
+ ];
780
+ }
781
+
782
+ type StatusRoutingView = Pick<CliStatusJson, "proxy" | "startup" | "remoteHub" | "connection">;
783
+
784
+ export function statusProxyUp(json: StatusRoutingView): boolean {
785
+ return json.remoteHub.connected && json.connection.transport === "link"
786
+ ? json.proxy.health.ok : Boolean(json.proxy.pid || json.proxy.health.ok);
787
+ }
788
+
789
+ /** `unusedProxyWarningLines` for the human `ocx status` report, role taken from the report itself. */
790
+ export function statusUnusedProxyLines(json: StatusRoutingView): string[] {
791
+ return unusedProxyWarningLines({
792
+ proxyUp: statusProxyUp(json),
793
+ routingKind: json.startup.routingKind,
794
+ ...(json.remoteHub.connected ? { connectedClient: {
795
+ transport: json.connection.transport === "link" ? "link" as const : "hub" as const,
796
+ serviceInstalled: json.startup.serviceInstalled && !json.startup.serviceConflict,
797
+ } } : {}),
798
+ });
799
+ }
800
+
801
+ /** `deadProxyRoutingAdviceLines` for the not-running half of the human `ocx status` report. */
802
+ export function statusDeadProxyLines(json: StatusRoutingView): string[] {
803
+ return [
804
+ json.startup.routingKind === "native"
805
+ ? "↳ Not running — Claude requests will fail with connection errors."
806
+ : "↳ Not running — Codex/Claude requests will fail with connection errors.",
807
+ ...deadProxyRoutingAdviceLines({
808
+ proxyUp: false,
809
+ routingKind: json.startup.routingKind,
810
+ connectedClient: json.remoteHub.connected,
811
+ }),
754
812
  ];
755
813
  }
756
814
 
@@ -1,6 +1,119 @@
1
1
  import { restoreNativeCodexAsync } from "../codex/inject";
2
2
  import type { RetainedCodexProviderTable } from "../codex/inject/restore";
3
3
  import { stripGrokConfig } from "../grok/inject";
4
+ import { readClientConnectionState, type ClientConnectionState } from "../client/state";
5
+ import { readPid, readRuntimePort } from "../config/process-state";
6
+ import { loadConfig } from "../config";
7
+ import { configuredAdminToken } from "../lib/admin-secrets";
8
+ import { readBoundedResponseBody } from "../lib/bounded-body";
9
+ import { gracefulStopHost, isProcessAlive, ProxyOwnershipRefusedError } from "../lib/process-control";
10
+ import { directLocalHttpFetch } from "../server/direct-local-http";
11
+ import { findLiveProxy, probeEndpointLiveness, proveLiveProxyOwnedByHome } from "../server/proxy-liveness";
12
+ import { observeGuardedManagerStopped } from "../service/guarded-manager-target";
13
+ import type { StartExitTeardown } from "./dispatch";
14
+ import type { StopOutcome } from "./stop-report";
15
+
16
+ /** Re-read ownership when an ordinary runtime actually exits, including after API drain. */
17
+ export function preserveConnectedClientRoutingOnExit(teardown: StartExitTeardown): StartExitTeardown {
18
+ return readClientConnectionState().kind === "connected"
19
+ ? { ...teardown, restoreNativeCodex: false, stripGrokConfig: false }
20
+ : teardown;
21
+ }
22
+
23
+ type ConnectedStopTarget = { pid: number; port: number; hostname?: string };
24
+ const CONNECTED_STOP_PROBE_MS = 2000;
25
+ const unsupportedConnectedStop = () => new ProxyOwnershipRefusedError(
26
+ "Connected-client stop refused: runtime identity, shutdown preservation or safe runtime absence could not be verified. Inspect 'ocx service status' and update/restart an incompatible runtime through its supervisor, then retry; use 'ocx disconnect' only if you intend to release those integrations.",
27
+ "connected_client_stop_unsupported",
28
+ );
29
+
30
+ /** A positive, PID-bound contract is required; old and new builds may share a version. */
31
+ export async function assertConnectedClientStopSupported(target: ConnectedStopTarget | null): Promise<void> {
32
+ if (!target) throw unsupportedConnectedStop();
33
+ if (!isProcessAlive(target.pid)) return; // A manager may already have ended this exact target.
34
+ const origin = `http://${gracefulStopHost(target.hostname)}:${target.port}`;
35
+ const signal = AbortSignal.timeout(CONNECTED_STOP_PROBE_MS);
36
+ const probe = async (path: string, authenticated: boolean): Promise<Record<string, unknown> | null> => {
37
+ try {
38
+ const headers: Record<string, string> = {};
39
+ if (authenticated) {
40
+ const token = configuredAdminToken(process.env.OPENCODEX_HOME?.trim() || undefined, process.env);
41
+ if (token) headers["x-opencodex-api-key"] = token;
42
+ }
43
+ const response = await directLocalHttpFetch(`${origin}${path}`, { method: "GET", headers, redirect: "error", signal },
44
+ { timeoutMs: CONNECTED_STOP_PROBE_MS });
45
+ if (!response.ok) { void response.body?.cancel().catch(() => {}); return null; }
46
+ const body = await readBoundedResponseBody(response, { maxBytes: 4096, signal, fatalUtf8: true });
47
+ if (body.truncated) return null;
48
+ const parsed: unknown = JSON.parse(body.text);
49
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
50
+ } catch { return null; }
51
+ };
52
+ const health = await probe("/healthz", false);
53
+ // The native machine listener has always preserved integrations on signal and 404s /api/stop.
54
+ if (health?.service === "opencodex" && health.role === "client" && health.pid === target.pid) return;
55
+ const capability = await probe("/api/stop", true);
56
+ if (capability?.schema === "ocx-stop-capabilities/1"
57
+ && capability.pid === target.pid && capability.connectedClientOwnership === true) return;
58
+ throw unsupportedConnectedStop();
59
+ }
60
+
61
+ /** Fail before either service-manager path, including a manager that cascades process exit. */
62
+ export async function preflightConnectedClientStop(approved?: ConnectedStopTarget): Promise<StopOutcome | "already-stopped" | null> {
63
+ try {
64
+ let target = approved;
65
+ if (!target) {
66
+ const pid = readPid();
67
+ const runtime = readRuntimePort(pid ?? undefined);
68
+ if (pid && isProcessAlive(pid)) {
69
+ if (!runtime) throw unsupportedConnectedStop();
70
+ target = { ...runtime, pid };
71
+ }
72
+ else {
73
+ const live = await findLiveProxy({ acceptPackageTreeFenced: true });
74
+ if (live?.pid) {
75
+ if (await proveLiveProxyOwnedByHome(live) !== "proven") throw unsupportedConnectedStop();
76
+ target = { ...live, pid: live.pid };
77
+ } else {
78
+ const config = loadConfig();
79
+ const endpoints = [...(runtime ? [runtime] : []), { port: config.port, hostname: config.hostname }];
80
+ if (endpoints.some(endpoint => !Number.isInteger(endpoint.port) || endpoint.port <= 0 || endpoint.port > 65535)
81
+ || await observeGuardedManagerStopped({ kind: "absent" }) !== "inactive") throw unsupportedConnectedStop();
82
+ for (const endpoint of endpoints) {
83
+ if (await probeEndpointLiveness(endpoint) !== "dead") throw unsupportedConnectedStop();
84
+ }
85
+ return "already-stopped";
86
+ }
87
+ }
88
+ }
89
+ if (!isProcessAlive(target.pid)) throw unsupportedConnectedStop();
90
+ await assertConnectedClientStopSupported(target);
91
+ return null;
92
+ } catch {
93
+ const error = unsupportedConnectedStop();
94
+ console.error(error.message);
95
+ process.exitCode = 1;
96
+ return { ok: false, summary: { schema: "ocx-stop/1", ok: false, outcome: "failed", exitCode: 1,
97
+ runtimeDown: false, service: "absent", proxy: "ownership-refused", sharedTeardown: "skipped", message: error.message } };
98
+ }
99
+ }
100
+
101
+ /**
102
+ * The line `ocx stop` prints in place of the shared teardown on a connected client, or null
103
+ * when this home is not one (#7563).
104
+ *
105
+ * A hub client or Remote Link Child gets its Codex routing and catalog from `ocx connect` /
106
+ * `ocx sync`, and its client runtime never writes them on start. The standalone teardown
107
+ * restored native Codex, rewrote the catalog and stripped the Grok block, and nothing on the
108
+ * client put any of it back: `ocx start` brought the runtime up with Codex still native and
109
+ * Grok unconfigured. Leaving them in place makes stop/start a round trip; `ocx disconnect`
110
+ * remains the teardown that owns them, with its own ownership checks.
111
+ */
112
+ export function connectedClientStopSkipLine(state: ClientConnectionState): string | null {
113
+ if (state.kind !== "connected") return null;
114
+ const role = state.value.transport === "link" ? "Remote Link Child" : "hub client";
115
+ return `↩️ Codex routing, its catalog and the Grok config stay as they are: this ${role}'s connection owns them, and 'ocx start' serves them again. To hand Codex back to its own account, run 'ocx disconnect'.`;
116
+ }
4
117
 
5
118
  /**
6
119
  * Restore shared client state after a stop.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `ocx sync --expect-link <linkId>` / `--expect-hub-key <apiKeyId>` (#7694): argument parsing and
3
+ * the refusal report. The check itself runs under the client locks in
4
+ * `src/client/sync-expectation.ts`; this module only turns argv into an expectation and a
5
+ * mismatch into the documented exit code and stderr lines.
6
+ */
7
+ import type { ClientSyncExpectation } from "../client/sync-expectation";
8
+
9
+ /** Exit code of a refused expectation: the machine is not in the state the caller named. */
10
+ export const SYNC_EXPECTATION_MISMATCH_EXIT = 5;
11
+ export const SYNC_EXPECTATION_USAGE_EXIT = 2;
12
+
13
+ const LINK_ID = /^lnk_[0-9a-f]{16}$/;
14
+ const FLAGS = ["--expect-link", "--expect-hub-key"] as const;
15
+
16
+ export type ParsedSyncExpectation =
17
+ | { ok: true; expectation?: ClientSyncExpectation }
18
+ | { ok: false; message: string };
19
+
20
+ /** Reads both flags in `--flag value` or `--flag=value` form; any doubt is a usage error. */
21
+ export function parseSyncExpectation(args: readonly string[]): ParsedSyncExpectation {
22
+ const found: { flag: typeof FLAGS[number]; value: string | undefined }[] = [];
23
+ for (let index = 0; index < args.length; index += 1) {
24
+ const arg = args[index]!;
25
+ for (const flag of FLAGS) {
26
+ if (arg === flag) {
27
+ const next = args[index + 1];
28
+ found.push({ flag, value: next === undefined || next.startsWith("--") ? undefined : next });
29
+ if (next !== undefined && !next.startsWith("--")) index += 1;
30
+ } else if (arg.startsWith(`${flag}=`)) {
31
+ found.push({ flag, value: arg.slice(flag.length + 1) });
32
+ }
33
+ }
34
+ }
35
+ if (found.length === 0) return { ok: true };
36
+ if (found.length > 1) {
37
+ return { ok: false, message: "ocx sync accepts one --expect-link or --expect-hub-key, given once." };
38
+ }
39
+ const [{ flag, value }] = found as [typeof found[number]];
40
+ if (flag === "--expect-link") {
41
+ if (value === undefined || !LINK_ID.test(value)) {
42
+ return { ok: false, message: "--expect-link needs a link id of the form lnk_ followed by 16 hex digits (see ocx connect status --json)." };
43
+ }
44
+ return { ok: true, expectation: { kind: "link", linkId: value } };
45
+ }
46
+ if (value === undefined || value.trim() === "" || value.trim() !== value || value.length > 256) {
47
+ return { ok: false, message: "--expect-hub-key needs the connected API key id (see ocx connect status --json)." };
48
+ }
49
+ return { ok: true, expectation: { kind: "hub", apiKeyId: value } };
50
+ }
51
+
52
+ /** A refusal prints one human line, then one JSON line a caller can parse as the last stderr line. */
53
+ export function reportSyncExpectationMismatch(
54
+ error: { phase: string; reason: string },
55
+ log: Pick<Console, "error">,
56
+ ): number {
57
+ log.error(`Sync refused (${error.phase}: ${error.reason}); nothing was changed and local providers were not synced.`);
58
+ log.error(JSON.stringify({ phase: error.phase, reason: error.reason }));
59
+ return SYNC_EXPECTATION_MISMATCH_EXIT;
60
+ }
@@ -1,10 +1,12 @@
1
+ import { basename, dirname } from "node:path";
1
2
  import type { ExportModel } from "../clients/config-export";
2
3
  import { guardAsideProfileIO, listAsideProfiles } from "../clients/aside-profiles";
3
4
  import { loadConfig } from "../config";
4
5
  import { listAsideProfileStores } from "../integrations/aside-profile-context";
6
+ import { hermesProfileBoundary, listHermesProfileStores } from "../integrations/hermes-profiles";
5
7
  import { isIntegrationClientId, type IntegrationClientId } from "../integrations/registry";
6
8
  import { createIntegrationStateStore, type IntegrationStateStore } from "../integrations/store";
7
- import { disableIntegrationCoordinated, type WriteOutcome } from "../integrations/writer";
9
+ import { disableIntegrationCoordinated, type CoordinatedIntegrationOptions, type WriteOutcome } from "../integrations/writer";
8
10
  import { loadExportModels } from "../server/management/model-rows";
9
11
  import type { OcxConfig } from "../types";
10
12
 
@@ -12,7 +14,7 @@ export interface UninstallIntegrationCleanupDeps {
12
14
  createStore: () => IntegrationStateStore;
13
15
  loadConfig: () => OcxConfig;
14
16
  loadModels: (config: OcxConfig) => Promise<ExportModel[]>;
15
- disable: (input: Parameters<typeof disableIntegrationCoordinated>[0]) => Promise<WriteOutcome>;
17
+ disable: (input: Parameters<typeof disableIntegrationCoordinated>[0], options?: CoordinatedIntegrationOptions) => Promise<WriteOutcome>;
16
18
  env?: NodeJS.ProcessEnv;
17
19
  home?: string;
18
20
  }
@@ -21,7 +23,7 @@ const defaults: UninstallIntegrationCleanupDeps = {
21
23
  createStore: () => createIntegrationStateStore(),
22
24
  loadConfig,
23
25
  loadModels: config => loadExportModels(config),
24
- disable: input => disableIntegrationCoordinated(input),
26
+ disable: (input, options) => disableIntegrationCoordinated(input, options),
25
27
  };
26
28
 
27
29
  export interface UninstallIntegrationCleanupResult {
@@ -46,7 +48,7 @@ export async function cleanupOwnedIntegrationsBeforeUninstall(
46
48
  }
47
49
  }
48
50
  type CleanupTarget = Pick<Parameters<typeof disableIntegrationCoordinated>[0], "clientId" | "store" | "io" | "resolvedPaths">
49
- & { store: IntegrationStateStore; profileId?: number };
51
+ & { store: IntegrationStateStore; profileId?: number; guard?: CoordinatedIntegrationOptions["guard"] };
50
52
  const targets: CleanupTarget[] = (rawIds as IntegrationClientId[]).sort()
51
53
  .map(clientId => ({ clientId, store }));
52
54
  // Read every child before any mutation. A broken child must not look like no ownership.
@@ -57,6 +59,38 @@ export async function cleanupOwnedIntegrationsBeforeUninstall(
57
59
  }
58
60
  if (childRecords.aside) targets.push({ clientId: "aside", ...child });
59
61
  }
62
+ // Named Hermes profiles keep their own stores (#7674). The record names the file we wrote; it
63
+ // must be that profile's config.yaml, so a record cannot aim this disable at any other file.
64
+ for (const child of listHermesProfileStores(store)) {
65
+ const childRecords = child.store.readRecordsStrict();
66
+ if (Object.keys(childRecords).some(id => id !== "hermes")) {
67
+ throw new Error("integration cleanup refused: Hermes profile storage names another client");
68
+ }
69
+ const configPath = childRecords.hermes?.configPath;
70
+ if (configPath === undefined) continue;
71
+ const profileHome = dirname(configPath);
72
+ if (basename(configPath) !== "config.yaml" || basename(profileHome) !== child.name
73
+ || basename(dirname(profileHome)) !== "profiles") {
74
+ throw new Error("integration cleanup refused: Hermes profile ownership is mismatched");
75
+ }
76
+ // Pinned now, before any await, and checked again inside the disable itself: a profile or
77
+ // `profiles` directory swapped for a link while models load cannot redirect this cleanup.
78
+ let holds: () => void;
79
+ try { holds = hermesProfileBoundary({ name: child.name, home: profileHome, configPath }, child.store); }
80
+ catch (error) {
81
+ throw new Error(`integration cleanup refused for Hermes profile ${child.name}: ${error instanceof Error ? error.message : String(error)}`);
82
+ }
83
+ targets.push({
84
+ clientId: "hermes", store: child.store, resolvedPaths: { configPath, detectDir: profileHome },
85
+ guard: () => {
86
+ try { holds(); return null; }
87
+ catch (error) {
88
+ return { ok: false, reason: "unsafe", state: "unsafe", clientId: "hermes",
89
+ message: error instanceof Error ? error.message : "Hermes profile cannot be changed safely" };
90
+ }
91
+ },
92
+ });
93
+ }
60
94
  if (targets.length === 0) return { attempted: 0, changed: 0 };
61
95
 
62
96
  const asideTargets = targets.filter(target => target.clientId === "aside");
@@ -85,7 +119,7 @@ export async function cleanupOwnedIntegrationsBeforeUninstall(
85
119
  const config = deps.loadConfig();
86
120
  const models = await deps.loadModels(config);
87
121
  let changed = 0;
88
- for (const { clientId, store: targetStore, io, resolvedPaths } of targets) {
122
+ for (const { clientId, store: targetStore, io, resolvedPaths, guard } of targets) {
89
123
  const result = await deps.disable({
90
124
  clientId,
91
125
  models,
@@ -96,7 +130,7 @@ export async function cleanupOwnedIntegrationsBeforeUninstall(
96
130
  ...(resolvedPaths ? { resolvedPaths } : {}),
97
131
  ...(deps.env ? { env: deps.env } : {}),
98
132
  ...(deps.home ? { home: deps.home } : {}),
99
- });
133
+ }, guard ? { guard } : undefined);
100
134
  if (!result.ok) {
101
135
  throw new Error(`integration cleanup refused for ${clientId}: ${result.message}`
102
136
  + (result.residual ? "; recovery did not complete; inspect the client file and retained snapshots before retrying" : ""));
@@ -107,7 +141,7 @@ export async function cleanupOwnedIntegrationsBeforeUninstall(
107
141
  if (result.changed) changed++;
108
142
  }
109
143
  // A profile can gain ownership while catalog loading or an earlier disable awaited its lock.
110
- if ([store, ...listAsideProfileStores(store).map(child => child.store)]
144
+ if ([store, ...listAsideProfileStores(store).map(child => child.store), ...listHermesProfileStores(store).map(child => child.store)]
111
145
  .some(current => Object.keys(current.readRecordsStrict()).length > 0)) {
112
146
  throw new Error("integration cleanup refused: ownership changed before removal");
113
147
  }
@@ -8,7 +8,11 @@ import { readClientConnectionState, sameClientConnectionOwner } from "../client/
8
8
  import { fetchHubUsage } from "../client/hub-client";
9
9
  import { readServiceApiTokenState, serviceApiTokenFingerprint } from "../lib/service-secrets";
10
10
  import { runningProxyUpdateHeaders } from "../oauth/login-cli";
11
+ import { readRuntimePort, type RuntimePortState } from "../config/process-state";
12
+ import { isLocalAttestationSecret } from "../lib/local-management-attestation";
11
13
  import { redactSecretString } from "../lib/redact";
14
+ import { findLiveProxy, probeHostname } from "../server/proxy-liveness";
15
+ import { fetchBoundLocalManagementRead, type LocalManagementReadDeps } from "../server/local-management-read-client";
12
16
  import { rangeWindow, USAGE_SURFACES } from "../usage/summary";
13
17
  import type { UsageTimeWindow } from "../usage/time-range";
14
18
  import {
@@ -16,8 +20,7 @@ import {
16
20
  printData,
17
21
  rejectArgs,
18
22
  RuntimeApiError,
19
- runtimeRequest,
20
- runtimeBaseUrl,
23
+ PROXY_NOT_RUNNING_MESSAGE,
21
24
  takeFlag,
22
25
  takeOption,
23
26
  takeOptionWithSyntax,
@@ -29,7 +32,10 @@ export const USAGE_COMPARE_USAGE = `Usage:
29
32
  [--provider <name>] [--model <id>] [--api-key-id <id>] [--json]`;
30
33
 
31
34
  export type CompareRange = "today" | "7d" | "30d";
32
- export type UsageCompareDeps = RuntimeApiDeps & { now?: () => number };
35
+ export type UsageCompareDeps = RuntimeApiDeps & Pick<LocalManagementReadDeps, "directFetch"> & {
36
+ now?: () => number;
37
+ readRuntime?: typeof readRuntimePort;
38
+ };
33
39
 
34
40
  const METRICS = ["requests", "totalTokens", "inputTokens", "outputTokens", "cachedInputTokens", "estimatedCostUsd"] as const;
35
41
  type Metric = typeof METRICS[number];
@@ -189,10 +195,60 @@ function captureUsageOwner() {
189
195
  const headers = runningProxyUpdateHeaders();
190
196
  const fingerprint = connection.kind === "connected" ? connection.value.tokenFingerprint
191
197
  : serviceApiTokenFingerprint(headers.get("X-OpenCodex-API-Key") ?? "");
192
- return { connection, token, headers, fingerprint };
198
+ return { connection, token, fingerprint };
193
199
  }
194
200
  type UsageOwner = ReturnType<typeof captureUsageOwner>;
195
201
 
202
+ function pinUsageRuntime(deps: UsageCompareDeps, owner: UsageOwner): (suffix: string) => Promise<ScopedUsage> {
203
+ const readRuntime = deps.readRuntime ?? readRuntimePort;
204
+ const initial = readRuntimePortForComparison();
205
+ const pinned = { ...initial };
206
+ let liveIdentity: string | undefined;
207
+ function readRuntimePortForComparison(): RuntimePortState {
208
+ const runtime = readRuntime();
209
+ if (!runtime || !isLocalAttestationSecret(runtime.attestationSecret)) {
210
+ throw new Error("Usage runtime unavailable: restart the proxy with an attested runtime record.");
211
+ }
212
+ return runtime;
213
+ }
214
+ function assertRuntime(): RuntimePortState {
215
+ const current = readRuntimePortForComparison();
216
+ if (current.pid !== pinned.pid || current.port !== pinned.port || current.hostname !== pinned.hostname
217
+ || current.attestationSecret !== pinned.attestationSecret) {
218
+ throw new Error("Usage runtime changed during comparison; no comparison was produced. Retry for the current runtime.");
219
+ }
220
+ return current;
221
+ }
222
+ return async suffix => {
223
+ assertRuntime();
224
+ const live = await (deps.findLiveProxy ?? findLiveProxy)();
225
+ assertRuntime();
226
+ assertUsageOwner(owner);
227
+ if (!live) throw new RuntimeApiError(PROXY_NOT_RUNNING_MESSAGE, 503, null, "proxy_not_running");
228
+ const identity = JSON.stringify([live.pid, live.port, live.hostname, live.source, live.role]);
229
+ if (live.source !== "runtime" || live.pid !== pinned.pid || live.port !== pinned.port
230
+ || probeHostname(live.hostname) !== probeHostname(pinned.hostname) || live.role === "client"
231
+ || (liveIdentity !== undefined && liveIdentity !== identity)) {
232
+ throw new Error("Usage runtime changed during comparison; no comparison was produced. Retry for the current runtime.");
233
+ }
234
+ liveIdentity = identity;
235
+ const read = await fetchBoundLocalManagementRead(live, `/api/usage?${suffix.replace(/^\?/, "")}`, {
236
+ fetchImpl: deps.fetchImpl, directFetch: deps.directFetch, readRuntime: assertRuntime,
237
+ timeoutMs: 60_000, requireResponseProof: true,
238
+ });
239
+ assertRuntime();
240
+ if (read.kind === "unavailable") {
241
+ throw new RuntimeApiError(`Local usage read unavailable (${read.reason}). No comparison was produced.`, 503, null);
242
+ }
243
+ if (!read.response.ok) {
244
+ throw new RuntimeApiError(`Usage request failed (HTTP ${read.response.status}). No comparison was produced.`, read.response.status, null);
245
+ }
246
+ const result = await read.response.json() as ScopedUsage;
247
+ assertRuntime();
248
+ return result;
249
+ };
250
+ }
251
+
196
252
  function assertUsageOwner(owner: UsageOwner): void {
197
253
  const current = readClientConnectionState();
198
254
  const expected = owner.connection;
@@ -216,6 +272,7 @@ async function readUsage(
216
272
  apiKeyId: string | undefined,
217
273
  deps: RuntimeApiDeps,
218
274
  owner: UsageOwner,
275
+ localRead?: (suffix: string) => Promise<ScopedUsage>,
219
276
  ): Promise<ScopedUsage> {
220
277
  assertUsageOwner(owner);
221
278
  const { connection, token } = owner;
@@ -233,16 +290,15 @@ async function readUsage(
233
290
  result = await fetchHubUsage(connection.value.serverUrl, token.token, new URLSearchParams(suffix.replace(/^\?/, "")), {
234
291
  fetchImpl: peerFetch, timeoutMs: 60_000, ...(link ? { peer: "Home" as const } : {}),
235
292
  });
236
- } else if (apiKeyId === undefined) {
237
- result = await runtimeRequest(`/api/usage${suffix}`, { headers: owner.headers }, deps);
238
293
  } else {
239
294
  try {
240
- result = await runtimeRequest(`/api/usage${suffix}`, { redirect: "error", credentials: "omit", headers: owner.headers }, deps);
295
+ result = await localRead!(suffix);
241
296
  } catch (error) {
242
- if (error instanceof RuntimeApiError && error.code === "proxy_not_running") throw error;
297
+ if (apiKeyId === undefined) throw error;
298
+ if (error instanceof RuntimeApiError) throw error;
243
299
  throw new Error("Key-scoped usage could not be read. Check runtime access and retry.");
244
300
  }
245
- if (result.filter?.apiKeyId !== apiKeyId) {
301
+ if (apiKeyId !== undefined && result.filter?.apiKeyId !== apiKeyId) {
246
302
  throw new Error("The server did not confirm the requested API key scope. Upgrade and restart the proxy, then retry.");
247
303
  }
248
304
  }
@@ -276,9 +332,9 @@ export async function handleUsageCompareCommand(argv: string[], deps: UsageCompa
276
332
  const windows = compareUsageWindows(range, now);
277
333
  const filters = { range, surface, provider, model, apiKeyId };
278
334
  const owner = captureUsageOwner();
279
- const readDeps = owner.connection.kind === "disconnected" ? { ...deps, baseUrl: await runtimeBaseUrl(deps) } : deps;
280
- const currentReport = await readUsage(query({ ...filters, since: windows.current.since, until: windows.current.until }), windows.current, apiKeyId, readDeps, owner);
281
- const previousReport = await readUsage(query({ ...filters, since: windows.previous.since, until: windows.previous.until }), windows.previous, apiKeyId, readDeps, owner);
335
+ const localRead = owner.connection.kind === "disconnected" ? pinUsageRuntime(deps, owner) : undefined;
336
+ const currentReport = await readUsage(query({ ...filters, since: windows.current.since, until: windows.current.until }), windows.current, apiKeyId, deps, owner, localRead);
337
+ const previousReport = await readUsage(query({ ...filters, since: windows.previous.since, until: windows.previous.until }), windows.previous, apiKeyId, deps, owner, localRead);
282
338
  const current = totalsOf(currentReport);
283
339
  const previous = totalsOf(previousReport);
284
340
  const deltaTotals: Totals = {};
@@ -74,6 +74,9 @@ import {
74
74
  assertNoClientDisconnectPending, assertClientConnectionUnchanged, sameClientConnectionOwner,
75
75
  } from "./state";
76
76
  import { assertClientCatalogCompatible, type CatalogCompatibilityDeps } from "./catalog-compatibility";
77
+ import {
78
+ assertClientSyncExpectation, ClientSyncExpectationError, isClientSyncLockBusy, type ClientSyncExpectation,
79
+ } from "./sync-expectation";
77
80
  import { overlayHomeCodexSettings } from "../link/codex-settings";
78
81
  import {
79
82
  clearHomeCodexSettingsRecord,
@@ -840,6 +843,21 @@ export interface ConnectedSyncResult {
840
843
  appliedRecord?: HomeCodexSettingsRecord;
841
844
  /** The Home's settings were injected but their record could not be written (OCX-6). */
842
845
  applyRecordFailed?: true;
846
+ /**
847
+ * The connection this sync ran under, read inside its lock and compare-and-swapped on every
848
+ * write. Callers decide link-vs-hub wording and restart ownership from this, never from a read
849
+ * they made before the lock.
850
+ */
851
+ connection: OcxClientConnectionConfig;
852
+ }
853
+
854
+ export interface ConnectedSyncOptions {
855
+ restartCodex?: boolean;
856
+ /**
857
+ * #7694: refuse unless this is the connection found under the lock. A mismatch throws
858
+ * `ClientSyncExpectationError` before any request or write.
859
+ */
860
+ expect?: ClientSyncExpectation;
843
861
  }
844
862
 
845
863
  /**
@@ -848,18 +866,36 @@ export interface ConnectedSyncResult {
848
866
  * never interleaves with another apply, and its record names what its own injection wrote.
849
867
  */
850
868
  export async function syncConnectedClient(
851
- options: { restartCodex?: boolean } = {},
869
+ options: ConnectedSyncOptions = {},
852
870
  deps: ClientConnectDeps = {},
853
871
  ): Promise<ConnectedSyncResult> {
854
- return withLinkApply(() => syncConnectedClientUnlocked(options, deps), deps.linkApplyLockPath);
872
+ let checked = false;
873
+ try {
874
+ return await withLinkApply(() => syncConnectedClientUnlocked(options, deps, () => { checked = true; }), deps.linkApplyLockPath);
875
+ } catch (error) {
876
+ // #7694: a pinned sync that cannot take a lock its check needs (a link connect holds the apply
877
+ // lock across its network reads) is refused as pending, with nothing written; it never surfaces
878
+ // as a generic failure the caller cannot tell from a broken sync.
879
+ if (options.expect && !checked && isClientSyncLockBusy(error)) {
880
+ throw new ClientSyncExpectationError(options.expect, "pending_operation");
881
+ }
882
+ throw error;
883
+ }
855
884
  }
856
885
 
857
886
  async function syncConnectedClientUnlocked(
858
- _options: { restartCodex?: boolean } = {},
887
+ options: ConnectedSyncOptions = {},
859
888
  deps: ClientConnectDeps = {},
889
+ markChecked: () => void = () => {},
860
890
  ): Promise<ConnectedSyncResult> {
861
891
  if (siblingOfLivePort() !== null) throw new Error(siblingSkipMessage());
862
892
  const initial = withClientLifecycleSync(() => withConfigMutationLockSync(() => {
893
+ // The expectation is checked by the read that selects this path; everything after is
894
+ // compare-and-swapped against the connection it passed (#7694).
895
+ if (options.expect) {
896
+ assertClientSyncExpectation(options.expect);
897
+ markChecked();
898
+ }
863
899
  assertNoClientDisconnectPending();
864
900
  const state = readClientConnectionState();
865
901
  if (state.kind !== "connected" || state.value.pendingOperation) throw new Error("client_sync_unavailable");
@@ -949,6 +985,7 @@ async function syncConnectedClientUnlocked(
949
985
  ...(homeSettings ? { homeSettings } : {}),
950
986
  ...(appliedRecord ? { appliedRecord } : {}),
951
987
  ...(applyRecordFailed ? { applyRecordFailed } : {}),
988
+ connection: next,
952
989
  };
953
990
  }
954
991
 
@@ -137,6 +137,15 @@ export function withdrawChangingHomeCodexSettingsRecord(linkId: string, document
137
137
  return true;
138
138
  }
139
139
 
140
+ /** The apply lock is held by another apply or a link connect in flight; nothing ran. */
141
+ export class LinkApplyBusyError extends Error {
142
+ readonly code = "link_apply_busy";
143
+ constructor() {
144
+ super("another Home settings apply is in progress on this machine; retry when it finishes");
145
+ this.name = "LinkApplyBusyError";
146
+ }
147
+ }
148
+
140
149
  /**
141
150
  * Serialize applies of the Home's settings on this Child, from the Home read through the Codex
142
151
  * injection to the record write, so a receipt always names the settings the injection wrote.
@@ -152,7 +161,7 @@ export async function withLinkApply<T>(work: () => Promise<T>, lockPath: string
152
161
  return await withClientLifecycle(() => { entered = true; return work(); }, { lockPath });
153
162
  } catch (error) {
154
163
  if (!entered && error instanceof Error && error.message === "client_lifecycle_busy") {
155
- throw new Error("another Home settings apply is in progress on this machine; retry when it finishes");
164
+ throw new LinkApplyBusyError();
156
165
  }
157
166
  throw error;
158
167
  }
@@ -76,7 +76,7 @@ function liftRequestIdleTimer(req: Request, server: Pick<Server<unknown>, "timeo
76
76
  * fetch, so a rebinding or cross-site browser page cannot reach the Home through this port.
77
77
  * - Without the committed link key nothing is fetched, and the caller gets
78
78
  * `503 link_credential_unavailable`.
79
- * - `/readyz` stays local: it reports this listener, not the tunnel.
79
+ * - `/readyz` stays local and is never relayed; the listener answers it from `link-readiness.ts`.
80
80
  * - A relayed request is exempt from the listener's idle limit, like a standalone data route.
81
81
  */
82
82
  export function handleLinkIngress(