@bitkyc08/opencodex 2.97.0 → 2.98.0-preview.20261107

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 (290) hide show
  1. package/bin/ocx.mjs +1 -1
  2. package/gui/dist/assets/App-6TFtZsUF.css +1 -0
  3. package/gui/dist/assets/App-B8_sOxoz.js +59 -0
  4. package/gui/dist/assets/Tray-DpWEp6ee.js +1 -0
  5. package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
  6. package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
  7. package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
  8. package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
  9. package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
  10. package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
  11. package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
  12. package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
  13. package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
  14. package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
  15. package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
  16. package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
  17. package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
  18. package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
  19. package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
  20. package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
  21. package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
  22. package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
  23. package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
  24. package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
  25. package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
  26. package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
  27. package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
  28. package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
  29. package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
  30. package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
  31. package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
  32. package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
  33. package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
  34. package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
  35. package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
  36. package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
  37. package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
  38. package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
  39. package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
  40. package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
  41. package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
  42. package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
  43. package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
  44. package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
  45. package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
  46. package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
  47. package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
  48. package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
  49. package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
  50. package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
  51. package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
  52. package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
  53. package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
  54. package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
  55. package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
  56. package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
  57. package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
  58. package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
  59. package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
  60. package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
  61. package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
  62. package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
  63. package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
  64. package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
  65. package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
  66. package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
  67. package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
  68. package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
  69. package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
  70. package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
  71. package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
  72. package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
  73. package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
  74. package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
  75. package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
  76. package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
  77. package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
  78. package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
  79. package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
  80. package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
  81. package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
  82. package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
  83. package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
  84. package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
  85. package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
  86. package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
  87. package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
  88. package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
  89. package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
  90. package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
  91. package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
  92. package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
  93. package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
  94. package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
  95. package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
  96. package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
  97. package/gui/dist/assets/brand-mark-VPhzz-WE.js +1 -0
  98. package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  99. package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  100. package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  101. package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  102. package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  103. package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  104. package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  105. package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  106. package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  107. package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  108. package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  109. package/gui/dist/assets/index-5REODpG3.css +2 -0
  110. package/gui/dist/assets/index-BWKBeK77.js +94 -0
  111. package/gui/dist/assets/segment-thumb-features-BQYzrze9.js +1 -0
  112. package/gui/dist/classic/assets/App-Bz65x1J6.js +58 -0
  113. package/gui/dist/{assets/Tray-CEw0y0jR.js → classic/assets/Tray-kk7mdO6I.js} +1 -1
  114. package/gui/dist/classic/assets/index-Dp2j8bSc.js +94 -0
  115. package/gui/dist/classic/assets/quota-summary-CvamtHjB.js +1 -0
  116. package/gui/dist/classic/index.html +47 -0
  117. package/gui/dist/favicon.png +0 -0
  118. package/gui/dist/favicon.svg +14 -0
  119. package/gui/dist/index.html +15 -2
  120. package/package.json +1 -1
  121. package/src/adapters/anthropic.ts +17 -8
  122. package/src/adapters/google.ts +7 -7
  123. package/src/adapters/kiro/adapter.ts +18 -3
  124. package/src/adapters/kiro/conversation.ts +8 -8
  125. package/src/adapters/kiro/payload.ts +45 -12
  126. package/src/adapters/kiro/stream.ts +169 -12
  127. package/src/adapters/kiro/structured-output-json.ts +191 -0
  128. package/src/adapters/kiro/structured-output-schema.ts +542 -0
  129. package/src/adapters/kiro/structured-output.ts +367 -0
  130. package/src/adapters/kiro-constants.ts +9 -0
  131. package/src/adapters/kiro-tools.ts +14 -9
  132. package/src/adapters/kiro-wire.ts +9 -5
  133. package/src/adapters/openai-chat/messages.ts +58 -5
  134. package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
  135. package/src/adapters/openai-chat/passthrough.ts +5 -3
  136. package/src/adapters/openai-chat/tool-schema.ts +83 -13
  137. package/src/adapters/openai-responses/opengateway-input.ts +18 -6
  138. package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
  139. package/src/adapters/qoder/live-models.ts +115 -1
  140. package/src/claude/failure-verdict.ts +21 -0
  141. package/src/claude/inbound-content-options.ts +15 -2
  142. package/src/claude/inbound-model-options.ts +2 -1
  143. package/src/claude/inbound-records.ts +2 -0
  144. package/src/claude/inbound.ts +17 -11
  145. package/src/claude/outbound.ts +52 -23
  146. package/src/cli/capabilities-access-remote.ts +13 -0
  147. package/src/cli/capabilities-base.ts +1 -0
  148. package/src/cli/capabilities-provider-models.ts +3 -3
  149. package/src/cli/codex-shim-autorestore.ts +7 -0
  150. package/src/cli/config-command.ts +11 -2
  151. package/src/cli/connect.ts +17 -2
  152. package/src/cli/dispatch.ts +3 -1
  153. package/src/cli/doctor.ts +95 -7
  154. package/src/cli/index.ts +12 -7
  155. package/src/cli/link-apply-restart.ts +9 -2
  156. package/src/cli/models.ts +124 -38
  157. package/src/cli/registry.ts +1 -1
  158. package/src/cli/restart-failure.ts +17 -0
  159. package/src/cli/stop-approval.ts +2 -2
  160. package/src/cli/sync-command.ts +1 -1
  161. package/src/cli/sync-fanout.ts +15 -4
  162. package/src/cli/system-restart-client.ts +5 -0
  163. package/src/cli/uninstall-client-state.ts +12 -1
  164. package/src/cli/update-restart-child.ts +13 -3
  165. package/src/cli/update-restart-home.ts +6 -3
  166. package/src/cli/update-restart.ts +36 -19
  167. package/src/client/connect.ts +4 -1
  168. package/src/client/hub-client.ts +5 -0
  169. package/src/client/link-management-relay.ts +39 -2
  170. package/src/client/link-readiness.ts +3 -1
  171. package/src/client/machine-api.ts +2 -1
  172. package/src/client/machine-listener.ts +7 -0
  173. package/src/client/orphan-token-recovery.ts +322 -0
  174. package/src/codex/catalog/provider-models.ts +12 -4
  175. package/src/codex/native-profile-api.ts +27 -1
  176. package/src/codex/shim-diagnostics.ts +7 -0
  177. package/src/codex/shim-legacy-record.ts +290 -0
  178. package/src/codex/shim-windows-refresh.ts +9 -2
  179. package/src/codex/shim-wrapper-write.ts +7 -0
  180. package/src/codex/shim.ts +80 -21
  181. package/src/config/diagnostics.ts +9 -9
  182. package/src/config/load-degrade.ts +27 -27
  183. package/src/config/provider-validation.ts +9 -2
  184. package/src/config/removed-opencode-free-backup.ts +6 -3
  185. package/src/config/tracked-runtime-inspection.ts +3 -3
  186. package/src/generated/compatibility-version.json +219 -147
  187. package/src/images/loop.ts +2 -2
  188. package/src/lib/client-error-body.ts +37 -6
  189. package/src/lib/config-ownership-removal.ts +422 -0
  190. package/src/lib/config-ownership.ts +646 -81
  191. package/src/lib/context-overflow-verdict.ts +3 -3
  192. package/src/lib/crash-guard.ts +4 -2
  193. package/src/lib/desktop-cli-handoff.d.mts +3 -4
  194. package/src/lib/desktop-cli-handoff.mjs +7 -16
  195. package/src/lib/errors.ts +1 -0
  196. package/src/lib/local-management-capability.ts +3 -1
  197. package/src/lib/messages-error-body.ts +162 -0
  198. package/src/lib/messages-sse-error-presentation.ts +93 -0
  199. package/src/lib/passive-read.ts +9 -4
  200. package/src/lib/socks5-fetch.ts +21 -9
  201. package/src/lib/upstream-retry.ts +81 -1
  202. package/src/lib/windows-owner-acl.ts +9 -3
  203. package/src/lib/winsw.ts +5 -5
  204. package/src/lib/workflow-budget.ts +3 -1
  205. package/src/oauth/index.ts +7 -0
  206. package/src/oauth/store.ts +20 -10
  207. package/src/protocols/codecs/messages-ir.ts +15 -9
  208. package/src/protocols/encoders/adapter-events.ts +26 -7
  209. package/src/protocols/encoders/messages.ts +72 -28
  210. package/src/providers/antigravity-models.ts +45 -12
  211. package/src/providers/free-directory.ts +2 -2
  212. package/src/providers/reasoning-metadata.ts +2 -1
  213. package/src/providers/registry/entries-extended.ts +9 -0
  214. package/src/reasoning-effort.ts +7 -2
  215. package/src/remote/hub-usage.ts +3 -0
  216. package/src/server/admission-model-scope.ts +1 -1
  217. package/src/server/admitted-http-turn.ts +2 -1
  218. package/src/server/anthropic-rate-limit-headers.ts +75 -3
  219. package/src/server/claude-messages.ts +130 -67
  220. package/src/server/gui-static.ts +4 -1
  221. package/src/server/hub-usage.ts +7 -2
  222. package/src/server/index/link-management.ts +8 -0
  223. package/src/server/index/ollama-routes.ts +2 -0
  224. package/src/server/index/serve-options.ts +23 -20
  225. package/src/server/index/startup-warnings.ts +5 -12
  226. package/src/server/index/websocket-handler.ts +1 -0
  227. package/src/server/inference/client-encoder-delivery.ts +5 -1
  228. package/src/server/management/logs-usage-routes.ts +89 -4
  229. package/src/server/management/provider-routes.ts +2 -22
  230. package/src/server/management/qoder-provider-probe.ts +105 -0
  231. package/src/server/management/route-registry.ts +3 -0
  232. package/src/server/management/usage-aggregate-cache.ts +15 -5
  233. package/src/server/management/usage-source-facets.ts +38 -0
  234. package/src/server/messages-native-tool-guard.ts +11 -3
  235. package/src/server/messages-native.ts +111 -40
  236. package/src/server/messages-response-headers.ts +25 -11
  237. package/src/server/messages-shared.ts +94 -64
  238. package/src/server/messages-sse-error-filter.ts +199 -0
  239. package/src/server/request-log.ts +12 -0
  240. package/src/server/responses/adapter-continuation.ts +11 -5
  241. package/src/server/responses/adapter-delivery.ts +14 -8
  242. package/src/server/responses/adapter-dispatch.ts +8 -8
  243. package/src/server/responses/anthropic-thinking-recovery.ts +2 -2
  244. package/src/server/responses/codex-auth-error.ts +8 -4
  245. package/src/server/responses/codex-ws-wire.ts +19 -3
  246. package/src/server/responses/compact.ts +4 -1
  247. package/src/server/responses/core-auth.ts +1 -1
  248. package/src/server/responses/core-combo-failure.ts +2 -0
  249. package/src/server/responses/core-combo.ts +2 -0
  250. package/src/server/responses/core-errors.ts +5 -4
  251. package/src/server/responses/core-options.ts +2 -0
  252. package/src/server/responses/empty-completion-guard.ts +4 -1
  253. package/src/server/responses/pacing-overload.ts +1 -1
  254. package/src/server/responses/passthrough-dispatch.ts +5 -5
  255. package/src/server/responses/request-prepare.ts +3 -1
  256. package/src/server/responses/request-transport.ts +9 -8
  257. package/src/server/responses/response-effects.ts +3 -2
  258. package/src/server/responses/terminal-guard.ts +30 -0
  259. package/src/server/restart-replacement.ts +3 -1
  260. package/src/server/sse-payload-rewrite.ts +23 -11
  261. package/src/server/workflow-refusal.ts +1 -1
  262. package/src/server/ws-bridge.ts +4 -0
  263. package/src/service/definition.ts +36 -4
  264. package/src/service/launchd.ts +89 -32
  265. package/src/service/logging.ts +34 -7
  266. package/src/service/plist-xml.ts +59 -0
  267. package/src/service/state.ts +8 -0
  268. package/src/service/systemd-env.ts +2 -0
  269. package/src/service/systemd.ts +31 -7
  270. package/src/service/windows-taskxml.ts +16 -7
  271. package/src/service-manager-probe.ts +4 -10
  272. package/src/types/provider.ts +2 -0
  273. package/src/types/request.ts +13 -1
  274. package/src/update/config-preflight.ts +48 -0
  275. package/src/update/index.ts +15 -1
  276. package/src/usage/client.ts +43 -0
  277. package/src/usage/error-detail.ts +1 -1
  278. package/src/usage/log.ts +4 -0
  279. package/src/usage/source-facets.ts +51 -0
  280. package/src/usage/source-filter.ts +65 -0
  281. package/src/usage/summary.ts +50 -8
  282. package/src/web-search/anthropic-executor.ts +105 -24
  283. package/src/web-search/executor.ts +5 -3
  284. package/src/web-search/loop.ts +2 -1
  285. package/src/web-search/progress-stream.ts +64 -5
  286. package/gui/dist/assets/App-DuNhggE1.js +0 -58
  287. package/gui/dist/assets/index-CynE_Rue.js +0 -94
  288. package/gui/dist/assets/quota-summary-VHFSlUuM.js +0 -1
  289. /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
  290. /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
@@ -12,7 +12,8 @@ import { acquireOwnershipMutationLease, unprivilegedOwnershipMutationEnvironment
12
12
  import { serviceStatePaths } from "../service/state";
13
13
  import { findLiveProxy, probeEndpointLiveness, probeHostname, type LiveProxy } from "../server/proxy-liveness";
14
14
  import { waitForPortAvailable } from "../server/ports";
15
- import { UPDATE_RESTART_CHILD_ENV, type UpdateRestartChildMarker } from "./update-restart-child";
15
+ import { normalizeBindHostname } from "../server/bind-host";
16
+ import { UPDATE_RESTART_CHILD_ENV, parseUpdateRestartMarker, type UpdateRestartChildMarker } from "./update-restart-child";
16
17
  import { assertUpdateRestartConfiguration, assertUpdateRestartHome, readUpdateRestartHome, type UpdateRestartHome, type UpdateRestartHomeDeps } from "./update-restart-home";
17
18
  import { observeAttestedUpdateReplacement, stopAttestedUpdateTarget } from "./update-restart-transport";
18
19
  import type { UpdateRestartCandidate } from "./update-restart-candidate";
@@ -39,7 +40,7 @@ export interface UpdateRestartIo {
39
40
  wait(ms: number): Promise<void>;
40
41
  }
41
42
  const ELIGIBILITY_REASONS = ["windows", "unsupported_platform", "foreground", "service", "shared_or_client",
42
- "package_tree_fenced", "unverifiable_ancestry", "target_changed", "configuration_changed", "desktop"] as const;
43
+ "package_tree_fenced", "unverifiable_ancestry", "target_changed", "configuration_changed", "desktop", "blank_runtime_hostname"] as const;
43
44
  export type UpdateRestartEligibilityReason = (typeof ELIGIBILITY_REASONS)[number];
44
45
 
45
46
  /** Carries only a closed reason code across the eligibility/transport boundary. */
@@ -74,6 +75,13 @@ export async function runUpdateRestart(candidate: UpdateRestartCandidate, deadli
74
75
  lease = io.acquire();
75
76
  const home = candidate.home;
76
77
  if (JSON.stringify(io.home()) !== JSON.stringify(home)) throw new Error("home_changed");
78
+ if (candidate.runtime.hostname !== undefined && !candidate.runtime.hostname.trim()) {
79
+ eligibilityReason = "blank_runtime_hostname";
80
+ throw new Error("target");
81
+ }
82
+ const marker = parseUpdateRestartMarker(JSON.stringify({ home, version: candidate.cliVersion, port: candidate.target.port,
83
+ hostname: normalizeBindHostname(candidate.runtime.hostname), deadlineAt }));
84
+ if (normalizeBindHostname(candidate.target.hostname) !== marker.hostname) throw new Error("target");
77
85
  const revalidate = () => {
78
86
  withinDeadline();
79
87
  io.checkHome(home);
@@ -122,7 +130,7 @@ export async function runUpdateRestart(candidate: UpdateRestartCandidate, deadli
122
130
  withinDeadline();
123
131
  io.checkHome(home);
124
132
  phase = "start";
125
- const child = io.start({ home, version: candidate.cliVersion, port: candidate.target.port, hostname: candidate.runtime.hostname ?? "", deadlineAt });
133
+ const child = io.start(marker);
126
134
  // The child must acquire its own lease and validate this frozen handoff before preflight.
127
135
  lease.release();
128
136
  lease = undefined;
@@ -136,7 +144,7 @@ export async function runUpdateRestart(candidate: UpdateRestartCandidate, deadli
136
144
  if (live) {
137
145
  io.checkHome(home);
138
146
  if (live.source !== "runtime" || live.pid !== child.pid || live.port !== candidate.target.port
139
- || (live.hostname ?? "") !== (candidate.target.hostname ?? "") || live.role === "client"
147
+ || !live.hostname || normalizeBindHostname(live.hostname) !== marker.hostname || live.role === "client"
140
148
  || live.packageTreeFenced || live.version !== candidate.cliVersion) throw new Error("replacement_mismatch");
141
149
  return { ok: true, live };
142
150
  }
@@ -165,6 +173,7 @@ export function describeUpdateRestartFailure(code: string, reason?: UpdateRestar
165
173
  case "unverifiable_ancestry": return "The proxy's process ancestry or manager could not be verified. Run `ocx status` to identify its owner before restarting.";
166
174
  case "configuration_changed": return "The selected configuration or connection changed. Run `ocx status` to inspect the intended proxy before restarting.";
167
175
  case "target_changed": return "The captured proxy identity changed. Run `ocx status` to inspect the intended proxy before restarting.";
176
+ case "blank_runtime_hostname": return "The running proxy's runtime record has a blank hostname, so its bind address cannot be verified. Use `ocx status` and `ocx service status` as clues, not proof of ownership or bind address. Once ownership is verified, for a service use the owning installation's `ocx service restart`; for Desktop, use the app; for a foreground proxy, use its terminal. For a detached standalone proxy, independently verify its process, home, supervisor and actual bind. If verified and forced termination is acceptable, the owner can run `ocx stop` from that installation and home; it may refuse or force termination if graceful shutdown fails. Independently confirm the process has exited, its supervisor will not restart it, and the intended address and port are free before running `ocx start` with the intended settings. If any step is uncertain or fails, stop and ask the owner or administrator; do not edit the runtime record or kill unrelated processes.";
168
177
  }
169
178
  })();
170
179
  return `${action} Nothing was stopped by this restart attempt.`;
@@ -191,6 +200,10 @@ export function describeUpdateRestartFailure(code: string, reason?: UpdateRestar
191
200
  }
192
201
  }
193
202
 
203
+ export function reportUpdateRestartFailure(result: Extract<UpdateRestartResult, { ok: false }>): void {
204
+ console.error(`❌ ${describeUpdateRestartFailure(result.code, result.reason)} (${result.code})`);
205
+ }
206
+
194
207
  export interface UpdateRestartStandaloneDeps {
195
208
  platform?: NodeJS.Platform;
196
209
  expectedHome?: UpdateRestartHome;
@@ -253,6 +266,24 @@ export function standalone(target: UpdateRestartCandidate["target"], deadlineAt:
253
266
  }
254
267
 
255
268
  /** Production composition keeps stop/start side effects out of cli/index.ts. */
269
+ /** Verify the new runtime record, its own proof, and an exact reread after attestation. */
270
+ export async function observeUpdateRestartReplacement(candidate: UpdateRestartCandidate, deadline: number, childPid: number,
271
+ deps: { findLive: typeof findLiveProxy; readRuntime: typeof readRuntimePort; attest: typeof observeAttestedUpdateReplacement } =
272
+ { findLive: findLiveProxy, readRuntime: readRuntimePort, attest: observeAttestedUpdateReplacement }): Promise<LiveProxy | null> {
273
+ const live = await deps.findLive({ deadlineAt: deadline, attempts: 1 });
274
+ if (!live) return null;
275
+ if (live.pid !== childPid) throw new Error("update_restart_replacement_changed");
276
+ const runtime = deps.readRuntime(childPid);
277
+ if (!runtime?.attestationSecret || runtime.pid !== childPid || runtime.port !== candidate.target.port
278
+ || !runtime.hostname || normalizeBindHostname(runtime.hostname) !== normalizeBindHostname(candidate.runtime.hostname) || runtime.siblingOfPort !== undefined) {
279
+ throw new Error("update_restart_replacement_unattested");
280
+ }
281
+ const attested = await deps.attest({ target: { ...live, pid: childPid },
282
+ secret: runtime.attestationSecret, version: candidate.cliVersion, deadlineAt: deadline });
283
+ if (JSON.stringify(deps.readRuntime(childPid)) !== JSON.stringify(runtime)) throw new Error("update_restart_replacement_changed");
284
+ return attested;
285
+ }
286
+
256
287
  export function restartFromCurrentInstallation(candidate: UpdateRestartCandidate, deadlineAt: number, environment: NodeJS.ProcessEnv): Promise<UpdateRestartResult> {
257
288
  const argv = startArgv(candidate.target.port);
258
289
  const executable = process.execPath;
@@ -286,21 +317,7 @@ export function restartFromCurrentInstallation(candidate: UpdateRestartCandidate
286
317
  child.unref();
287
318
  return child;
288
319
  },
289
- observe: async (deadline, childPid) => {
290
- const live = await findLiveProxy({ deadlineAt: deadline, attempts: 1 });
291
- if (!live) return null;
292
- if (live.pid !== childPid) throw new Error("update_restart_replacement_changed");
293
- const runtime = readRuntimePort(childPid);
294
- if (!runtime?.attestationSecret || runtime.port !== candidate.target.port
295
- || runtime.hostname !== candidate.runtime.hostname || runtime.siblingOfPort !== undefined) {
296
- throw new Error("update_restart_replacement_unattested");
297
- }
298
- const attested = await observeAttestedUpdateReplacement({ target: { ...live, pid: childPid },
299
- secret: runtime.attestationSecret, version: candidate.cliVersion, deadlineAt: deadline });
300
- const current = readRuntimePort(childPid);
301
- if (JSON.stringify(current) !== JSON.stringify(runtime)) throw new Error("update_restart_replacement_changed");
302
- return attested;
303
- },
320
+ observe: (deadline, childPid) => observeUpdateRestartReplacement(candidate, deadline, childPid),
304
321
  wait: ms => Bun.sleep(ms),
305
322
  });
306
323
  }
@@ -556,6 +556,9 @@ function assertConnectingState(expectedTokenFingerprint?: string): void {
556
556
  const token = readServiceApiTokenState();
557
557
  if (expectedTokenFingerprint === undefined ? token.kind !== "absent"
558
558
  : token.kind !== "present" || token.fingerprint !== expectedTokenFingerprint) {
559
+ if (expectedTokenFingerprint === undefined && token.kind === "present") {
560
+ throw new Error("client_token_changed: if this is not a Hub and no admission secret or installed service uses the token, inspect it and use ocx disconnect --orphaned-token --yes before retrying");
561
+ }
559
562
  throw new Error("client_token_changed");
560
563
  }
561
564
  }
@@ -1121,7 +1124,7 @@ export async function disconnectClient(
1121
1124
  writeDesktopDisconnectReceipt(held, previous, receipt);
1122
1125
  }
1123
1126
  } else if (state.kind !== "disconnected" || !receipt || !disconnectAtLeast(receipt, "clearing_connection")) {
1124
- throw new Error("disconnect refused: no recoverable connected state");
1127
+ throw new Error("disconnect refused: no recoverable connected state; if this is not a Hub and no admission secret or installed service uses the token, inspect it and use ocx disconnect --orphaned-token --yes");
1125
1128
  }
1126
1129
  if (!receipt || receipt.keepCatalog !== keepCatalog) throw new Error("client_disconnect_options_changed");
1127
1130
  return { receipt, connection };
@@ -513,6 +513,11 @@ export async function fetchHubUsage(
513
513
  const text = await boundedText(response, MAX_HUB_USAGE_BYTES, { inactivityTimeoutMs: safeTimeout(options.timeoutMs) });
514
514
  const report = parseHubUsage(parseJson(text, "hub_usage_invalid"));
515
515
  if (!report) throw new HubClientError("hub_usage_invalid", "Hub usage response was invalid");
516
+ const requestedClient = query.get("client");
517
+ if (requestedClient !== null && (query.getAll("client").length !== 1
518
+ || report.sourceFilter?.client !== requestedClient || report.sourceFilter.scope !== "authenticated-key")) {
519
+ throw new HubClientError("hub_usage_invalid", "Hub usage source filter was not confirmed");
520
+ }
516
521
  return report;
517
522
  }
518
523
 
@@ -8,9 +8,11 @@
8
8
  * which attaches the link key only after the tunnel listener proves the link identity. Anything
9
9
  * outside the shared read allowlist is refused here, before a request exists.
10
10
  */
11
- import { HUB_RELAY_RESPONSE_BODY_MAX_BYTES } from "./hub-relay";
11
+ import { HUB_RELAY_DEFAULT_TIMEOUT_MS, HUB_RELAY_RESPONSE_BODY_MAX_BYTES } from "./hub-relay";
12
12
  import type { LinkIngress } from "./link-ingress";
13
13
  import { relayLinkDataRequest } from "./link-relay";
14
+ import { parseUsageSource } from "../usage/source-filter";
15
+ import { readBoundedResponseBytes } from "../lib/bounded-body";
14
16
  import {
15
17
  LINK_MANAGEMENT_PREFIX,
16
18
  linkChildManagementRefusal,
@@ -41,6 +43,15 @@ export async function relayLinkManagementRead(
41
43
  if (!linkManagementReadAllowed(req.method, pathname, new URLSearchParams(search.slice(1)))) {
42
44
  return linkChildRefusalResponse(homePhrase, linkId, `${req.method.toUpperCase()} ${pathname}`);
43
45
  }
46
+ const source = pathname === "/api/usage" ? parseUsageSource(new URLSearchParams(search.slice(1))) : { kind: "legacy" as const };
47
+ if (source.kind !== "legacy") {
48
+ if (source.kind !== "filtered" || source.filter.device.kind !== "key"
49
+ || !ingress.apiKeyId || source.filter.device.id !== ingress.apiKeyId) {
50
+ return Response.json({ error: "link_usage_scope_refused" }, { status: 403 });
51
+ }
52
+ // HEAD has no body in which the Home can confirm the filter; never present it as verified.
53
+ if (req.method.toUpperCase() === "HEAD") return new Response(null, { status: 405 });
54
+ }
44
55
  const admissionKey = ingress.linkKey();
45
56
  if (!admissionKey) return Response.json({ error: "link_credential_unavailable" }, { status: 503 });
46
57
  const outbound = new Request(`http://127.0.0.1${LINK_MANAGEMENT_PREFIX}${pathname}${search}`, {
@@ -48,7 +59,7 @@ export async function relayLinkManagementRead(
48
59
  headers: { accept: "application/json" },
49
60
  signal: req.signal,
50
61
  });
51
- return relayLinkDataRequest(outbound, {
62
+ const response = await relayLinkDataRequest(outbound, {
52
63
  tunnelPort: ingress.tunnelPort,
53
64
  admissionKey,
54
65
  linkId: ingress.linkId,
@@ -58,4 +69,30 @@ export async function relayLinkManagementRead(
58
69
  bodyLimitBytes: HUB_RELAY_RESPONSE_BODY_MAX_BYTES,
59
70
  routeAllowed: linkManagementRouteAllowed,
60
71
  });
72
+ if (source.kind !== "filtered" || !response.ok) return response;
73
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
74
+ if (contentType !== "application/json" && !contentType?.endsWith("+json")) {
75
+ try { void response.body?.cancel().catch(() => {}); } catch { /* best effort */ }
76
+ return Response.json({ error: "link_usage_filter_unconfirmed" }, { status: 502 });
77
+ }
78
+ try {
79
+ const requestedTimeout = ingress.relay?.headerTimeoutMs;
80
+ const deadline = requestedTimeout && requestedTimeout > 0
81
+ ? Math.min(requestedTimeout, HUB_RELAY_DEFAULT_TIMEOUT_MS) : HUB_RELAY_DEFAULT_TIMEOUT_MS;
82
+ const result = await readBoundedResponseBytes(response, { maxBytes: HUB_RELAY_RESPONSE_BODY_MAX_BYTES,
83
+ signal: AbortSignal.any([req.signal, AbortSignal.timeout(deadline)]), inactivityTimeoutMs: deadline });
84
+ if (result.oversized) throw new Error("response too large");
85
+ const body: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(result.bytes));
86
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("invalid response");
87
+ const echo = (body as Record<string, unknown>).sourceFilter;
88
+ if (!echo || typeof echo !== "object" || Array.isArray(echo)) throw new Error("missing source filter");
89
+ const value = echo as Record<string, unknown>;
90
+ const device = value.device;
91
+ if (value.client !== source.filter.client || !device || typeof device !== "object" || Array.isArray(device)
92
+ || (device as Record<string, unknown>).kind !== "key"
93
+ || (device as Record<string, unknown>).id !== ingress.apiKeyId) throw new Error("source filter mismatch");
94
+ return Response.json(body, { status: response.status, headers: response.headers });
95
+ } catch {
96
+ return Response.json({ error: "link_usage_filter_unconfirmed" }, { status: 502 });
97
+ }
61
98
  }
@@ -20,7 +20,9 @@ import type { ClientLinkSupervisorStatus } from "./link-tunnel";
20
20
  export type LinkReadinessReason =
21
21
  | "tunnel_idle" | "tunnel_connecting" | "tunnel_failed" | "tunnel_unavailable" | "sidecar_invalid"
22
22
  | "home_unreachable" | "home_unauthorized" | "link_auth_failed" | "link_credential_unavailable"
23
- | "link_unverified";
23
+ | "link_unverified"
24
+ /** The Child's durable connection no longer matches the one this runtime started with. */
25
+ | "client_state_changed";
24
26
 
25
27
  export type LinkReadiness = { ready: true } | { ready: false; reason: LinkReadinessReason };
26
28
 
@@ -131,7 +131,8 @@ export async function handleMachineApi(
131
131
  }
132
132
  try {
133
133
  const result = input.action === "uninstall" ? await uninstallCodexShimAsync() : await installCodexShimAsync();
134
- return Response.json({ success: true, action: input.action, result, shim: diagnoseCodexShim() });
134
+ // 200 either way so the dashboard re-reads the shim diagnosis; a refusal is not a success.
135
+ return Response.json({ success: !result.refused, action: input.action, result, shim: diagnoseCodexShim() });
135
136
  } catch (error) {
136
137
  return Response.json({ success: false, error: error instanceof Error ? error.message : "shim action failed" }, { status: 409 });
137
138
  }
@@ -41,6 +41,7 @@ import { linkRouteAllowed } from "../link/routes";
41
41
  import { linkHomeName, linkHomePhrase } from "./link-home";
42
42
  import { relayLinkManagementRead } from "./link-management-relay";
43
43
  import type { ClientRestartAdmission } from "./runtime-restart";
44
+ import { clientRestartRollbackAction } from "./runtime-restart";
44
45
  import { isLinkConnectionGeneration } from "../link/relay-auth";
45
46
 
46
47
  const VERSION = packageVersion("0.0.0");
@@ -136,6 +137,7 @@ export function startMachineListener(
136
137
  return state.value;
137
138
  })();
138
139
  const linkMode = isLinkConnection(connection);
140
+ const connectionChanged = () => clientRestartRollbackAction(connection, readClientConnectionState()) === "recycle";
139
141
  if (linkMode && !connection.link) throw new Error("link machine listener requires link transport metadata");
140
142
  const managementAuth = deps.managementAuthState ?? initializeManagementAuthState(config);
141
143
  let hubReachability: HubReachability = "unknown";
@@ -202,6 +204,8 @@ export function startMachineListener(
202
204
  if (linkMode && deps.linkReadiness) {
203
205
  try { link = await deps.linkReadiness(); } catch { link = { ready: false, reason: "link_unverified" }; }
204
206
  }
207
+ // Read durable ownership once, after any probe, so a change during the probe still shows.
208
+ if (linkMode && connectionChanged()) link = { ready: false, reason: "client_state_changed" };
205
209
  if (link && !link.ready) {
206
210
  // The /readyz contract: not ready is 503 with Retry-After and status pending or failed.
207
211
  return Response.json({ ...identity, status: "pending", ...facts, link: { state: "unavailable", reason: link.reason } },
@@ -253,6 +257,9 @@ export function startMachineListener(
253
257
  if (managementPrincipal(req, managementAuth, config) !== "gui-session") {
254
258
  return Response.json({ error: "opencodex machine GUI session required" }, { status: 401 });
255
259
  }
260
+ if (linkMode && (url.pathname === "/api/machine/status" || url.pathname === "/api/machine/clients" || url.pathname === "/api/link/status") && connectionChanged()) {
261
+ return Response.json({ error: "client_state_changed" }, { status: 503, headers: { "Cache-Control": "no-store" } });
262
+ }
256
263
  // A loopback dashboard session proves possession, not user presence: any local
257
264
  // process can fetch the dashboard bootstrap and replay its token and CSRF value.
258
265
  // Keep the connected listener useful for status/diagnostics, but never let that
@@ -0,0 +1,322 @@
1
+ import { createHash } from "node:crypto";
2
+ import { chmodSync, closeSync, constants, fchmodSync, fstatSync, linkSync, lstatSync, mkdtempSync, openSync, readFileSync, readSync, renameSync, unlinkSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { getConfigDir, getConfigPath, readConfigDiagnostics, withConfigMutationLockSync } from "../config";
5
+ import { readConfigGenerationInCurrentMutationTransaction } from "../config/mutation-lock";
6
+ import { withConfigDirHardeningSettled } from "../config/paths";
7
+ import { readAlivePid, readRuntimePort } from "../config/process-state";
8
+ import { readDesktopDisconnectReceipt } from "../claude/desktop-remote-store";
9
+ import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
10
+ import { hardenSecretDir, hardenSecretPath } from "../lib/windows-secret-acl";
11
+ import { readServiceApiTokenState, serviceApiTokenFingerprint } from "../lib/service-secrets";
12
+ import { createLocalAttestationChallenge, LOCAL_ATTESTATION_CHALLENGE_HEADER, LOCAL_ATTESTATION_PROOF_HEADER, verifyLocalAttestationProof } from "../lib/local-management-attestation";
13
+ import { LOCAL_PROVIDER_RELOAD_CAPABILITY_VERSION } from "../lib/local-provider-reload-contract";
14
+ import { loopbackFamilyAvailability } from "../lib/loopback-family";
15
+ import { acquireOwnershipMutationLease } from "../service/ownership-mutation-lease.mjs";
16
+ import { serviceStatePaths } from "../service/state";
17
+ import { classifyHealthz, DEFAULT_PROBE_TIMEOUT_MS, loopbackProbeHosts, observeProxyLiveness, probeEndpointLiveness, probeHostname, proveLiveProxyOwnedByHome, START_OWNERSHIP_LIVENESS, type LiveProxy } from "../server/proxy-liveness";
18
+ import { directLocalHttpFetch } from "../server/direct-local-http";
19
+ import { configuredApiAuthToken, isApiAuthRequired } from "../server/auth-cors";
20
+ import { defaultProbeRunner, defaultRawProbeRunner, inspectServiceManagerInstallation, type ProbeDeps } from "../service-manager-probe";
21
+ import { endpointsToProve, everyEndpointProvenDownAsync } from "../cli/uninstall-plan";
22
+ import { withClientLifecycle, type ClientLifecycleLockDeps } from "./lifecycle-lock";
23
+ import { pendingClientConnectMayOwnToken, readClientConnectionState } from "./state";
24
+
25
+ export interface OrphanTokenRecoveryDeps {
26
+ lifecycleLockDeps?: ClientLifecycleLockDeps;
27
+ acquireLease?: () => { release(): void };
28
+ /** Test seam: production uses the attested runtime and tri-state endpoint probes below. */
29
+ runtimeSafe?: () => Promise<boolean>;
30
+ /** Test seam: production checks installed and indeterminate service definitions. */
31
+ inspectServiceManager?: typeof inspectServiceManagerInstallation;
32
+ /** Exercise Windows handle ordering on other platforms; never set by the CLI. */
33
+ windowsMoveForTest?: boolean;
34
+ onWindowsHandlesClosed?: (fds: readonly number[]) => void;
35
+ }
36
+
37
+ function assertDisconnected(): void {
38
+ if (readClientConnectionState().kind !== "disconnected") throw new Error("orphan recovery refused: client state is not disconnected");
39
+ const diagnostics = readConfigDiagnostics();
40
+ if (diagnostics.source === "fallback") throw new Error("orphan recovery refused: admission configuration is unverified; repair the configuration before retrying");
41
+ if (diagnostics.config.runtimeRole === "hub") throw new Error("orphan recovery refused: this is a Hub; manage its admission secret through the Hub service instead");
42
+ const runtime = readRuntimePort();
43
+ if (isApiAuthRequired(diagnostics.config) || (runtime?.hostname && isApiAuthRequired({ hostname: runtime.hostname }))
44
+ || configuredApiAuthToken() || process.env.OCX_API_TOKEN_FILE?.trim()) {
45
+ throw new Error("orphan recovery refused: this installation may use an admission secret; inspect its bind and token configuration before retrying");
46
+ }
47
+ const token = readServiceApiTokenState();
48
+ if (token.kind === "present" && diagnostics.config.apiKeys?.some(entry =>
49
+ [entry.key, entry.pendingRotation?.key].some(value => value && serviceApiTokenFingerprint(value.trim()) === token.fingerprint))) {
50
+ throw new Error("orphan recovery refused: the token matches a configured admission secret; inspect the API keys before retrying");
51
+ }
52
+ if (pendingClientConnectMayOwnToken()) throw new Error("orphan recovery refused: client connect is pending");
53
+ const receipt = readDesktopDisconnectReceipt();
54
+ if (receipt.kind === "unsafe" || (receipt.kind === "valid" && receipt.value.phase !== "complete")) {
55
+ throw new Error("orphan recovery refused: disconnect is pending or unsafe");
56
+ }
57
+ }
58
+
59
+ function assertNoServiceAdmission(inspect: typeof inspectServiceManagerInstallation): void {
60
+ let service;
61
+ try { service = inspect(); }
62
+ catch { throw new Error("orphan recovery refused: service admission use is unverified; inspect the service configuration before retrying"); }
63
+ if (service.kind !== "absent") {
64
+ throw new Error("orphan recovery refused: an installed or unverified service may use the admission secret; inspect 'ocx service status' and remove or migrate the service before retrying");
65
+ }
66
+ }
67
+
68
+ /** Unlike generic discovery, failure to launch a manager probe cannot prove token ownership absent. */
69
+ export function inspectOrphanServiceAdmission(deps: ProbeDeps = {}): ReturnType<typeof inspectServiceManagerInstallation> {
70
+ const run = deps.run ?? defaultProbeRunner;
71
+ const runRaw = deps.runRaw ?? defaultRawProbeRunner;
72
+ return inspectServiceManagerInstallation({ ...deps,
73
+ run: (...args) => { const result = run(...args); if (result.spawnFailed) throw new Error("service manager unavailable"); return result; },
74
+ runRaw: (...args) => { const result = runRaw(...args); if (result.spawnFailed) throw new Error("service manager unavailable"); return result; },
75
+ });
76
+ }
77
+
78
+ function configWitness(): { generation: number; digest: string | null } {
79
+ let digest: string | null;
80
+ try { digest = createHash("sha256").update(readFileSync(getConfigPath())).digest("hex"); }
81
+ catch (error) {
82
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
83
+ digest = null;
84
+ }
85
+ return { generation: readConfigGenerationInCurrentMutationTransaction().value, digest };
86
+ }
87
+
88
+ /** No null liveness result is treated as evidence of absence. The caller holds the start lease. */
89
+ async function runtimeIsSafe(): Promise<boolean> {
90
+ const diagnostics = readConfigDiagnostics();
91
+ if (diagnostics.source === "fallback") return false;
92
+ const runtime = readRuntimePort();
93
+ const observation = await observeProxyLiveness(START_OWNERSHIP_LIVENESS);
94
+ const endpoints = endpointsToProve(runtime, diagnostics.config);
95
+ if (observation.kind === "unknown") return false;
96
+ if (observation.kind === "absent") return readAlivePid() === null && everyEndpointProvenDownAsync(endpoints, probeEndpointLiveness);
97
+ const live = observation.live;
98
+ if (!live) return false;
99
+ if (live.role === "client" || !runtime || !runtime.hostname?.trim() || runtime.siblingOfPort !== undefined) return false;
100
+ const observed = { ...live, hostname: live.probeHostname ?? live.hostname };
101
+ if (await proveLiveProxyOwnedByHome(observed, START_OWNERSHIP_LIVENESS) !== "proven") return false;
102
+ if (!await proveStandalone(observed, runtime)) return false;
103
+ for (const host of loopbackProbeHosts(live.hostname)) {
104
+ if (host === probeHostname(observed.hostname) || loopbackFamilyAvailability(host) === "unavailable") continue;
105
+ const answer = await classifyHealthz(`http://${host}:${live.port}/healthz`, directLocalHttpFetch, START_OWNERSHIP_LIVENESS.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS);
106
+ if (answer === "unknown" || (answer === "live" && !await proveStandalone({ ...observed, hostname: host }, runtime))) return false;
107
+ }
108
+ const otherEndpoints = endpoints.filter(endpoint => endpoint.port !== live.port || probeHostname(endpoint.hostname) !== probeHostname(live.hostname));
109
+ return otherEndpoints.length === 0 || everyEndpointProvenDownAsync(otherEndpoints, probeEndpointLiveness);
110
+ }
111
+
112
+ /** The client listener omits this standalone-only capability, including on legacy health bodies. */
113
+ async function proveStandalone(live: LiveProxy, runtime: NonNullable<ReturnType<typeof readRuntimePort>>): Promise<boolean> {
114
+ if (live.pid === null || runtime.pid !== live.pid || runtime.port !== live.port || !runtime.attestationSecret) return false;
115
+ try {
116
+ const challenge = createLocalAttestationChallenge();
117
+ const response = await directLocalHttpFetch(`http://${probeHostname(live.hostname)}:${live.port}/healthz`, {
118
+ headers: { [LOCAL_ATTESTATION_CHALLENGE_HEADER]: challenge }, signal: AbortSignal.timeout(START_OWNERSHIP_LIVENESS.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS),
119
+ });
120
+ const body = await response.json() as { service?: unknown; pid?: unknown; port?: unknown; role?: unknown; providerReloadCapability?: unknown };
121
+ return response.ok && body.service === "opencodex" && body.pid === live.pid && body.port === live.port
122
+ && body.role !== "client" && body.providerReloadCapability === LOCAL_PROVIDER_RELOAD_CAPABILITY_VERSION
123
+ && verifyLocalAttestationProof(runtime.attestationSecret, challenge, live.pid, live.port, response.headers.get(LOCAL_ATTESTATION_PROOF_HEADER))
124
+ && JSON.stringify(readRuntimePort()) === JSON.stringify(runtime);
125
+ } catch { return false; }
126
+ }
127
+
128
+ type OpenSource = { path: string; name: string; fd: number | null; dev: number; ino: number; hash: string };
129
+ type Sources = { home: string; dev: number; ino: number; entries: { path: string; name: string; source: OpenSource | null }[] };
130
+
131
+ function fingerprint(fd: number): string {
132
+ // Read by descriptor with a hard cap even if a non-cooperating writer grows the file.
133
+ const bytes = Buffer.alloc(4097);
134
+ try {
135
+ let used = 0;
136
+ while (used < bytes.length) {
137
+ const count = readSync(fd, bytes, used, bytes.length - used, used);
138
+ if (count === 0) break;
139
+ used += count;
140
+ }
141
+ if (used > 4096 || fstatSync(fd).size > 4096) throw new Error("orphan recovery refused: unsafe token file");
142
+ return createHash("sha256").update(bytes.subarray(0, used)).digest("hex");
143
+ } finally { bytes.fill(0); }
144
+ }
145
+
146
+ function openSource(path: string, name: string): OpenSource | null {
147
+ let entry;
148
+ try { entry = lstatSync(path); }
149
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
150
+ if (entry.isFile() && !entry.isSymbolicLink() && entry.nlink > 1) {
151
+ // An interrupted Windows recovery leaves its identity pin linked to the original.
152
+ throw new Error(`orphan recovery refused: unsafe token file (another hard link exists; if an earlier recovery was interrupted, remove the leftover .${name}.identity pin from its orphaned-token-* backup folder and retry)`);
153
+ }
154
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.size > 4096
155
+ || (process.platform !== "win32" && entry.uid !== process.getuid?.())) throw new Error("orphan recovery refused: unsafe token file");
156
+ const fd = openSync(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK));
157
+ try {
158
+ const opened = fstatSync(fd);
159
+ if (!opened.isFile() || opened.nlink !== 1 || opened.dev !== entry.dev || opened.ino !== entry.ino) {
160
+ throw new Error("orphan recovery refused: token file changed");
161
+ }
162
+ return { path, name, fd, dev: opened.dev, ino: opened.ino, hash: fingerprint(fd) };
163
+ } catch (error) { closeSync(fd); throw error; }
164
+ }
165
+
166
+ function readSources(): Sources {
167
+ const home = getConfigDir();
168
+ assertNotRealHomeUnderTest(home);
169
+ const dirStat = lstatSync(home);
170
+ if (!dirStat.isDirectory() || dirStat.isSymbolicLink() || (process.platform !== "win32" && dirStat.uid !== process.getuid?.())) {
171
+ throw new Error("orphan recovery refused: unsafe config directory");
172
+ }
173
+ const entries: Sources["entries"] = [];
174
+ try {
175
+ for (const name of ["service-api-token", "service-api-token.prev"]) {
176
+ const path = join(home, name);
177
+ entries.push({ path, name, source: openSource(path, name) });
178
+ }
179
+ if (!entries.some(entry => entry.source)) throw new Error("orphan recovery refused: no token files found");
180
+ return { home, dev: dirStat.dev, ino: dirStat.ino, entries };
181
+ } catch (error) {
182
+ for (const entry of entries) if (entry.source?.fd != null) closeSync(entry.source.fd);
183
+ throw error;
184
+ }
185
+ }
186
+
187
+ function verifyPinnedFile(path: string, source: OpenSource): void {
188
+ const entry = lstatSync(path);
189
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 2 || entry.dev !== source.dev || entry.ino !== source.ino) {
190
+ throw new Error("orphan recovery refused: token identity witness changed");
191
+ }
192
+ const fd = openSync(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK));
193
+ try {
194
+ const opened = fstatSync(fd);
195
+ if (!opened.isFile() || opened.nlink !== 2 || opened.dev !== source.dev || opened.ino !== source.ino || fingerprint(fd) !== source.hash) {
196
+ throw new Error("orphan recovery refused: token identity witness changed");
197
+ }
198
+ } finally { closeSync(fd); }
199
+ }
200
+
201
+ /** Best effort: drop a pin only while another name still holds the original token. */
202
+ function releasePins(pins: Map<string, string>): void {
203
+ for (const pin of pins.values()) {
204
+ try { if (lstatSync(pin).nlink > 1) unlinkSync(pin); } catch { /* the refusal below still names the folder */ }
205
+ }
206
+ }
207
+
208
+ function moveToPrivateBackup(sources: Sources, deps: OrphanTokenRecoveryDeps): { backupDir: string; files: string[] } {
209
+ const home = getConfigDir();
210
+ let backupDir: string | undefined;
211
+ const pins = new Map<string, string>();
212
+ try {
213
+ const homeStat = lstatSync(home);
214
+ if (home !== sources.home || !homeStat.isDirectory() || homeStat.isSymbolicLink()
215
+ || homeStat.dev !== sources.dev || homeStat.ino !== sources.ino) throw new Error("orphan recovery refused: config directory changed");
216
+ // Reopen and compare both names, including absence, after the asynchronous liveness probe.
217
+ for (const entry of sources.entries) {
218
+ const now = openSource(entry.path, entry.name);
219
+ try {
220
+ if (Boolean(now) !== Boolean(entry.source) || (now && entry.source
221
+ && (now.dev !== entry.source.dev || now.ino !== entry.source.ino || now.hash !== entry.source.hash))) {
222
+ throw new Error("orphan recovery refused: token file changed");
223
+ }
224
+ } finally { if (now?.fd != null) closeSync(now.fd); }
225
+ }
226
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
227
+ backupDir = mkdtempSync(join(home, `orphaned-token-${stamp}-`));
228
+ if (process.platform === "win32") hardenSecretDir(backupDir, { required: true });
229
+ else chmodSync(backupDir, 0o700);
230
+ const windowsMove = process.platform === "win32" || deps.windowsMoveForTest === true;
231
+ if (windowsMove) {
232
+ // A private hard link keeps each original file identity allocated after its Windows handle
233
+ // closes. Thus the rename cannot substitute a recycled file ID without detection.
234
+ for (const { source } of sources.entries) {
235
+ if (!source || source.fd === null) continue;
236
+ const pin = join(backupDir, `.${source.name}.identity`);
237
+ linkSync(source.path, pin);
238
+ pins.set(source.name, pin);
239
+ if (process.platform === "win32") hardenSecretPath(pin, { required: true });
240
+ const pinned = lstatSync(pin);
241
+ const original = fstatSync(source.fd);
242
+ if (!pinned.isFile() || pinned.nlink !== 2 || pinned.dev !== source.dev || pinned.ino !== source.ino
243
+ || original.dev !== source.dev || original.ino !== source.ino || original.nlink !== 2) {
244
+ throw new Error("orphan recovery refused: token file changed before move");
245
+ }
246
+ verifyPinnedFile(pin, source);
247
+ }
248
+ const closed: number[] = [];
249
+ for (const { source } of sources.entries) {
250
+ if (source?.fd == null) continue;
251
+ closeSync(source.fd);
252
+ closed.push(source.fd);
253
+ source.fd = null;
254
+ }
255
+ deps.onWindowsHandlesClosed?.(closed);
256
+ }
257
+ for (const { source } of sources.entries) {
258
+ if (!source) continue;
259
+ if (process.platform !== "win32" && source.fd !== null) fchmodSync(source.fd, 0o600);
260
+ const current = lstatSync(source.path);
261
+ if (!current.isFile() || current.nlink !== (windowsMove ? 2 : 1) || current.dev !== source.dev || current.ino !== source.ino) {
262
+ throw new Error("orphan recovery refused: token file changed");
263
+ }
264
+ const destination = join(backupDir, source.name);
265
+ renameSync(source.path, destination);
266
+ const moved = lstatSync(destination);
267
+ if (!moved.isFile() || moved.dev !== source.dev || moved.ino !== source.ino) throw new Error("orphan recovery refused: token file changed during move");
268
+ const pin = pins.get(source.name);
269
+ if (pin) {
270
+ const witness = lstatSync(pin);
271
+ if (!witness.isFile() || witness.dev !== source.dev || witness.ino !== source.ino || witness.nlink !== 2 || moved.nlink !== 2) {
272
+ throw new Error("orphan recovery refused: token identity witness changed");
273
+ }
274
+ verifyPinnedFile(destination, source);
275
+ unlinkSync(pin);
276
+ pins.delete(source.name);
277
+ }
278
+ if (process.platform === "win32") hardenSecretPath(destination, { required: true });
279
+ const verified = openSource(destination, source.name);
280
+ try {
281
+ if (!verified || verified.dev !== source.dev || verified.ino !== source.ino || verified.hash !== source.hash) {
282
+ throw new Error("orphan recovery refused: token file changed during move");
283
+ }
284
+ } finally { if (verified?.fd != null) closeSync(verified.fd); }
285
+ }
286
+ return { backupDir, files: sources.entries.filter(entry => entry.source).map(entry => entry.name) };
287
+ } catch (error) {
288
+ if (backupDir) {
289
+ releasePins(pins);
290
+ throw new Error(`orphan recovery incomplete; inspect private backup at ${JSON.stringify(backupDir)} before retrying`, { cause: error });
291
+ }
292
+ throw error;
293
+ }
294
+ }
295
+
296
+ /** Preserve explicitly selected orphan candidates without asserting they belong to a link. */
297
+ export async function recoverOrphanedTokens(deps: OrphanTokenRecoveryDeps = {}): Promise<{ backupDir: string; files: string[] }> {
298
+ const lease = (deps.acquireLease ?? (() => acquireOwnershipMutationLease(serviceStatePaths())))();
299
+ try {
300
+ return await withClientLifecycle(async () => {
301
+ const prepared = withConfigMutationLockSync(() => {
302
+ assertDisconnected();
303
+ return { witness: configWitness(), runtime: JSON.stringify(readRuntimePort()), pid: readAlivePid(), sources: readSources() };
304
+ });
305
+ try {
306
+ assertNoServiceAdmission(deps.inspectServiceManager ?? inspectOrphanServiceAdmission);
307
+ if (!await (deps.runtimeSafe ?? runtimeIsSafe)()) throw new Error("orphan recovery refused: client runtime is live or runtime state is unverified");
308
+ return await withConfigDirHardeningSettled(getConfigDir(), () => {
309
+ assertNoServiceAdmission(deps.inspectServiceManager ?? inspectOrphanServiceAdmission);
310
+ return withConfigMutationLockSync(() => {
311
+ assertDisconnected();
312
+ if (JSON.stringify(configWitness()) !== JSON.stringify(prepared.witness)) throw new Error("orphan recovery refused: config changed during liveness check");
313
+ if (JSON.stringify(readRuntimePort()) !== prepared.runtime || readAlivePid() !== prepared.pid) throw new Error("orphan recovery refused: runtime changed during liveness check");
314
+ return moveToPrivateBackup(prepared.sources, deps);
315
+ });
316
+ });
317
+ } finally {
318
+ for (const entry of prepared.sources.entries) if (entry.source?.fd != null) closeSync(entry.source.fd);
319
+ }
320
+ }, deps.lifecycleLockDeps);
321
+ } finally { lease.release(); }
322
+ }