@remodex/rmx 1.0.2

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 (588) hide show
  1. package/AGENTS_INSTALL.md +91 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/assets/architecture.png +0 -0
  5. package/assets/banner.png +0 -0
  6. package/assets/claude-code-models.gif +0 -0
  7. package/assets/codex-app-picker.png +0 -0
  8. package/bin/ocx.mjs +584 -0
  9. package/bin/package-main.mjs +9 -0
  10. package/gui/dist/assets/index-CZqebSPQ.css +1 -0
  11. package/gui/dist/assets/index-CkETtt7P.js +71 -0
  12. package/gui/dist/favicon.png +0 -0
  13. package/gui/dist/fonts/google-sans-cyrillic.woff2 +0 -0
  14. package/gui/dist/fonts/google-sans-latin.woff2 +0 -0
  15. package/gui/dist/icons.svg +24 -0
  16. package/gui/dist/index.html +25 -0
  17. package/gui/dist/logo.png +0 -0
  18. package/gui/dist/provider-icons/alibaba-color.svg +1 -0
  19. package/gui/dist/provider-icons/antigravity-color.svg +1 -0
  20. package/gui/dist/provider-icons/claude-color.svg +1 -0
  21. package/gui/dist/provider-icons/cline-color.svg +16 -0
  22. package/gui/dist/provider-icons/cloudflare-ai-gateway-color.svg +1 -0
  23. package/gui/dist/provider-icons/commandcode-color.svg +1 -0
  24. package/gui/dist/provider-icons/copilot-color.svg +1 -0
  25. package/gui/dist/provider-icons/cursor-color.svg +2 -0
  26. package/gui/dist/provider-icons/deepseek-color.svg +1 -0
  27. package/gui/dist/provider-icons/discord.svg +1 -0
  28. package/gui/dist/provider-icons/firepass-color.svg +1 -0
  29. package/gui/dist/provider-icons/fireworks-color.svg +1 -0
  30. package/gui/dist/provider-icons/gemini-color.svg +1 -0
  31. package/gui/dist/provider-icons/github-copilot-color.svg +1 -0
  32. package/gui/dist/provider-icons/gitlab-duo-color.svg +1 -0
  33. package/gui/dist/provider-icons/grok.svg +1 -0
  34. package/gui/dist/provider-icons/groq-color.svg +1 -0
  35. package/gui/dist/provider-icons/huggingface-color.svg +1 -0
  36. package/gui/dist/provider-icons/kimi-color.svg +1 -0
  37. package/gui/dist/provider-icons/kiro-color.svg +15 -0
  38. package/gui/dist/provider-icons/lm-studio-color.svg +1 -0
  39. package/gui/dist/provider-icons/mistral-color.svg +1 -0
  40. package/gui/dist/provider-icons/moonshot-color.svg +1 -0
  41. package/gui/dist/provider-icons/nvidia-color.svg +1 -0
  42. package/gui/dist/provider-icons/ollama-color.svg +1 -0
  43. package/gui/dist/provider-icons/openai.svg +1 -0
  44. package/gui/dist/provider-icons/opencode.svg +2 -0
  45. package/gui/dist/provider-icons/openrouter-color.svg +1 -0
  46. package/gui/dist/provider-icons/pi.svg +21 -0
  47. package/gui/dist/provider-icons/qianfan-color.svg +1 -0
  48. package/gui/dist/provider-icons/qwen-portal-color.svg +1 -0
  49. package/gui/dist/provider-icons/telegram.svg +1 -0
  50. package/gui/dist/provider-icons/vercel-ai-gateway-color.svg +1 -0
  51. package/gui/dist/provider-icons/vllm-color.svg +1 -0
  52. package/gui/dist/provider-icons/xiaomi-color.svg +1 -0
  53. package/package.json +118 -0
  54. package/src/AGENTS.md +28 -0
  55. package/src/adapters/anthropic-image-guard.ts +251 -0
  56. package/src/adapters/anthropic-image-normalize.ts +518 -0
  57. package/src/adapters/anthropic.ts +1205 -0
  58. package/src/adapters/azure.ts +36 -0
  59. package/src/adapters/base.ts +83 -0
  60. package/src/adapters/client-fingerprint.ts +59 -0
  61. package/src/adapters/command-code.ts +453 -0
  62. package/src/adapters/cursor/arg-codec.ts +38 -0
  63. package/src/adapters/cursor/arg-normalize.ts +104 -0
  64. package/src/adapters/cursor/cursor-errors.ts +165 -0
  65. package/src/adapters/cursor/discovery.ts +276 -0
  66. package/src/adapters/cursor/effort-map.ts +139 -0
  67. package/src/adapters/cursor/exec-policy.ts +88 -0
  68. package/src/adapters/cursor/framing.ts +250 -0
  69. package/src/adapters/cursor/gen/agent_pb.ts +15274 -0
  70. package/src/adapters/cursor/kv-store.ts +52 -0
  71. package/src/adapters/cursor/live-models.ts +153 -0
  72. package/src/adapters/cursor/live-smoke-gate.ts +41 -0
  73. package/src/adapters/cursor/live-transport.ts +1235 -0
  74. package/src/adapters/cursor/mcp-config.ts +42 -0
  75. package/src/adapters/cursor/mcp-manager.ts +333 -0
  76. package/src/adapters/cursor/message-mapper.ts +49 -0
  77. package/src/adapters/cursor/native-exec-common.ts +59 -0
  78. package/src/adapters/cursor/native-exec-desktop.ts +184 -0
  79. package/src/adapters/cursor/native-exec-fs.ts +332 -0
  80. package/src/adapters/cursor/native-exec-mcp.ts +153 -0
  81. package/src/adapters/cursor/native-exec-network.ts +43 -0
  82. package/src/adapters/cursor/native-exec-shell.ts +548 -0
  83. package/src/adapters/cursor/native-exec-tools.ts +118 -0
  84. package/src/adapters/cursor/native-exec.ts +604 -0
  85. package/src/adapters/cursor/protobuf-events.ts +735 -0
  86. package/src/adapters/cursor/protobuf-request.ts +719 -0
  87. package/src/adapters/cursor/request-builder.ts +280 -0
  88. package/src/adapters/cursor/thread-continuity.ts +67 -0
  89. package/src/adapters/cursor/tool-definitions.ts +621 -0
  90. package/src/adapters/cursor/transport-retry.ts +132 -0
  91. package/src/adapters/cursor/transport.ts +57 -0
  92. package/src/adapters/cursor/types.ts +59 -0
  93. package/src/adapters/cursor.ts +196 -0
  94. package/src/adapters/google-antigravity-replay.ts +520 -0
  95. package/src/adapters/google-antigravity-wire.ts +140 -0
  96. package/src/adapters/google-errors.ts +85 -0
  97. package/src/adapters/google-http.ts +100 -0
  98. package/src/adapters/google-tool-schema.ts +173 -0
  99. package/src/adapters/google-truncation.ts +24 -0
  100. package/src/adapters/google-wire-compiler.ts +232 -0
  101. package/src/adapters/google.ts +859 -0
  102. package/src/adapters/identity.ts +77 -0
  103. package/src/adapters/image.ts +23 -0
  104. package/src/adapters/kiro-constants.ts +16 -0
  105. package/src/adapters/kiro-errors.ts +208 -0
  106. package/src/adapters/kiro-events.ts +197 -0
  107. package/src/adapters/kiro-images.ts +129 -0
  108. package/src/adapters/kiro-retry.ts +312 -0
  109. package/src/adapters/kiro-thinking.ts +104 -0
  110. package/src/adapters/kiro-tool-fallback.ts +36 -0
  111. package/src/adapters/kiro-tools.ts +224 -0
  112. package/src/adapters/kiro-truncation.ts +33 -0
  113. package/src/adapters/kiro-wire.ts +129 -0
  114. package/src/adapters/kiro.ts +1924 -0
  115. package/src/adapters/mimo-free.ts +263 -0
  116. package/src/adapters/openai-chat.ts +1265 -0
  117. package/src/adapters/openai-responses.ts +1309 -0
  118. package/src/adapters/run-turn-queue.ts +114 -0
  119. package/src/adapters/tool-catalog-nudge.ts +71 -0
  120. package/src/adapters/upstream-http-error.ts +48 -0
  121. package/src/android-remote/assets.ts +218 -0
  122. package/src/android-remote/attachments.ts +168 -0
  123. package/src/android-remote/auth.ts +237 -0
  124. package/src/android-remote/cloudflare-provisioning.ts +409 -0
  125. package/src/android-remote/cloudflare-secret.ts +106 -0
  126. package/src/android-remote/cloudflare-tunnel.ts +488 -0
  127. package/src/android-remote/cloudflared.ts +286 -0
  128. package/src/android-remote/codex-app-server.ts +565 -0
  129. package/src/android-remote/desktop-history-page.ts +936 -0
  130. package/src/android-remote/desktop-ipc.ts +3643 -0
  131. package/src/android-remote/desktop-ownership-store.ts +98 -0
  132. package/src/android-remote/desktop-project-registration.ts +129 -0
  133. package/src/android-remote/desktop-session-stream.ts +1110 -0
  134. package/src/android-remote/desktop-workspace-state.ts +443 -0
  135. package/src/android-remote/file-change-parser.ts +112 -0
  136. package/src/android-remote/gateway.ts +9108 -0
  137. package/src/android-remote/mutation-store.ts +299 -0
  138. package/src/android-remote/projection.ts +1780 -0
  139. package/src/android-remote/queued-turn-store.ts +248 -0
  140. package/src/android-remote/session-command-recovery.ts +1384 -0
  141. package/src/android-remote/store.ts +466 -0
  142. package/src/android-remote/thread-reconciliation.ts +133 -0
  143. package/src/android-remote/thread-source-paths.ts +307 -0
  144. package/src/android-remote/thread-stream.ts +546 -0
  145. package/src/android-remote/turn-activity.ts +235 -0
  146. package/src/android-remote/user-message-identity.ts +94 -0
  147. package/src/bridge.ts +1793 -0
  148. package/src/chat/inbound.ts +295 -0
  149. package/src/chat/outbound.ts +821 -0
  150. package/src/claude/agents-inject.ts +267 -0
  151. package/src/claude/alias.ts +149 -0
  152. package/src/claude/auth-detect.ts +229 -0
  153. package/src/claude/auth-mode-migration.ts +32 -0
  154. package/src/claude/auth-mode.ts +62 -0
  155. package/src/claude/context-windows.ts +189 -0
  156. package/src/claude/desktop-3p-guard.ts +35 -0
  157. package/src/claude/desktop-3p-paths.ts +84 -0
  158. package/src/claude/desktop-3p.ts +601 -0
  159. package/src/claude/desktop-health.ts +26 -0
  160. package/src/claude/desktop-profile.ts +263 -0
  161. package/src/claude/gateway-cache.ts +70 -0
  162. package/src/claude/inbound-debug.ts +163 -0
  163. package/src/claude/inbound.ts +519 -0
  164. package/src/claude/model-info.ts +154 -0
  165. package/src/claude/outbound.ts +898 -0
  166. package/src/cli/access.ts +108 -0
  167. package/src/cli/account-api.ts +296 -0
  168. package/src/cli/account-auth.ts +250 -0
  169. package/src/cli/account-catalog-refresh.ts +14 -0
  170. package/src/cli/account-extended.ts +476 -0
  171. package/src/cli/account-main.ts +317 -0
  172. package/src/cli/account.ts +297 -0
  173. package/src/cli/agent-driven.ts +70 -0
  174. package/src/cli/agent.ts +184 -0
  175. package/src/cli/catalog-prewarm.ts +27 -0
  176. package/src/cli/claude-desktop.ts +211 -0
  177. package/src/cli/claude.ts +302 -0
  178. package/src/cli/codex-shim-autorestore.ts +45 -0
  179. package/src/cli/codex-shim-readiness.ts +69 -0
  180. package/src/cli/combo.ts +124 -0
  181. package/src/cli/config-command.ts +183 -0
  182. package/src/cli/debug.ts +228 -0
  183. package/src/cli/desktop-first-run.ts +25 -0
  184. package/src/cli/doctor.ts +1022 -0
  185. package/src/cli/export-command.ts +201 -0
  186. package/src/cli/help.ts +370 -0
  187. package/src/cli/index.ts +1565 -0
  188. package/src/cli/init.ts +224 -0
  189. package/src/cli/integrations.ts +225 -0
  190. package/src/cli/interactive-confirm.ts +133 -0
  191. package/src/cli/internal-dispatch.ts +35 -0
  192. package/src/cli/launcher-context.ts +77 -0
  193. package/src/cli/models-runtime.ts +224 -0
  194. package/src/cli/models.ts +340 -0
  195. package/src/cli/observe.ts +170 -0
  196. package/src/cli/opencode.ts +587 -0
  197. package/src/cli/provider-runtime.ts +179 -0
  198. package/src/cli/provider.ts +476 -0
  199. package/src/cli/ready.ts +301 -0
  200. package/src/cli/route-policy.ts +92 -0
  201. package/src/cli/runtime-api.ts +328 -0
  202. package/src/cli/star-prompt.ts +211 -0
  203. package/src/cli/status-oauth.ts +78 -0
  204. package/src/cli/status.ts +321 -0
  205. package/src/cli/system-command.ts +196 -0
  206. package/src/cli/system-restart-client.ts +146 -0
  207. package/src/cli/tray-proxy.ts +205 -0
  208. package/src/cli/v2.ts +200 -0
  209. package/src/cli.ts +10 -0
  210. package/src/clients/config-export.ts +1109 -0
  211. package/src/codex/account-id.ts +34 -0
  212. package/src/codex/account-label.ts +34 -0
  213. package/src/codex/account-lifecycle.ts +172 -0
  214. package/src/codex/account-namespace-match.ts +63 -0
  215. package/src/codex/account-namespaces.ts +195 -0
  216. package/src/codex/account-pause.ts +20 -0
  217. package/src/codex/account-priority.ts +83 -0
  218. package/src/codex/account-runtime-state.ts +31 -0
  219. package/src/codex/account-store.ts +517 -0
  220. package/src/codex/account-usability.ts +40 -0
  221. package/src/codex/admission.ts +263 -0
  222. package/src/codex/app-server-processes.ts +799 -0
  223. package/src/codex/auth-api.ts +2098 -0
  224. package/src/codex/auth-collision.ts +107 -0
  225. package/src/codex/auth-context.ts +480 -0
  226. package/src/codex/autostart-health.ts +156 -0
  227. package/src/codex/catalog/account-models.ts +67 -0
  228. package/src/codex/catalog/aggregation.ts +471 -0
  229. package/src/codex/catalog/bundled.ts +533 -0
  230. package/src/codex/catalog/effort.ts +432 -0
  231. package/src/codex/catalog/filesystem-evidence.ts +302 -0
  232. package/src/codex/catalog/kinds.ts +2 -0
  233. package/src/codex/catalog/metadata.ts +287 -0
  234. package/src/codex/catalog/native-models.ts +7 -0
  235. package/src/codex/catalog/parsing.ts +503 -0
  236. package/src/codex/catalog/provider-fetch.ts +2267 -0
  237. package/src/codex/catalog/sync.ts +1606 -0
  238. package/src/codex/catalog-admission.ts +197 -0
  239. package/src/codex/catalog-refresh-status.ts +87 -0
  240. package/src/codex/catalog-write-serialization.ts +242 -0
  241. package/src/codex/catalog.ts +15 -0
  242. package/src/codex/codex-write-lock.ts +384 -0
  243. package/src/codex/convergence-types.ts +593 -0
  244. package/src/codex/convergence.ts +580 -0
  245. package/src/codex/custom-model-catalog-migration.ts +176 -0
  246. package/src/codex/data/upstream-models.json +830 -0
  247. package/src/codex/desired-state.ts +230 -0
  248. package/src/codex/desktop-client-processes.ts +521 -0
  249. package/src/codex/exec-invocation.ts +22 -0
  250. package/src/codex/features.ts +1091 -0
  251. package/src/codex/generation.ts +202 -0
  252. package/src/codex/history-job.ts +347 -0
  253. package/src/codex/history-lock.ts +242 -0
  254. package/src/codex/history-migration-guardian.ts +115 -0
  255. package/src/codex/history-provider.ts +1075 -0
  256. package/src/codex/history-transition.ts +105 -0
  257. package/src/codex/history-worker.ts +204 -0
  258. package/src/codex/home.ts +206 -0
  259. package/src/codex/inject-coordination.ts +257 -0
  260. package/src/codex/inject.ts +1857 -0
  261. package/src/codex/injected-marker.ts +79 -0
  262. package/src/codex/integration-record.ts +266 -0
  263. package/src/codex/internal/catalog-writer.ts +203 -0
  264. package/src/codex/internal/history-writer.ts +105 -0
  265. package/src/codex/journal.ts +172 -0
  266. package/src/codex/main-account-cache.ts +56 -0
  267. package/src/codex/main-account.ts +40 -0
  268. package/src/codex/management-convergence.ts +114 -0
  269. package/src/codex/model-cache.ts +267 -0
  270. package/src/codex/native-main-admission.ts +47 -0
  271. package/src/codex/native-main-auth-temp.ts +187 -0
  272. package/src/codex/native-main-claim.ts +167 -0
  273. package/src/codex/native-main-lock-file.ts +162 -0
  274. package/src/codex/native-main-owner.ts +329 -0
  275. package/src/codex/native-profile-api.ts +247 -0
  276. package/src/codex/native-profile-manager.ts +1531 -0
  277. package/src/codex/native-profile-processes.ts +121 -0
  278. package/src/codex/native-profile-recovery.ts +99 -0
  279. package/src/codex/native-profile-stage-store.ts +387 -0
  280. package/src/codex/native-profile-startup.ts +348 -0
  281. package/src/codex/native-profile-store.ts +855 -0
  282. package/src/codex/native-profile-types.ts +120 -0
  283. package/src/codex/native-residue.ts +691 -0
  284. package/src/codex/paths.ts +78 -0
  285. package/src/codex/plugins-doctor.ts +242 -0
  286. package/src/codex/pool-rotation.ts +295 -0
  287. package/src/codex/project-config-warnings.ts +426 -0
  288. package/src/codex/prompt-journal.ts +311 -0
  289. package/src/codex/prompt-layers.ts +967 -0
  290. package/src/codex/prompt-lock.ts +143 -0
  291. package/src/codex/provider-adoption.ts +242 -0
  292. package/src/codex/quota-rejection.ts +224 -0
  293. package/src/codex/quota.ts +494 -0
  294. package/src/codex/refresh.ts +60 -0
  295. package/src/codex/routing.ts +1855 -0
  296. package/src/codex/runtime.ts +659 -0
  297. package/src/codex/shim.ts +1215 -0
  298. package/src/codex/subagent-defaults.ts +557 -0
  299. package/src/codex/subagent-model-fallback.ts +560 -0
  300. package/src/codex/sync.ts +238 -0
  301. package/src/codex/transition-state.ts +612 -0
  302. package/src/codex/upstream-host-health.ts +368 -0
  303. package/src/codex/user-identity.ts +374 -0
  304. package/src/codex/warmup.ts +192 -0
  305. package/src/codex/websocket-registry.ts +100 -0
  306. package/src/codex/write-coordination.ts +114 -0
  307. package/src/combos/failover.ts +140 -0
  308. package/src/combos/index.ts +44 -0
  309. package/src/combos/request.ts +64 -0
  310. package/src/combos/resolve.ts +232 -0
  311. package/src/combos/types.ts +392 -0
  312. package/src/config.ts +3270 -0
  313. package/src/generated/model-metadata.ts +144 -0
  314. package/src/github/star-state.ts +203 -0
  315. package/src/grok/inject.ts +540 -0
  316. package/src/grok/inspect.ts +45 -0
  317. package/src/grok/status.ts +127 -0
  318. package/src/grok/sync.ts +66 -0
  319. package/src/images/artifacts.ts +516 -0
  320. package/src/images/fulfill-video.ts +163 -0
  321. package/src/images/fulfill.ts +149 -0
  322. package/src/images/index.ts +4 -0
  323. package/src/images/loop.ts +922 -0
  324. package/src/images/plan.ts +133 -0
  325. package/src/images/synthetic-tool.ts +133 -0
  326. package/src/images/types.ts +41 -0
  327. package/src/images/xai-client.ts +141 -0
  328. package/src/images/xai-video-client.ts +163 -0
  329. package/src/index.ts +22 -0
  330. package/src/integrations/config-io.ts +151 -0
  331. package/src/integrations/journal.ts +315 -0
  332. package/src/integrations/merge.ts +135 -0
  333. package/src/integrations/native/ownership-preflight.ts +202 -0
  334. package/src/integrations/ownership.ts +111 -0
  335. package/src/integrations/registry.ts +108 -0
  336. package/src/integrations/serialize.ts +235 -0
  337. package/src/integrations/state.ts +290 -0
  338. package/src/integrations/store.ts +103 -0
  339. package/src/integrations/writer.ts +492 -0
  340. package/src/lib/abort.ts +146 -0
  341. package/src/lib/admin-secrets.ts +25 -0
  342. package/src/lib/admission.ts +83 -0
  343. package/src/lib/app-owned-memory-stores.ts +173 -0
  344. package/src/lib/app-owned-memory.ts +265 -0
  345. package/src/lib/bounded-body.ts +242 -0
  346. package/src/lib/bun-binary-validator.d.mts +3 -0
  347. package/src/lib/bun-binary-validator.mjs +18 -0
  348. package/src/lib/bun-runtime.ts +184 -0
  349. package/src/lib/bun-stream-caps.ts +127 -0
  350. package/src/lib/config-ownership.ts +438 -0
  351. package/src/lib/crash-guard.ts +344 -0
  352. package/src/lib/debug-log-buffer.ts +83 -0
  353. package/src/lib/debug-settings.ts +108 -0
  354. package/src/lib/debug.ts +31 -0
  355. package/src/lib/destination-policy.ts +316 -0
  356. package/src/lib/errors.ts +364 -0
  357. package/src/lib/eventstream-decoder.ts +253 -0
  358. package/src/lib/gcp-adc.ts +341 -0
  359. package/src/lib/injection-debug-log.ts +58 -0
  360. package/src/lib/local-management-attestation.ts +51 -0
  361. package/src/lib/open-url.ts +25 -0
  362. package/src/lib/pinned-http.ts +182 -0
  363. package/src/lib/privacy.ts +20 -0
  364. package/src/lib/process-control.ts +168 -0
  365. package/src/lib/provider-environment.ts +470 -0
  366. package/src/lib/provider-outbound.ts +203 -0
  367. package/src/lib/provider-url.ts +14 -0
  368. package/src/lib/proxy-env.ts +18 -0
  369. package/src/lib/redact.ts +510 -0
  370. package/src/lib/remodex-home.ts +616 -0
  371. package/src/lib/retry-after.ts +55 -0
  372. package/src/lib/service-secrets.ts +178 -0
  373. package/src/lib/shadow-call.ts +54 -0
  374. package/src/lib/sidecar-tracker.ts +52 -0
  375. package/src/lib/sse-decoder.ts +364 -0
  376. package/src/lib/state-store-registrations.ts +109 -0
  377. package/src/lib/state-store-sweeper.ts +184 -0
  378. package/src/lib/system-restart-contract.ts +73 -0
  379. package/src/lib/test-home-guard.ts +98 -0
  380. package/src/lib/token-estimate.ts +69 -0
  381. package/src/lib/translator-budget.ts +366 -0
  382. package/src/lib/upstream-reachability.ts +91 -0
  383. package/src/lib/upstream-retry.ts +508 -0
  384. package/src/lib/win-exec.ts +115 -0
  385. package/src/lib/win-paths.ts +68 -0
  386. package/src/lib/windows-elevation.ts +705 -0
  387. package/src/lib/windows-secret-acl.ts +817 -0
  388. package/src/lib/windows-user-principal.ts +283 -0
  389. package/src/lib/winsw.ts +402 -0
  390. package/src/model-sources.ts +73 -0
  391. package/src/oauth/anthropic-routing.ts +594 -0
  392. package/src/oauth/anthropic.ts +177 -0
  393. package/src/oauth/callback-server.ts +294 -0
  394. package/src/oauth/chatgpt.ts +150 -0
  395. package/src/oauth/command-code.ts +239 -0
  396. package/src/oauth/cursor.ts +231 -0
  397. package/src/oauth/github-copilot.ts +428 -0
  398. package/src/oauth/google-antigravity.ts +230 -0
  399. package/src/oauth/health.ts +443 -0
  400. package/src/oauth/index.ts +1280 -0
  401. package/src/oauth/key-providers.ts +128 -0
  402. package/src/oauth/kimi.ts +213 -0
  403. package/src/oauth/kiro-credentials.ts +726 -0
  404. package/src/oauth/kiro.ts +621 -0
  405. package/src/oauth/local-token-detect.ts +121 -0
  406. package/src/oauth/log.ts +48 -0
  407. package/src/oauth/login-cli.ts +163 -0
  408. package/src/oauth/pkce.ts +15 -0
  409. package/src/oauth/store.ts +655 -0
  410. package/src/oauth/token-guardian.ts +309 -0
  411. package/src/oauth/types.ts +62 -0
  412. package/src/oauth/xai.ts +241 -0
  413. package/src/providers/alibaba-region-backup.ts +75 -0
  414. package/src/providers/alibaba-region-migration.ts +156 -0
  415. package/src/providers/alibaba-region-startup.ts +36 -0
  416. package/src/providers/antigravity-models.ts +317 -0
  417. package/src/providers/api-keys.ts +140 -0
  418. package/src/providers/base-url-choices.ts +64 -0
  419. package/src/providers/codex-capacity.ts +288 -0
  420. package/src/providers/command-code-efforts.ts +85 -0
  421. package/src/providers/context-cap.ts +73 -0
  422. package/src/providers/derive.ts +451 -0
  423. package/src/providers/free-directory.ts +187 -0
  424. package/src/providers/github-copilot-transport.ts +56 -0
  425. package/src/providers/google-vertex-location.ts +14 -0
  426. package/src/providers/key-failover.ts +271 -0
  427. package/src/providers/kiro-models.ts +67 -0
  428. package/src/providers/label.ts +19 -0
  429. package/src/providers/model-discovery-limits.ts +16 -0
  430. package/src/providers/model-discovery.ts +361 -0
  431. package/src/providers/openai-sidecar.ts +235 -0
  432. package/src/providers/openai-tier-startup.ts +27 -0
  433. package/src/providers/openai-tiers.ts +301 -0
  434. package/src/providers/openai-virtual-models.ts +83 -0
  435. package/src/providers/openrouter-routing.ts +102 -0
  436. package/src/providers/provider-id-rewrite.ts +179 -0
  437. package/src/providers/quota.ts +1942 -0
  438. package/src/providers/reasoning-capabilities.ts +336 -0
  439. package/src/providers/registry.ts +2375 -0
  440. package/src/providers/slug-codec.ts +74 -0
  441. package/src/providers/xai-transport.ts +149 -0
  442. package/src/reasoning-effort.ts +243 -0
  443. package/src/responses/compaction.ts +124 -0
  444. package/src/responses/hosted-tool-policy.ts +9 -0
  445. package/src/responses/parser.ts +714 -0
  446. package/src/responses/reasoning-envelope.ts +60 -0
  447. package/src/responses/reasoning-replay-cache.ts +106 -0
  448. package/src/responses/schema.ts +159 -0
  449. package/src/responses/spill-store.ts +431 -0
  450. package/src/responses/state.ts +1039 -0
  451. package/src/responses/tool-groups.ts +19 -0
  452. package/src/router.ts +802 -0
  453. package/src/routing/analytics.ts +377 -0
  454. package/src/routing/capability.ts +205 -0
  455. package/src/routing/cost.ts +77 -0
  456. package/src/routing/evaluator.ts +444 -0
  457. package/src/routing/health.ts +401 -0
  458. package/src/routing/history/cursor.ts +43 -0
  459. package/src/routing/history/indexer.ts +605 -0
  460. package/src/routing/history/schema.ts +72 -0
  461. package/src/routing/profile-namespace.ts +15 -0
  462. package/src/routing/profile.ts +424 -0
  463. package/src/routing/quota.ts +145 -0
  464. package/src/routing/request-evidence.ts +45 -0
  465. package/src/routing/trace.ts +686 -0
  466. package/src/server/adapter-resolve.ts +83 -0
  467. package/src/server/auth-cors.ts +606 -0
  468. package/src/server/chat-completions.ts +379 -0
  469. package/src/server/claude-messages.ts +980 -0
  470. package/src/server/effort-policy.ts +251 -0
  471. package/src/server/github-copilot-responses-repair.ts +338 -0
  472. package/src/server/gui-static.ts +152 -0
  473. package/src/server/image-retry.ts +42 -0
  474. package/src/server/images.ts +485 -0
  475. package/src/server/index.ts +1633 -0
  476. package/src/server/lifecycle.ts +482 -0
  477. package/src/server/live.ts +609 -0
  478. package/src/server/management/agent-settings-routes.ts +1180 -0
  479. package/src/server/management/android-remote-routes.ts +390 -0
  480. package/src/server/management/api-access.ts +141 -0
  481. package/src/server/management/api-key-usage.ts +167 -0
  482. package/src/server/management/body.ts +35 -0
  483. package/src/server/management/combo-routes.ts +244 -0
  484. package/src/server/management/config-routes.ts +602 -0
  485. package/src/server/management/context.ts +88 -0
  486. package/src/server/management/integration-routes.ts +538 -0
  487. package/src/server/management/logs-usage-routes.ts +516 -0
  488. package/src/server/management/model-routes.ts +519 -0
  489. package/src/server/management/model-rows.ts +143 -0
  490. package/src/server/management/native-integration-routes.ts +781 -0
  491. package/src/server/management/oauth-account-routes.ts +573 -0
  492. package/src/server/management/provider-routes.ts +781 -0
  493. package/src/server/management/request-history-routes.ts +191 -0
  494. package/src/server/management/routing-analytics-routes.ts +74 -0
  495. package/src/server/management/routing-profile-routes.ts +384 -0
  496. package/src/server/management/shared.ts +277 -0
  497. package/src/server/management/sidebar-routes.ts +106 -0
  498. package/src/server/management/sync-response.ts +69 -0
  499. package/src/server/management/system-restart.ts +433 -0
  500. package/src/server/management/system-routes.ts +141 -0
  501. package/src/server/management/usage-summary-cache.ts +86 -0
  502. package/src/server/management-api.ts +269 -0
  503. package/src/server/management-auth.ts +353 -0
  504. package/src/server/memory-watchdog.ts +156 -0
  505. package/src/server/port-reclaim.ts +307 -0
  506. package/src/server/ports.ts +156 -0
  507. package/src/server/proxy-liveness.ts +326 -0
  508. package/src/server/proxy-stop.ts +92 -0
  509. package/src/server/readiness.ts +99 -0
  510. package/src/server/relay-eager.ts +353 -0
  511. package/src/server/relay.ts +1179 -0
  512. package/src/server/request-decompress.ts +132 -0
  513. package/src/server/request-log-conversation.ts +168 -0
  514. package/src/server/request-log.ts +1072 -0
  515. package/src/server/responses/collaboration.ts +409 -0
  516. package/src/server/responses/compact.ts +710 -0
  517. package/src/server/responses/core.ts +3561 -0
  518. package/src/server/responses/encrypted-payload.ts +308 -0
  519. package/src/server/responses/fetch-helpers.ts +171 -0
  520. package/src/server/responses/passthrough-error.ts +78 -0
  521. package/src/server/responses/policy-fallback.ts +152 -0
  522. package/src/server/responses/terminal-guard.ts +230 -0
  523. package/src/server/responses/upstream-error.ts +48 -0
  524. package/src/server/responses-image-gen-repair.ts +132 -0
  525. package/src/server/responses-item-id-repair.ts +272 -0
  526. package/src/server/responses-json-events.ts +52 -0
  527. package/src/server/responses-model-rewrite.ts +29 -0
  528. package/src/server/responses-snapshot-repair.ts +621 -0
  529. package/src/server/responses.ts +10 -0
  530. package/src/server/search.ts +181 -0
  531. package/src/server/sse-frame-buffer.ts +292 -0
  532. package/src/server/sse-payload-rewrite.ts +263 -0
  533. package/src/server/startup-action-control.ts +308 -0
  534. package/src/server/startup-health-cache.ts +119 -0
  535. package/src/server/system-env.ts +418 -0
  536. package/src/server/windows-tcp-drop.ts +184 -0
  537. package/src/server/windows-tray-control.ts +41 -0
  538. package/src/server/ws-bridge.ts +470 -0
  539. package/src/service-manager-probe.ts +824 -0
  540. package/src/service.ts +3011 -0
  541. package/src/stall-timeout.ts +20 -0
  542. package/src/storage/cleanup-job.ts +57 -0
  543. package/src/storage/cleanup.ts +3085 -0
  544. package/src/storage/policy-job.ts +457 -0
  545. package/src/storage/policy-scheduler.ts +40 -0
  546. package/src/storage/policy-worker.ts +59 -0
  547. package/src/storage/policy.ts +527 -0
  548. package/src/storage/restore-job.ts +299 -0
  549. package/src/storage/restore-worker.ts +58 -0
  550. package/src/storage/scanner.ts +238 -0
  551. package/src/storage/storage-mutation-coordinator.ts +139 -0
  552. package/src/storage/worker-lifecycle.ts +215 -0
  553. package/src/tray/assets/opencodex-tray-offline.ico +0 -0
  554. package/src/tray/assets/opencodex-tray-online.ico +0 -0
  555. package/src/tray/assets/opencodex-tray-warning.ico +0 -0
  556. package/src/tray/assets/opencodex-tray.png +0 -0
  557. package/src/tray/windows-tray.ps1 +364 -0
  558. package/src/tray/windows.ts +738 -0
  559. package/src/types.ts +1531 -0
  560. package/src/update/badge.ts +72 -0
  561. package/src/update/desktop-release.ts +1620 -0
  562. package/src/update/index.ts +402 -0
  563. package/src/update/job.ts +1906 -0
  564. package/src/update/notify.ts +261 -0
  565. package/src/update/npm-cache-preflight.d.mts +47 -0
  566. package/src/update/npm-cache-preflight.mjs +201 -0
  567. package/src/update/npm-invocation.d.mts +23 -0
  568. package/src/update/npm-invocation.mjs +94 -0
  569. package/src/update/tray-update-plan.d.mts +18 -0
  570. package/src/update/tray-update-plan.mjs +38 -0
  571. package/src/usage/cost.ts +0 -0
  572. package/src/usage/debug.ts +97 -0
  573. package/src/usage/expected-prices.ts +283 -0
  574. package/src/usage/log.ts +695 -0
  575. package/src/usage/summary.ts +585 -0
  576. package/src/usage/totals.ts +14 -0
  577. package/src/vision/anthropic-describe.ts +185 -0
  578. package/src/vision/describe.ts +127 -0
  579. package/src/vision/index.ts +558 -0
  580. package/src/vision/reasoning.ts +55 -0
  581. package/src/web-search/anthropic-executor.ts +189 -0
  582. package/src/web-search/executor.ts +105 -0
  583. package/src/web-search/format-result.ts +89 -0
  584. package/src/web-search/index.ts +196 -0
  585. package/src/web-search/loop.ts +791 -0
  586. package/src/web-search/parse.ts +235 -0
  587. package/src/web-search/progress-stream.ts +342 -0
  588. package/src/web-search/synthetic-tool.ts +47 -0
@@ -0,0 +1,1857 @@
1
+ import { existsSync, readFileSync, unlinkSync } from "node:fs";
2
+ import {
3
+ atomicWriteFile,
4
+ loadConfig,
5
+ observeConfigGeneration,
6
+ readConfigAdmissionSnapshot,
7
+ subagentDefaultSyncEffective,
8
+ websocketsEnabled,
9
+ } from "../config";
10
+ import { CodexWriteLockSkipped, withCodexWriteLock } from "./codex-write-lock";
11
+ import { shouldSyncCodexOnStart } from "./desired-state";
12
+ import { resolveCodexHistoryTransition } from "./history-transition";
13
+ import {
14
+ buildInjectWitness,
15
+ captureCodexPreImages,
16
+ codexInjectLockOutcome,
17
+ codexWriteCoordinationEligibility,
18
+ CodexPartialWriteError,
19
+ CodexWriteConflictError,
20
+ DEFAULT_INJECT_LOCK_TIMEOUT_MS,
21
+ recomputeInjectWitness,
22
+ restoreCodexPreImages,
23
+ } from "./inject-coordination";
24
+ import { readIntegrationRecord } from "./integration-record";
25
+ import { classifyNativeRoutedResidue } from "./native-residue";
26
+ import { inspectNativeCodexOwnership } from "../integrations/native/ownership-preflight";
27
+ import {
28
+ resolveCodexCoordinatorDatabasePath,
29
+ resolveEffectiveUserIdentity,
30
+ } from "./user-identity";
31
+ import {
32
+ markJournalInjectedState,
33
+ removeJournal,
34
+ restoreJournalState,
35
+ writeJournal,
36
+ } from "./journal";
37
+ import { withCatalogWriteSerialization } from "./catalog-write-serialization";
38
+ import { restoreCodexCatalogWithPermit } from "./catalog/sync";
39
+ import { syncCodexHistoryProvider, type CodexHistoryFailureReason } from "./history-provider";
40
+ import {
41
+ describeHistoryJobFailure,
42
+ deriveCodexHistoryOperation,
43
+ resolveCodexHistoryJobTarget,
44
+ runCodexHistoryJob,
45
+ type CodexHistoryJobOutcome,
46
+ } from "./history-job";
47
+ import {
48
+ OCX_SECTION_MARKER,
49
+ hasInjectedCodexRouting,
50
+ hasInjectedOpenaiBaseUrl,
51
+ isRootOpenaiBaseUrlLine,
52
+ isOcxSectionMarker,
53
+ providerTableStart,
54
+ providerTableString,
55
+ rootTomlString,
56
+ tomlStringPattern,
57
+ } from "./injected-marker";
58
+ import {
59
+ CODEX_CONFIG_PATH,
60
+ CODEX_EXTERNAL_MODELS_PATH,
61
+ CODEX_PROFILE_PATH,
62
+ DEFAULT_CATALOG_PATH,
63
+ getCodexHome,
64
+ parseTomlString,
65
+ readRootTomlString,
66
+ resolveCodexConfigPath,
67
+ tomlString,
68
+ } from "./paths";
69
+ import { resolveEffectiveProjectModelProvider } from "./project-config-warnings";
70
+ import {
71
+ transformManagedSubagentDefaults,
72
+ type ManagedSubagentDefaults,
73
+ } from "./subagent-defaults";
74
+ import type { OcxConfig } from "../types";
75
+ import {
76
+ adoptActiveCodexLbProvider,
77
+ CODEX_LB_PROVIDER_ID,
78
+ } from "./provider-adoption";
79
+
80
+ // Ownership predicates live in `./injected-marker` so `journal.ts` can reach them
81
+ // without importing this module back. Re-exported for existing external callers.
82
+ export { hasInjectedCodexRouting, hasInjectedOpenaiBaseUrl };
83
+
84
+ /**
85
+ * User-owned settings that have to be inactive while Remodex owns Codex routing
86
+ * stay visible in config.toml as comments. The paired temporary-value marker
87
+ * records the exact line Remodex added, so fallback cleanup removes it only
88
+ * while it is byte-for-byte unchanged.
89
+ *
90
+ * The journal remains the preferred byte-for-byte restore. These markers are
91
+ * the drift-safe fallback for a user who edits unrelated config while routing
92
+ * is active: we can restore only the settings we temporarily displaced without
93
+ * replacing the rest of their newer file.
94
+ */
95
+ export const REMODEX_PRESERVED_SETTING_PREFIX =
96
+ "# Remodex preserved while routing: ";
97
+ export const REMODEX_TEMPORARY_SETTING_PREFIX =
98
+ "# Remodex temporary routing value: ";
99
+
100
+ function preservedSettingLine(line: string): string {
101
+ return `${REMODEX_PRESERVED_SETTING_PREFIX}${line}`;
102
+ }
103
+
104
+ function temporarySettingMarker(line: string): string {
105
+ return `${REMODEX_TEMPORARY_SETTING_PREFIX}${JSON.stringify(line)}`;
106
+ }
107
+
108
+ function temporaryReplacementLines(
109
+ original: string | null,
110
+ replacement: string,
111
+ ): string[] {
112
+ return [
113
+ ...(original === null ? [] : [preservedSettingLine(original)]),
114
+ temporarySettingMarker(replacement),
115
+ replacement,
116
+ ];
117
+ }
118
+
119
+ interface TemporarySettingCleanup {
120
+ content: string;
121
+ error: string | null;
122
+ }
123
+
124
+ /**
125
+ * Remove only temporary values whose marker still names the exact next line.
126
+ * A changed or malformed pair is ambiguous ownership and therefore left alone.
127
+ */
128
+ function stripTemporarySettingValues(content: string): TemporarySettingCleanup {
129
+ const lines = content.split("\n");
130
+ const out: string[] = [];
131
+ const errors: string[] = [];
132
+ for (let i = 0; i < lines.length; i += 1) {
133
+ const line = lines[i]!;
134
+ if (!line.startsWith(REMODEX_TEMPORARY_SETTING_PREFIX)) {
135
+ out.push(line);
136
+ continue;
137
+ }
138
+ const encoded = line.slice(REMODEX_TEMPORARY_SETTING_PREFIX.length);
139
+ let expected: unknown;
140
+ try {
141
+ expected = JSON.parse(encoded);
142
+ } catch {
143
+ expected = null;
144
+ }
145
+ const next = lines[i + 1];
146
+ if (typeof expected !== "string" || next !== expected) {
147
+ out.push(line);
148
+ errors.push(`temporary routing marker near line ${i + 1} no longer matches its managed value`);
149
+ continue;
150
+ }
151
+ i += 1;
152
+ }
153
+ return {
154
+ content: out.join("\n"),
155
+ error: errors.length > 0 ? errors.join("; ") : null,
156
+ };
157
+ }
158
+
159
+ function restorePreservedSettingLines(content: string): string {
160
+ return content
161
+ .split("\n")
162
+ .map(line =>
163
+ line.startsWith(REMODEX_PRESERVED_SETTING_PREFIX)
164
+ ? line.slice(REMODEX_PRESERVED_SETTING_PREFIX.length)
165
+ : line)
166
+ .join("\n");
167
+ }
168
+
169
+ /**
170
+ * Return a previously managed document to its user-owned baseline before a
171
+ * fresh injection is computed.
172
+ */
173
+ export function restorePreservedCodexSettings(
174
+ content: string,
175
+ ): TemporarySettingCleanup {
176
+ const stripped = stripTemporarySettingValues(content);
177
+ return stripped.error
178
+ ? stripped
179
+ : { content: restorePreservedSettingLines(stripped.content), error: null };
180
+ }
181
+
182
+ export function externalCodexModelProvider(content: string): string | null {
183
+ const provider = resolveEffectiveProjectModelProvider(content).provider;
184
+ return provider && provider !== "openai" && provider !== "opencodex"
185
+ ? provider
186
+ : null;
187
+ }
188
+
189
+ export function currentExternalCodexModelProvider(): string | null {
190
+ if (!existsSync(CODEX_CONFIG_PATH)) return null;
191
+ return externalCodexModelProvider(readFileSync(CODEX_CONFIG_PATH, "utf8"));
192
+ }
193
+
194
+ /**
195
+ * Detect the file's dominant line ending. Every transform in this module is LF-pure
196
+ * (split("\n") + hard "\n" joins), so CRLF configs (Windows-edited config.toml) are
197
+ * normalized to LF at the pipeline boundary and converted back on write — otherwise a
198
+ * single inject would leave a mixed-EOL file.
199
+ */
200
+ export function dominantEol(content: string): "\r\n" | "\n" {
201
+ const crlf = (content.match(/\r\n/g) ?? []).length;
202
+ if (crlf === 0) return "\n";
203
+ const bareLf = (content.match(/\n/g) ?? []).length - crlf;
204
+ return crlf >= bareLf ? "\r\n" : "\n";
205
+ }
206
+
207
+ /** Normalize all line endings to `eol` (CRLF first collapsed to LF, then expanded). */
208
+ export function applyEol(content: string, eol: "\r\n" | "\n"): string {
209
+ const lf = content.replace(/\r\n/g, "\n");
210
+ return eol === "\n" ? lf : lf.replace(/\n/g, "\r\n");
211
+ }
212
+
213
+ /**
214
+ * Design B (2026-07-06): loopback installs no longer re-tag the provider. Instead of
215
+ * `model_provider = "opencodex"` + a `[model_providers.opencodex]` table, we set the official
216
+ * built-in override `openai_base_url` (codex-rs config_toml.rs) so codex's own `openai`
217
+ * provider points at the proxy. Threads keep `model_provider = "openai"`, so history never
218
+ * needs remapping or restore. Non-loopback binds keep the legacy table injection because the
219
+ * built-in provider cannot carry the `x-opencodex-api-key` env header.
220
+ */
221
+
222
+ export interface InjectCodexOptions {
223
+ /**
224
+ * Absolute or CODEX_HOME-relative catalog path to advertise to Codex. Pass `null` only when the
225
+ * Remodex catalog could not be materialized; Codex will then keep its native catalog instead of
226
+ * failing on a missing model_catalog_json file.
227
+ */
228
+ catalogPath?: string | null;
229
+ /**
230
+ * How long to wait for the Codex write lock before reporting contention.
231
+ *
232
+ * Bounded by default so a stuck holder cannot wedge `rmx start`; an explicit
233
+ * caller that is willing to wait can raise it.
234
+ */
235
+ lockTimeoutMs?: number;
236
+ }
237
+
238
+ function configuredManagedSubagentDefaults(
239
+ config:
240
+ | Pick<
241
+ OcxConfig,
242
+ "injectionModel" | "injectionEffort" | "syncCodexSubagentDefaults"
243
+ >
244
+ | undefined,
245
+ ): ManagedSubagentDefaults | null {
246
+ if (!subagentDefaultSyncEffective(config ?? {})) return null;
247
+ return {
248
+ model: config!.injectionModel!.trim(),
249
+ ...(config!.injectionEffort?.trim()
250
+ ? { reasoningEffort: config!.injectionEffort.trim() }
251
+ : {}),
252
+ };
253
+ }
254
+
255
+ /**
256
+ * The `[model_providers.opencodex]` TABLE only. A table is position-independent in TOML, so it is
257
+ * safe to append at EOF. The bare root key `model_provider = "opencodex"` is NOT included here —
258
+ * it must live at the document root (before any table header) and is set separately by
259
+ * setRootModelProvider(). Appending the bare key at EOF was the original bug: it nested under
260
+ * whatever `[table]` happened to be open last (e.g. `[plugins."chrome@openai-bundled"]`), so Codex
261
+ * never saw a global model_provider and silently fell back to the `openai` (ChatGPT) provider.
262
+ */
263
+ /**
264
+ * True only for hostnames that bind loopback ONLY. Wildcard binds ("0.0.0.0", "::") are NOT
265
+ * loopback: they expose the proxy on every interface and therefore require the admission token.
266
+ * Do not use `providerBaseHost` for this decision — it folds wildcards to 127.0.0.1 because it
267
+ * answers "what address do I dial", which is a different question from "is this exposed".
268
+ */
269
+ export function isLoopbackHostname(hostname: string | undefined): boolean {
270
+ const normalized = (hostname ?? "127.0.0.1").trim().toLowerCase();
271
+ return (
272
+ normalized === "" ||
273
+ normalized === "localhost" ||
274
+ normalized === "127.0.0.1" ||
275
+ normalized === "::1" ||
276
+ normalized === "[::1]"
277
+ );
278
+ }
279
+
280
+ export function providerBaseHost(hostname: string | undefined): string {
281
+ const trimmed = (hostname ?? "127.0.0.1").trim();
282
+ const lower = trimmed.toLowerCase();
283
+ // Match what the server actually binds. Writing "localhost" while binding IPv4-only
284
+ // 127.0.0.1 breaks on Windows, where localhost commonly resolves to ::1 first.
285
+ if (lower === "::1" || lower === "[::1]") return "[::1]";
286
+ if (
287
+ isLoopbackHostname(trimmed) ||
288
+ trimmed === "0.0.0.0" ||
289
+ trimmed === "::" ||
290
+ trimmed === "[::]"
291
+ )
292
+ return "127.0.0.1";
293
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) return trimmed;
294
+ return trimmed.includes(":") ? `[${trimmed}]` : trimmed;
295
+ }
296
+
297
+ export function shouldInjectApiAuthHeader(
298
+ config: Pick<OcxConfig, "hostname" | "unauthenticatedLoopbackListener"> | undefined,
299
+ ): boolean {
300
+ // The unauthenticated loopback listener is a loopback bind, so it admits without a
301
+ // credential (#1102). Emitting the env header anyway would be worse than useless: the
302
+ // directly-spawned app-server this exists for has no OPENCODEX_API_AUTH_TOKEN in its
303
+ // environment, and Codex would send an empty header value.
304
+ if (config?.unauthenticatedLoopbackListener?.enabled) return false;
305
+ return !isLoopbackHostname(config?.hostname);
306
+ }
307
+
308
+ export function buildProviderTableBlock(
309
+ port: number,
310
+ supportsWebsockets = false,
311
+ includeApiAuthHeader = false,
312
+ hostname?: string,
313
+ ): string {
314
+ const host = providerBaseHost(hostname);
315
+ const lines = [
316
+ "",
317
+ OCX_SECTION_MARKER,
318
+ "[model_providers.opencodex]",
319
+ 'name = "Remodex"',
320
+ `base_url = "http://${host}:${port}/v1"`,
321
+ 'wire_api = "responses"',
322
+ "requires_openai_auth = true",
323
+ ];
324
+ if (includeApiAuthHeader) {
325
+ lines.push(
326
+ 'env_http_headers = { "x-opencodex-api-key" = "OPENCODEX_API_AUTH_TOKEN" }',
327
+ );
328
+ }
329
+ if (supportsWebsockets) lines.push("supports_websockets = true");
330
+ return lines.join("\n") + "\n";
331
+ }
332
+
333
+ export function buildOpenaiBaseUrlLine(
334
+ port: number,
335
+ hostname?: string,
336
+ ): string {
337
+ return `openai_base_url = "http://${providerBaseHost(hostname)}:${port}/v1"`;
338
+ }
339
+
340
+ /**
341
+ * Design B root-key injection: place `OCX_SECTION_MARKER` + `openai_base_url` at the document
342
+ * ROOT (before the first table header). Idempotent: an existing marker-owned line is rewritten
343
+ * in place. A user's OWN root `openai_base_url` (no marker above it) is respected — we keep it
344
+ * and inject nothing, reporting `keptUserBaseUrl` so the caller can surface it.
345
+ */
346
+ export function setRootOpenaiBaseUrl(
347
+ content: string,
348
+ port: number,
349
+ hostname?: string,
350
+ ): { content: string; keptUserBaseUrl: boolean } {
351
+ const lines = content.split("\n");
352
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
353
+ const rootEnd = firstTable === -1 ? lines.length : firstTable;
354
+ const key = buildOpenaiBaseUrlLine(port, hostname);
355
+
356
+ for (let i = 0; i < rootEnd; i++) {
357
+ if (!isRootOpenaiBaseUrlLine(lines[i])) continue;
358
+ const markerOwned = i > 0 && isOcxSectionMarker(lines[i - 1]);
359
+ if (!markerOwned) return { content, keptUserBaseUrl: true };
360
+ lines[i] = key;
361
+ return { content: lines.join("\n"), keptUserBaseUrl: false };
362
+ }
363
+
364
+ if (firstTable === -1) {
365
+ return {
366
+ content:
367
+ content.replace(/\n+$/, "") +
368
+ "\n" +
369
+ OCX_SECTION_MARKER +
370
+ "\n" +
371
+ key +
372
+ "\n",
373
+ keptUserBaseUrl: false,
374
+ };
375
+ }
376
+ let insertAt = firstTable;
377
+ while (insertAt > 0 && lines[insertAt - 1].trim() === "") insertAt--;
378
+ lines.splice(insertAt, 0, OCX_SECTION_MARKER, key);
379
+ return { content: lines.join("\n"), keptUserBaseUrl: false };
380
+ }
381
+
382
+ /**
383
+ * Remove the marker-owned root `openai_base_url` (marker line + the key line right after it).
384
+ * A user's own root override (no marker) survives; an orphaned marker with no key line after
385
+ * it is dropped too so repeated strip/inject cycles cannot accumulate marker comments.
386
+ */
387
+ export function stripInjectedOpenaiBaseUrl(content: string): string {
388
+ const lines = content.split("\n");
389
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
390
+ const rootEnd = firstTable === -1 ? lines.length : firstTable;
391
+ const drop = new Set<number>();
392
+ for (let i = 0; i < rootEnd; i++) {
393
+ if (!isOcxSectionMarker(lines[i])) continue;
394
+ if (i + 1 < rootEnd && isRootOpenaiBaseUrlLine(lines[i + 1])) {
395
+ drop.add(i);
396
+ drop.add(i + 1);
397
+ } else if (i + 1 >= rootEnd || lines[i + 1].trim() === "") {
398
+ drop.add(i); // orphaned marker at root
399
+ }
400
+ }
401
+ if (drop.size === 0) return content;
402
+ return lines.filter((_, i) => !drop.has(i)).join("\n");
403
+ }
404
+
405
+ export type CodexRoutingKind =
406
+ "native" | "opencodex-local" | "custom-local" | "custom-remote" | "unknown";
407
+
408
+ type RoutingEndpointKind = "local" | "remote" | "unknown";
409
+
410
+ function ipv4Octets(hostname: string): number[] | null {
411
+ const dotted = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
412
+ if (dotted) {
413
+ const octets = dotted.slice(1).map(Number);
414
+ return octets.some((octet) => octet > 255) ? null : octets;
415
+ }
416
+ const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(hostname);
417
+ if (!mapped) return null;
418
+ const high = Number.parseInt(mapped[1], 16);
419
+ const low = Number.parseInt(mapped[2], 16);
420
+ return [high >>> 8, high & 0xff, low >>> 8, low & 0xff];
421
+ }
422
+
423
+ function classifyRoutingEndpoint(value: string): RoutingEndpointKind {
424
+ try {
425
+ const url = new URL(value);
426
+ if (url.protocol !== "http:" && url.protocol !== "https:") return "unknown";
427
+ const hostname = url.hostname
428
+ .toLowerCase()
429
+ .replace(/^\[|\]$/g, "")
430
+ .replace(/\.$/, "");
431
+ if (!hostname) return "unknown";
432
+ if (hostname === "localhost" || hostname.endsWith(".localhost"))
433
+ return "local";
434
+ if (hostname === "::" || hostname === "::1" || hostname === "0.0.0.0")
435
+ return "local";
436
+ const octets = ipv4Octets(hostname);
437
+ if (octets) {
438
+ if (octets.every((octet) => octet === 0)) return "local";
439
+ if (octets[0] === 127) return "local";
440
+ return "remote";
441
+ }
442
+ if (/^::ffff:/i.test(hostname)) return "unknown";
443
+ return "remote";
444
+ } catch {
445
+ return "unknown";
446
+ }
447
+ }
448
+
449
+ /** Classify actual routing dependency separately from Remodex ownership. */
450
+ export function classifyCodexRouting(content: string): CodexRoutingKind {
451
+ const rootBaseUrl = rootTomlString(content, "openai_base_url");
452
+ if (rootBaseUrl) {
453
+ const endpoint = classifyRoutingEndpoint(rootBaseUrl);
454
+ if (endpoint === "unknown") return "unknown";
455
+ if (hasInjectedOpenaiBaseUrl(content)) return "opencodex-local";
456
+ return endpoint === "local" ? "custom-local" : "custom-remote";
457
+ }
458
+ const rootProvider = rootTomlString(content, "model_provider");
459
+ if (rootProvider) {
460
+ const providerTableExists =
461
+ providerTableStart(content.split("\n"), rootProvider) !== -1;
462
+ const providerBaseUrl = providerTableString(
463
+ content,
464
+ rootProvider,
465
+ "base_url",
466
+ );
467
+ if (providerBaseUrl) {
468
+ const endpoint = classifyRoutingEndpoint(providerBaseUrl);
469
+ if (endpoint === "unknown") return "unknown";
470
+ if (rootProvider === "opencodex") return "opencodex-local";
471
+ return endpoint === "local" ? "custom-local" : "custom-remote";
472
+ }
473
+ if (
474
+ rootProvider === "opencodex" ||
475
+ providerTableExists ||
476
+ rootProvider !== "openai"
477
+ )
478
+ return "unknown";
479
+ }
480
+ return "native";
481
+ }
482
+
483
+ /** Read-only probe used by status, doctor, and the dashboard. */
484
+ export function isCodexRoutingInjected(): boolean {
485
+ const path = CODEX_CONFIG_PATH;
486
+ if (!existsSync(path)) return false;
487
+ try {
488
+ return hasInjectedCodexRouting(readFileSync(path, "utf8"));
489
+ } catch {
490
+ return false;
491
+ }
492
+ }
493
+
494
+ export function getCodexRoutingKind(): CodexRoutingKind {
495
+ const path = CODEX_CONFIG_PATH;
496
+ if (!existsSync(path)) return "native";
497
+ try {
498
+ return classifyCodexRouting(readFileSync(path, "utf8"));
499
+ } catch {
500
+ return "unknown";
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Strip every existing `model_provider` line that we must not duplicate: any line set to
506
+ * "opencodex" (wherever it sits — including a previously mis-nested one under a table), plus any
507
+ * ROOT-level model_provider (before the first table) of any value, since we override the global.
508
+ * A `model_provider` legitimately inside a user table/profile with a non-opencodex value is left
509
+ * untouched.
510
+ */
511
+ function stripExistingModelProvider(
512
+ content: string,
513
+ temporarilyDisableRoot: boolean,
514
+ ): string {
515
+ const lines = content.split("\n");
516
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
517
+ const out: string[] = [];
518
+ lines.forEach((line, i) => {
519
+ if (/^\s*model_provider\s*=/.test(line)) {
520
+ const isOurs = /^\s*model_provider\s*=\s*"opencodex"\s*$/.test(line);
521
+ const isRoot = firstTable === -1 || i < firstTable;
522
+ if (isOurs) return;
523
+ if (isRoot && temporarilyDisableRoot) {
524
+ out.push(preservedSettingLine(line));
525
+ return;
526
+ }
527
+ }
528
+ out.push(line);
529
+ });
530
+ return out.join("\n");
531
+ }
532
+
533
+ /**
534
+ * Drop ROOT-level `model_context_window` overrides (keys before the first table header). Codex
535
+ * treats this root key as a global override that wins over the per-model catalog values, so a stale
536
+ * `model_context_window = 1000000` makes every model (e.g. gpt-5.5) report a 1M window. User-owned
537
+ * compaction limits do not alter the advertised context window and must survive reinjection.
538
+ */
539
+ export function stripRootContextWindowOverrides(content: string): string {
540
+ const lines = content.split("\n");
541
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
542
+ return lines
543
+ .filter((line, i) => {
544
+ const isRoot = firstTable === -1 || i < firstTable;
545
+ return !isRoot || !/^\s*model_context_window\s*=/.test(line);
546
+ })
547
+ .join("\n");
548
+ }
549
+
550
+ /**
551
+ * Injection counterpart to stripRootContextWindowOverrides.
552
+ *
553
+ * The root override must be inactive while the generated catalog owns context
554
+ * windows, but deleting the line makes drift-safe restoration impossible.
555
+ * Comment it instead; stop/disable can then restore exactly that setting even
556
+ * when the user edited a different part of config.toml meanwhile.
557
+ */
558
+ export function preserveRootContextWindowOverrides(content: string): string {
559
+ const lines = content.split("\n");
560
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
561
+ return lines
562
+ .map((line, i) => {
563
+ const isRoot = firstTable === -1 || i < firstTable;
564
+ return isRoot && /^\s*model_context_window\s*=/.test(line)
565
+ ? preservedSettingLine(line)
566
+ : line;
567
+ })
568
+ .join("\n");
569
+ }
570
+
571
+ function stripRootRoutedModel(content: string): string {
572
+ const lines = content.split("\n");
573
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
574
+ return lines
575
+ .filter((line, i) => {
576
+ const isRoot = firstTable === -1 || i < firstTable;
577
+ if (!isRoot) return true;
578
+ const m = line.match(/^\s*model\s*=\s*("(?:\\.|[^"])*"|'[^']*')\s*$/);
579
+ if (!m) return true;
580
+ const model = parseTomlString(m[1]);
581
+ return !model?.includes("/");
582
+ })
583
+ .join("\n");
584
+ }
585
+
586
+ /**
587
+ * Insert `model_provider = "opencodex"` at the document ROOT — immediately before the first table
588
+ * header (TOML root keys must precede all tables). If there are no tables, append it to the root body.
589
+ */
590
+ function setRootModelProvider(content: string): string {
591
+ const lines = content.split("\n");
592
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
593
+ const key = 'model_provider = "opencodex"';
594
+ const managed = temporaryReplacementLines(null, key);
595
+ if (firstTable === -1) {
596
+ return content.replace(/\n+$/, "") + "\n" + managed.join("\n") + "\n";
597
+ }
598
+ let insertAt = firstTable;
599
+ while (insertAt > 0 && lines[insertAt - 1].trim() === "") insertAt--;
600
+ lines.splice(insertAt, 0, ...managed);
601
+ return lines.join("\n");
602
+ }
603
+
604
+ function readRootModelCatalogPath(content: string): string | null {
605
+ return readRootTomlString(content, "model_catalog_json");
606
+ }
607
+
608
+ function setRootModelCatalogPath(content: string, catalogPath: string): string {
609
+ const lines = content.split("\n");
610
+ const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
611
+ const key = `model_catalog_json = ${tomlString(catalogPath)}`;
612
+ const rootEnd = firstTable === -1 ? lines.length : firstTable;
613
+ for (let i = 0; i < rootEnd; i++) {
614
+ const m = lines[i].match(
615
+ /^\s*model_catalog_json\s*=\s*("(?:\\.|[^"])*"|'[^']*')\s*$/,
616
+ );
617
+ if (!m) continue;
618
+ const existing = parseTomlString(m[1]);
619
+ if (isOpencodexCatalogPath(existing)) {
620
+ lines.splice(i, 1, ...temporaryReplacementLines(lines[i]!, key));
621
+ return lines.join("\n");
622
+ }
623
+ return content;
624
+ }
625
+ const managed = temporaryReplacementLines(null, key);
626
+ if (firstTable === -1) {
627
+ return content.replace(/\n+$/, "") + "\n" + managed.join("\n") + "\n";
628
+ }
629
+ let insertAt = firstTable;
630
+ while (insertAt > 0 && lines[insertAt - 1].trim() === "") insertAt--;
631
+ lines.splice(insertAt, 0, ...managed);
632
+ return lines.join("\n");
633
+ }
634
+
635
+ function removeProfileSection(content: string): string {
636
+ const lines = content.split("\n");
637
+ const filtered: string[] = [];
638
+ let inProfile = false;
639
+ for (const line of lines) {
640
+ if (line.trim() === "[profiles.opencodex]") {
641
+ inProfile = true;
642
+ continue;
643
+ }
644
+ if (inProfile) {
645
+ if (/^\s*\[/.test(line) && line.trim() !== "[profiles.opencodex]") {
646
+ inProfile = false;
647
+ filtered.push(line);
648
+ }
649
+ continue;
650
+ }
651
+ filtered.push(line);
652
+ }
653
+ return (
654
+ filtered
655
+ .join("\n")
656
+ .replace(/\n{3,}/g, "\n\n")
657
+ .trimEnd() + "\n"
658
+ );
659
+ }
660
+
661
+ function normalizeServiceTier(content: string): string {
662
+ return content
663
+ .split("\n")
664
+ .flatMap(line => {
665
+ const match = /^(\s*service_tier\s*=\s*)["']priority["']\s*$/.exec(line);
666
+ if (!match) return [line];
667
+ const replacement = `${match[1]}"fast"`;
668
+ return temporaryReplacementLines(line, replacement);
669
+ })
670
+ .join("\n");
671
+ }
672
+
673
+ function ensureFastModeFeature(content: string, fastMode?: boolean): string {
674
+ // Tri-state fast mode (see OcxConfig.fastMode): true forces `fast_mode = true`,
675
+ // false forces `fast_mode = false`, and undefined leaves the user's config
676
+ // untouched (no [features] table is added and an existing fast_mode line is
677
+ // preserved as-is). Table and key matching accept the valid TOML spellings
678
+ // `[features] # comment`, `["features"]` / `['features']`, and quoted keys.
679
+ const lines = content.split("\n");
680
+ const featuresHeader = /^\s*\[(["']?)\s*features\s*\1\]\s*(?:#.*)?$/;
681
+ const fastModeKey = /^\s*(?:"fast_mode"|'fast_mode'|fast_mode)\s*=/;
682
+ const featuresStart = lines.findIndex(line => featuresHeader.test(line));
683
+ if (featuresStart === -1) {
684
+ if (fastMode === undefined) return content;
685
+ const replacement = `fast_mode = ${fastMode ? "true" : "false"}`;
686
+ return content.trimEnd()
687
+ + "\n\n[features]\n"
688
+ + temporaryReplacementLines(null, replacement).join("\n")
689
+ + "\n";
690
+ }
691
+
692
+ const nextTable = lines.findIndex(
693
+ (line, index) => index > featuresStart && /^\s*\[/.test(line),
694
+ );
695
+ const featuresEnd = nextTable === -1 ? lines.length : nextTable;
696
+ for (let i = featuresStart + 1; i < featuresEnd; i++) {
697
+ if (fastModeKey.test(lines[i])) {
698
+ if (fastMode === undefined) return lines.join("\n");
699
+ const replacement = lines[i].replace(
700
+ /^(\s*)(?:"fast_mode"|'fast_mode'|fast_mode)\s*=.*$/,
701
+ `$1fast_mode = ${fastMode ? "true" : "false"}`,
702
+ );
703
+ if (replacement === lines[i]) return lines.join("\n");
704
+ lines.splice(i, 1, ...temporaryReplacementLines(lines[i]!, replacement));
705
+ return lines.join("\n");
706
+ }
707
+ }
708
+
709
+ if (fastMode === undefined) return lines.join("\n");
710
+ let insertAt = featuresEnd;
711
+ while (insertAt > featuresStart + 1 && lines[insertAt - 1].trim() === "") insertAt--;
712
+ const replacement = `fast_mode = ${fastMode ? "true" : "false"}`;
713
+ lines.splice(insertAt, 0, ...temporaryReplacementLines(null, replacement));
714
+ return lines.join("\n");
715
+ }
716
+
717
+ function isOpencodexCatalogPath(path: string): boolean {
718
+ return path.replace(/\\/g, "/").split("/").pop() === "opencodex-catalog.json";
719
+ }
720
+
721
+ function stripOpencodexCatalogPath(content: string): string {
722
+ return content
723
+ .split("\n")
724
+ .filter((line) => {
725
+ const m = line.match(
726
+ /^\s*model_catalog_json\s*=\s*("(?:\\.|[^"])*"|'[^']*')\s*$/,
727
+ );
728
+ return !m || !isOpencodexCatalogPath(parseTomlString(m[1]));
729
+ })
730
+ .join("\n");
731
+ }
732
+
733
+ export function buildProfileFile(port: number, catalogPath?: string | null, supportsWebsockets = false, includeApiAuthHeader = false, hostname?: string, fastMode?: boolean): string {
734
+ const host = providerBaseHost(hostname);
735
+ // A real Codex v2 profile, not a snippet for config.toml. The explicit provider
736
+ // override is what lets a base config keep `model_provider = "codex-lb"` (or any
737
+ // other provider) while a Remodex-owned app-server routes through localhost.
738
+ // Non-loopback keeps the provider-table shape because the built-in provider
739
+ // cannot carry the x-opencodex-api-key env header.
740
+ if (!includeApiAuthHeader) {
741
+ const lines = [
742
+ "# Remodex proxy profile — use with: codex --profile opencodex",
743
+ "# Generated separately so ~/.codex/config.toml remains user-owned and unchanged.",
744
+ `# Routes model requests through the Remodex proxy at ${host}:${port}.`,
745
+ 'model_provider = "openai"',
746
+ buildOpenaiBaseUrlLine(port, hostname),
747
+ ];
748
+ if (catalogPath) lines.push(`model_catalog_json = ${tomlString(catalogPath)}`);
749
+ if (fastMode !== undefined) lines.push("", "[features]", `fast_mode = ${fastMode ? "true" : "false"}`, "");
750
+ return lines.join("\n");
751
+ }
752
+ const lines = [
753
+ "# Remodex proxy profile — use with: codex --profile opencodex",
754
+ `# Routes all model requests through the Remodex proxy at ${host}:${port}`,
755
+ 'model_provider = "opencodex"',
756
+ ];
757
+ if (catalogPath) lines.push(`model_catalog_json = ${tomlString(catalogPath)}`);
758
+ if (fastMode !== undefined) lines.push("", "[features]", `fast_mode = ${fastMode ? "true" : "false"}`);
759
+ lines.push(buildProviderTableBlock(port, supportsWebsockets, includeApiAuthHeader, hostname).trimEnd(), "");
760
+ return lines.join("\n");
761
+ }
762
+
763
+ export function chooseCatalogPathForInjection(
764
+ content: string,
765
+ requested?: string | null,
766
+ ): string | null {
767
+ if (requested !== undefined) return requested;
768
+
769
+ const existing = readRootModelCatalogPath(content);
770
+ if (existing) {
771
+ const resolved = resolveCodexConfigPath(existing);
772
+ if (!isOpencodexCatalogPath(resolved) || existsSync(resolved))
773
+ return existing;
774
+ }
775
+
776
+ return existsSync(DEFAULT_CATALOG_PATH) ? DEFAULT_CATALOG_PATH : null;
777
+ }
778
+
779
+ export interface CodexInjectResult {
780
+ success: boolean;
781
+ message: string;
782
+ status?: "skipped";
783
+ skippedReason?: "desired_disabled" | "desired_enabled";
784
+ nativeSubagentDefaultsWarning?: string;
785
+ }
786
+
787
+ export async function injectCodexConfig(
788
+ port: number,
789
+ config?: OcxConfig,
790
+ options: InjectCodexOptions = {},
791
+ ): Promise<CodexInjectResult> {
792
+ // Point Codex at the unauthenticated loopback listener when it is enabled (#1102).
793
+ //
794
+ // Resolved here rather than at the call sites because every caller already passes the proxy
795
+ // port and the config together: startup sync, `rmx sync`, and the ensure path would each
796
+ // need the same two-line change, and a caller that missed it would silently emit a base_url
797
+ // requiring a credential the directly-spawned app-server does not have.
798
+ //
799
+ // The listener port is fixed in config, never OS-assigned, so this value survives restarts
800
+ // and matches what an already-running app-server read at startup.
801
+ const loopback = config?.unauthenticatedLoopbackListener;
802
+ if (loopback?.enabled) port = loopback.port;
803
+ if (!existsSync(CODEX_CONFIG_PATH)) {
804
+ return {
805
+ success: false,
806
+ message: `Codex config not found at ${CODEX_CONFIG_PATH}. Is Codex installed?`,
807
+ };
808
+ }
809
+
810
+ const rawContent = readFileSync(CODEX_CONFIG_PATH, "utf-8");
811
+ const activeProvider = externalCodexModelProvider(rawContent);
812
+ let adoptedProviderMessage = "";
813
+ if (activeProvider) {
814
+ if (activeProvider === CODEX_LB_PROVIDER_ID) {
815
+ config ??= loadConfig();
816
+ const adoption = adoptActiveCodexLbProvider(rawContent, config);
817
+ if (adoption.kind === "adopted" || adoption.kind === "already-managed") {
818
+ adoptedProviderMessage = adoption.kind === "adopted"
819
+ ? ` Imported Codex Desktop's codex-lb provider into Remodex using only its environment-variable reference.\n`
820
+ : ` Codex Desktop's codex-lb provider is already managed by Remodex.\n`;
821
+ } else {
822
+ removeJournal();
823
+ const reason = adoption.kind === "inactive"
824
+ ? "codex-lb is no longer active"
825
+ : "reason" in adoption
826
+ ? adoption.reason
827
+ : "codex-lb adoption did not converge";
828
+ return {
829
+ success: false,
830
+ message:
831
+ `Codex routing NOT injected: the active codex-lb provider could not be safely adopted (${reason}).\n` +
832
+ ` No Codex Desktop files were changed.`,
833
+ };
834
+ }
835
+ }
836
+
837
+ // External-provider coexistence is profile-only. In particular, do not
838
+ // remove/comment model_provider, model, service_tier, or the provider table
839
+ // in config.toml. The regular Codex app keeps using that base configuration;
840
+ // Remodex's external app-server projects this sidecar through one-off config overrides.
841
+ removeJournal();
842
+ if (!shouldSyncCodexOnStart(loadConfig())) {
843
+ return {
844
+ success: true,
845
+ status: "skipped",
846
+ skippedReason: "desired_disabled",
847
+ message: "Codex integration is OFF; no Codex config, catalog, cache, or history was changed.",
848
+ };
849
+ }
850
+ const requestedCatalogPath = options.catalogPath === undefined
851
+ ? chooseCatalogPathForInjection(rawContent)
852
+ : options.catalogPath;
853
+ const profileCatalogPath = existsSync(CODEX_EXTERNAL_MODELS_PATH)
854
+ ? CODEX_EXTERNAL_MODELS_PATH
855
+ : requestedCatalogPath;
856
+ const legacyMode = shouldInjectApiAuthHeader(config);
857
+ const profileContent = buildProfileFile(
858
+ port,
859
+ profileCatalogPath,
860
+ websocketsEnabled(config ?? {}),
861
+ legacyMode,
862
+ config?.hostname,
863
+ config?.fastMode,
864
+ );
865
+ atomicWriteFile(CODEX_PROFILE_PATH, profileContent);
866
+ const nativeSubagentDefaultsWarning = configuredManagedSubagentDefaults(config)
867
+ ? `Native Codex sub-agent defaults were not added to config.toml because external model_provider ${tomlString(activeProvider)} owns it.`
868
+ : undefined;
869
+ return {
870
+ success: true,
871
+ ...(nativeSubagentDefaultsWarning ? { nativeSubagentDefaultsWarning } : {}),
872
+ message:
873
+ `${adoptedProviderMessage}` +
874
+ `Codex config preserved byte-for-byte with external model_provider ${tomlString(activeProvider)}.\n` +
875
+ ` Remodex Codex profile: ${CODEX_PROFILE_PATH} (codex --profile opencodex)\n` +
876
+ (profileCatalogPath
877
+ ? ` Codex model catalog: ${profileCatalogPath}\n`
878
+ : ` Codex model catalog: online discovery via the local endpoint\n`) +
879
+ ` Local Responses endpoint: http://${providerBaseHost(config?.hostname)}:${port}/v1` +
880
+ (legacyMode
881
+ ? ` with x-opencodex-api-key from OPENCODEX_API_AUTH_TOKEN\n`
882
+ : `\n`) +
883
+ ` Remodex's external Codex app-server will apply this profile automatically.`,
884
+ };
885
+ }
886
+
887
+ // Marker-owned native defaults are Remodex residue, never part of the
888
+ // user's journal baseline. Clean them before either snapshotting or adding a
889
+ // root routing key: inserting that key ahead of a marker-owned first table
890
+ // would otherwise separate the table marker from its header. Ambiguous
891
+ // markers fail closed without writing config, profile, or journal state.
892
+ const nativeDefaultsBaseline = transformManagedSubagentDefaults(
893
+ rawContent,
894
+ null,
895
+ );
896
+ if (!nativeDefaultsBaseline.ok) {
897
+ return {
898
+ success: false,
899
+ message:
900
+ `Codex config injection refused: existing Remodex-managed native sub-agent defaults are ambiguous: ${nativeDefaultsBaseline.error}. ` +
901
+ `No files were changed; inspect ${CODEX_CONFIG_PATH}.`,
902
+ };
903
+ }
904
+ const baselineContent = nativeDefaultsBaseline.content;
905
+ const legacyMode = shouldInjectApiAuthHeader(config);
906
+
907
+ /*
908
+ * The journal write used to happen HERE, before the transforms. It now happens
909
+ * inside the write lock further down, and the transforms were hoisted above it
910
+ * rather than the lock being narrowed to the three file writes.
911
+ *
912
+ * Why: the lock's witness hashes the CANDIDATE BYTES, and those are not final
913
+ * until `profileContent` and the EOL-applied `content` exist. Opening the lock
914
+ * before them would leave nothing to hash; keeping the journal outside the
915
+ * lock would leave the first artifact-creating write unserialized, which is
916
+ * the hole this edge exists to close.
917
+ *
918
+ * The move is safe because the region between here and the writes performs no
919
+ * filesystem mutation — its only touch is `existsSync` on the catalog paths
920
+ * (`chooseCatalogPathForInjection`) — and because `writeJournal` is called
921
+ * with `configContent`, so it snapshots the baseline it is handed rather than
922
+ * rereading `config.toml` underneath the transforms.
923
+ */
924
+ // EOL boundary: transforms below are LF-pure; preserve the file's dominant ending on write.
925
+ const eol = dominantEol(rawContent);
926
+ let content = applyEol(baselineContent, "\n");
927
+
928
+ // Idempotent clean-up of any prior injection: drop the provider table (marker-based) and every
929
+ // stray/mis-nested model_provider line, so re-injecting can't duplicate keys or leave the buggy
930
+ // table-nested key behind.
931
+ // Design B form FIRST: removeOcxSection also keys on the marker line, so a root-level
932
+ // marker + openai_base_url pair must be gone before it scans or it would swallow root keys.
933
+ content = stripInjectedOpenaiBaseUrl(content);
934
+ if (content.includes("[model_providers.opencodex]")) {
935
+ content = removeOcxSection(content);
936
+ }
937
+ content = removeProfileSection(content);
938
+ const restoredSettings = restorePreservedCodexSettings(content);
939
+ if (restoredSettings.error) {
940
+ return {
941
+ success: false,
942
+ message:
943
+ `Codex config injection refused: ${restoredSettings.error}. ` +
944
+ `No files were changed; inspect ${CODEX_CONFIG_PATH}.`,
945
+ };
946
+ }
947
+ content = restoredSettings.content;
948
+ content = stripExistingModelProvider(
949
+ content,
950
+ legacyMode || activeProvider === CODEX_LB_PROVIDER_ID,
951
+ );
952
+ content = preserveRootContextWindowOverrides(content);
953
+ content = normalizeServiceTier(content);
954
+ content = ensureFastModeFeature(content, config?.fastMode);
955
+
956
+ const catalogPath = chooseCatalogPathForInjection(
957
+ content,
958
+ options.catalogPath,
959
+ );
960
+ content = catalogPath
961
+ ? setRootModelCatalogPath(content, catalogPath)
962
+ : stripOpencodexCatalogPath(content);
963
+
964
+ let keptUserBaseUrl = false;
965
+ if (legacyMode) {
966
+ // Legacy (non-loopback) injection: the built-in openai provider cannot carry the
967
+ // x-opencodex-api-key env header, so keep the opencodex provider table + root re-tag.
968
+ // 1) Root key BEFORE the first table header (must be a global, not nested under a table).
969
+ content = setRootModelProvider(content);
970
+ // 2) Provider table appended at EOF (position-independent).
971
+ content =
972
+ content.trimEnd() +
973
+ "\n" +
974
+ buildProviderTableBlock(
975
+ port,
976
+ websocketsEnabled(config ?? {}),
977
+ true,
978
+ config?.hostname,
979
+ );
980
+ } else {
981
+ // Design B (loopback): a single root override; codex keeps its native `openai` provider id
982
+ // so thread history is never remapped. Any legacy form was already stripped above.
983
+ content = stripInjectedOpenaiBaseUrl(content); // normalize before idempotent re-insert
984
+ const result = setRootOpenaiBaseUrl(content, port, config?.hostname);
985
+ content = result.content;
986
+ keptUserBaseUrl = result.keptUserBaseUrl;
987
+ }
988
+
989
+ const desiredSubagentDefaults = configuredManagedSubagentDefaults(config);
990
+ const routingOwnershipWarning =
991
+ keptUserBaseUrl && desiredSubagentDefaults
992
+ ? "Native Codex sub-agent defaults were not injected: a user-owned root openai_base_url prevents Remodex from managing active Codex routing."
993
+ : undefined;
994
+ const managedDefaults = transformManagedSubagentDefaults(
995
+ content,
996
+ keptUserBaseUrl ? null : desiredSubagentDefaults,
997
+ );
998
+ let nativeSubagentDefaultsWarning = routingOwnershipWarning;
999
+ let managedDefaultsMessage = routingOwnershipWarning
1000
+ ? ` ⚠️ ${routingOwnershipWarning}\n`
1001
+ : "";
1002
+ if (managedDefaults.ok) {
1003
+ content = managedDefaults.content;
1004
+ if (desiredSubagentDefaults && managedDefaults.conflicts.length > 0) {
1005
+ const keys = managedDefaults.conflicts
1006
+ .map((conflict) => `agents.${conflict.key}`)
1007
+ .join(", ");
1008
+ nativeSubagentDefaultsWarning = `Native Codex sub-agent defaults were not injected: user-owned ${keys} preserved.`;
1009
+ managedDefaultsMessage = ` ⚠️ ${nativeSubagentDefaultsWarning}\n`;
1010
+ }
1011
+ } else {
1012
+ const action =
1013
+ desiredSubagentDefaults && !keptUserBaseUrl
1014
+ ? "were not injected"
1015
+ : "could not be safely removed";
1016
+ nativeSubagentDefaultsWarning = `Native Codex sub-agent defaults ${action}: ${managedDefaults.error}.`;
1017
+ managedDefaultsMessage = ` ⚠️ ${nativeSubagentDefaultsWarning}\n`;
1018
+ }
1019
+
1020
+ const profileCatalogPath = existsSync(CODEX_EXTERNAL_MODELS_PATH)
1021
+ ? CODEX_EXTERNAL_MODELS_PATH
1022
+ : catalogPath;
1023
+ const profileContent = buildProfileFile(port, profileCatalogPath, websocketsEnabled(config ?? {}), legacyMode, config?.hostname, config?.fastMode);
1024
+ content = applyEol(content, eol);
1025
+
1026
+ /*
1027
+ * The witness, built from the FINAL bytes. Everything it hashes is either the
1028
+ * output about to be written or evidence that can be re-read under the lock;
1029
+ * ownership rides along as recorded context because it is not re-observed
1030
+ * there — see `write-coordination.ts`.
1031
+ */
1032
+ const persisted = readConfigAdmissionSnapshot();
1033
+ const persistedIdentity =
1034
+ persisted.kind === "read" ? persisted.contentSha256 : "unreadable";
1035
+ const observedGeneration = observeConfigGeneration();
1036
+ const generation =
1037
+ observedGeneration.kind === "ready"
1038
+ ? { present: true, value: observedGeneration.generation.value }
1039
+ : { present: false, value: 0 };
1040
+ const candidate = {
1041
+ configBytes: content,
1042
+ profileBytes: profileContent,
1043
+ catalogPath,
1044
+ };
1045
+ const witness = buildInjectWitness(
1046
+ candidate,
1047
+ rawContent,
1048
+ persistedIdentity,
1049
+ generation,
1050
+ "unknown",
1051
+ );
1052
+
1053
+ /*
1054
+ * THE COORDINATED SECTION.
1055
+ *
1056
+ * This is the write lock's first production caller. Everything above is
1057
+ * classification and pure transformation; everything from here to the end of
1058
+ * the callback replaces files, and two processes doing it at once is the
1059
+ * interruption hazard this substrate exists to close.
1060
+ *
1061
+ * The witness hashes the bytes about to be written rather than the inputs that
1062
+ * produced them, so two operations intending different output cannot share an
1063
+ * id no matter which input differed.
1064
+ */
1065
+ /*
1066
+ * Eligibility BEFORE acquisition, never "try and fall back".
1067
+ *
1068
+ * A home routed before this substrate existed cannot have its first
1069
+ * coordinator row created — the guard that refuses is correct — and that
1070
+ * describes every pre-substrate install. Attempting the lock there would enter
1071
+ * a refusal path on the entire installed base, so the decision happens first
1072
+ * and those homes keep the write sequence they have always used.
1073
+ */
1074
+ const eligibility = codexWriteCoordinationEligibility({
1075
+ coordinatorPath: () =>
1076
+ resolveCodexCoordinatorDatabasePath(
1077
+ resolveEffectiveUserIdentity(),
1078
+ getCodexHome(),
1079
+ ),
1080
+ residue: () => classifyNativeRoutedResidue(),
1081
+ integrationRecord: () => readIntegrationRecord(),
1082
+ });
1083
+ if (eligibility.kind === "refused") {
1084
+ return {
1085
+ success: false,
1086
+ message: `Codex configuration was not written: ${eligibility.reason}.`,
1087
+ };
1088
+ }
1089
+
1090
+ const applyNativeArtifacts = (): void => {
1091
+ writeJournal({
1092
+ currentStateIsNative: !hasInjectedCodexRouting(rawContent),
1093
+ configContent: baselineContent,
1094
+ });
1095
+ atomicWriteFile(CODEX_CONFIG_PATH, content);
1096
+ atomicWriteFile(CODEX_PROFILE_PATH, profileContent);
1097
+ markJournalInjectedState(content, profileContent);
1098
+ };
1099
+
1100
+ /*
1101
+ * Set only on the coordinated path: the generation/txId the transition just
1102
+ * committed. The terminal history update CASes against this, so a job that
1103
+ * was overtaken cannot overwrite the winner. Stays undefined for a
1104
+ * legacy-uncoordinated home, which publishes no transition to resolve.
1105
+ */
1106
+ let transitionReceipt: { nativeGeneration: number; currentTxId: string } | undefined;
1107
+
1108
+ if (eligibility.kind === "legacy-uncoordinated") {
1109
+ // Unchanged behavior for homes the coordinator cannot yet adopt. Stated
1110
+ // rather than implied: this is the boundary, and adoption is its own phase.
1111
+ if (!shouldSyncCodexOnStart(loadConfig())) {
1112
+ return {
1113
+ success: true,
1114
+ status: "skipped",
1115
+ skippedReason: "desired_disabled",
1116
+ message: "Codex integration is OFF; no Codex config, catalog, cache, or history was changed.",
1117
+ };
1118
+ }
1119
+ applyNativeArtifacts();
1120
+ } else {
1121
+ const coordinated = await withCodexWriteLock(
1122
+ {
1123
+ timeoutMs: options.lockTimeoutMs ?? DEFAULT_INJECT_LOCK_TIMEOUT_MS,
1124
+ admitted: { authoritySnapshotId: witness.comparisonId },
1125
+ readAdmissionUnderLock: () => ({
1126
+ authoritySnapshotId: recomputeInjectWitness({
1127
+ candidate: witness.candidate,
1128
+ canonicalTargets: witness.evidence.canonicalTargets,
1129
+ persistedIdentity,
1130
+ generation,
1131
+ observedOwnership: witness.observedOwnership,
1132
+ }).comparisonId,
1133
+ }),
1134
+ },
1135
+ (ctx) => {
1136
+ if (!shouldSyncCodexOnStart(loadConfig())) {
1137
+ throw new CodexWriteLockSkipped("desired_disabled");
1138
+ }
1139
+ /*
1140
+ * Publish BEFORE touching the filesystem. `assertPublished` runs after this
1141
+ * callback returns and throws unless a transition was recorded, so writing
1142
+ * first would replace every file and only then fail — with SQLite rolling
1143
+ * back and the filesystem staying changed.
1144
+ *
1145
+ * `beginTransition` returns a conflict rather than throwing, so its result
1146
+ * is checked here; ignoring it would reach the same failure by a slower
1147
+ * route.
1148
+ */
1149
+ const published = ctx.coordinator.beginTransition(
1150
+ {
1151
+ nativeGeneration: ctx.expectation.nativeBefore,
1152
+ currentTxId: ctx.currentTxId,
1153
+ },
1154
+ {
1155
+ txId: ctx.expectation.txId,
1156
+ direction: "apply",
1157
+ authoritySnapshotId: ctx.admission.authoritySnapshotId,
1158
+ nextRetryAt: new Date().toISOString(),
1159
+ },
1160
+ );
1161
+ if (published.kind !== "updated") {
1162
+ throw new CodexWriteConflictError(
1163
+ `The Codex transition could not be published: ${published.kind}.`,
1164
+ );
1165
+ }
1166
+
1167
+ /*
1168
+ * Exact pre-images, captured under the lock and used for compensation.
1169
+ *
1170
+ * A rolled-back coordinator row is not a rolled-back filesystem: each
1171
+ * `atomicWriteFile` is atomic alone, never across the three together, so a
1172
+ * failure partway leaves earlier replacements in place. `restoreJournalState`
1173
+ * cannot be the undo — it restores whichever journal occupies the path,
1174
+ * which need not be the one this operation wrote.
1175
+ */
1176
+ const preImages = captureCodexPreImages();
1177
+ try {
1178
+ applyNativeArtifacts();
1179
+ } catch (error) {
1180
+ // Compensate, then ALWAYS throw. Returning a partial result would let the
1181
+ // lock commit a row describing an apply that did not finish.
1182
+ const restored = restoreCodexPreImages(preImages);
1183
+ if (!restored.complete) {
1184
+ throw new CodexPartialWriteError(restored.unrestored);
1185
+ }
1186
+ throw error;
1187
+ }
1188
+ return {
1189
+ kind: "applied" as const,
1190
+ /*
1191
+ * The receipt the terminal update matches on. The transition commits
1192
+ * when the callback returns, so this pair is what the post-job
1193
+ * `updateCodexHistoryTransition` CASes against — an overtaken job
1194
+ * cannot overwrite a winner.
1195
+ */
1196
+ receipt: {
1197
+ nativeGeneration: ctx.expectation.nativeAfter,
1198
+ currentTxId: ctx.expectation.txId,
1199
+ },
1200
+ };
1201
+ },
1202
+ );
1203
+
1204
+ if (coordinated.status !== "acquired") {
1205
+ return codexInjectLockOutcome(coordinated);
1206
+ }
1207
+ transitionReceipt = coordinated.value.receipt;
1208
+ }
1209
+ // Legacy mode still forward-tags history so re-tagged threads stay listable. Design B needs
1210
+ // the opposite: a one-time migration of previously re-tagged threads BACK to openai (restore
1211
+ // machinery; cheap no-op when there is nothing to migrate).
1212
+ // History runs in a Worker under H, not on this thread.
1213
+ //
1214
+ // The three surfaces it touches — the SQLite rows, the backup manifest, and the
1215
+ // rollout files — do not share a transaction, so a busy timeout only ever
1216
+ // serialized one of them and an opposite-direction process could overtake
1217
+ // through the other two. The operation is derived from admitted intent here and
1218
+ // handed down fixed; the Worker never takes a direction from its caller.
1219
+ const historyOutcome = await runCodexHistoryJob({
1220
+ ...resolveCodexHistoryJobTarget(),
1221
+ expectedDesiredEnabled: true,
1222
+ operation: deriveCodexHistoryOperation({
1223
+ direction: "apply",
1224
+ resumeHistory: config?.syncResumeHistory !== false,
1225
+ legacyMode,
1226
+ }),
1227
+ });
1228
+ // A blocked or failed unit is reported, not silently counted as zero work:
1229
+ // `failed` is what makes the caller's message say so.
1230
+ const history: { rows: number; files: number; failed?: true } =
1231
+ historyOutcome.kind === "converged"
1232
+ ? { rows: historyOutcome.rows, files: historyOutcome.files }
1233
+ : historyOutcome.kind === "skipped"
1234
+ ? { rows: 0, files: 0 }
1235
+ : { rows: 0, files: 0, failed: true };
1236
+
1237
+ /*
1238
+ * Resolve the transition this job belongs to, on the coordinated path only.
1239
+ *
1240
+ * `updateCodexHistoryTransition` had no production caller since it was
1241
+ * written, so every completed or skipped job left the row permanently
1242
+ * `pending` — the transition was published and never resolved. This is the
1243
+ * first time the durable row reflects what actually happened. The CAS on the
1244
+ * receipt means an overtaken job's late write loses and is not overwritten.
1245
+ */
1246
+ if (transitionReceipt) {
1247
+ resolveCodexHistoryTransition(transitionReceipt, historyOutcome);
1248
+ }
1249
+
1250
+ const catalogMessage = catalogPath
1251
+ ? ` Codex model catalog: ${catalogPath}\n`
1252
+ : ` Codex model catalog not injected because no Remodex catalog file exists yet.\n`;
1253
+ const ejected = (history as { ejectedRows?: number }).ejectedRows ?? 0;
1254
+ const migratedRows = (history.rows ?? 0) + ejected;
1255
+ const historyMessage =
1256
+ config?.syncResumeHistory === false
1257
+ ? ` Codex resume history: left unchanged (syncResumeHistory=false).\n`
1258
+ : history.failed
1259
+ ? formatApplyHistoryFailure(historyOutcome, legacyMode)
1260
+ : legacyMode
1261
+ ? ` Codex resume history: ${history.rows} thread(s) made visible for Remodex; originals backed up for restore.\n`
1262
+ : migratedRows > 0
1263
+ ? ` Codex resume history: ${migratedRows} legacy Remodex-tagged thread(s) migrated back to openai (one-time).\n`
1264
+ : ` Codex resume history: untouched (threads keep their native openai tag).\n`;
1265
+ // A user-owned root openai_base_url means we did NOT install routing — say so honestly
1266
+ // instead of claiming the proxy route is active (catalog/fast_mode were still written).
1267
+ if (keptUserBaseUrl) {
1268
+ return {
1269
+ success: true,
1270
+ ...(nativeSubagentDefaultsWarning
1271
+ ? { nativeSubagentDefaultsWarning }
1272
+ : {}),
1273
+ message:
1274
+ `⚠️ Codex routing NOT injected: your config already sets a root openai_base_url, and Remodex never overwrites a user-owned override.\n` +
1275
+ catalogMessage +
1276
+ historyMessage +
1277
+ managedDefaultsMessage +
1278
+ ` To route plain codex through the proxy, remove your openai_base_url line from ~/.codex/config.toml and rerun 'rmx start'.\n` +
1279
+ ` Reference config: ${CODEX_PROFILE_PATH}`,
1280
+ };
1281
+ }
1282
+ const headline = legacyMode
1283
+ ? `Injected Remodex as default provider into Codex config.\n`
1284
+ : `Pointed Codex's built-in openai provider at the Remodex proxy (openai_base_url).\n`;
1285
+ return {
1286
+ success: true,
1287
+ ...(nativeSubagentDefaultsWarning ? { nativeSubagentDefaultsWarning } : {}),
1288
+ message:
1289
+ headline +
1290
+ adoptedProviderMessage +
1291
+ catalogMessage +
1292
+ historyMessage +
1293
+ managedDefaultsMessage +
1294
+ ` All models now route through Remodex proxy (like OpenRouter).\n` +
1295
+ ` OpenAI models (gpt-5.5, etc.) are passed through to OpenAI.\n` +
1296
+ ` Custom models route to their configured providers.\n` +
1297
+ (legacyMode
1298
+ ? ` Fallback: codex --profile opencodex (same behavior)`
1299
+ : ` Fallback reference: ${CODEX_PROFILE_PATH}`),
1300
+ };
1301
+ }
1302
+
1303
+ function removeOcxSection(content: string): string {
1304
+ const lines = content.split("\n");
1305
+ const filtered: string[] = [];
1306
+ let inOcxSection = false;
1307
+ for (const line of lines) {
1308
+ if (
1309
+ isOcxSectionMarker(line) ||
1310
+ line.trim() === "[model_providers.opencodex]"
1311
+ ) {
1312
+ inOcxSection = true;
1313
+ continue;
1314
+ }
1315
+ if (inOcxSection) {
1316
+ // End the injected section at the next table header that ISN'T our own — exact match so a
1317
+ // user's "[model_providers.opencodex_backup]" (or similar) is preserved, not swallowed.
1318
+ if (
1319
+ /^\s*\[/.test(line) &&
1320
+ line.trim() !== "[model_providers.opencodex]"
1321
+ ) {
1322
+ inOcxSection = false;
1323
+ filtered.push(line);
1324
+ }
1325
+ continue;
1326
+ }
1327
+ filtered.push(line);
1328
+ }
1329
+ return (
1330
+ filtered
1331
+ .join("\n")
1332
+ .replace(/\n{3,}/g, "\n\n")
1333
+ .trimEnd() + "\n"
1334
+ );
1335
+ }
1336
+
1337
+ interface StripOpencodexConfigResult {
1338
+ content: string;
1339
+ managedDefaultsError: string | null;
1340
+ temporarySettingsError: string | null;
1341
+ }
1342
+
1343
+ /**
1344
+ * Detailed form used by the on-disk restore path. A damaged ownership marker is
1345
+ * ambiguous: keep the associated value, but return the transform error so the
1346
+ * caller cannot report a complete restore.
1347
+ */
1348
+ function stripOpencodexConfigResult(
1349
+ content: string,
1350
+ ): StripOpencodexConfigResult {
1351
+ let out = content;
1352
+ const hadRootOcxProvider =
1353
+ readRootTomlString(out, "model_provider") === "opencodex";
1354
+ const hadInjectedBaseUrl = hasInjectedOpenaiBaseUrl(out);
1355
+ out = stripInjectedOpenaiBaseUrl(out); // before removeOcxSection — it keys on the marker line too
1356
+ if (out.includes("[model_providers.opencodex]")) {
1357
+ out = removeOcxSection(out);
1358
+ }
1359
+ out = removeProfileSection(out);
1360
+ /*
1361
+ * Remove exact marker-owned replacement values while the displaced user
1362
+ * lines are still comments. Legacy cleanup below can then remove unmarked
1363
+ * pre-marker residue without mistaking a restored user value for ours.
1364
+ */
1365
+ const temporary = stripTemporarySettingValues(out);
1366
+ out = temporary.content;
1367
+ // Regex (not exact-string) removal so compact `model_provider="opencodex"` is stripped too —
1368
+ // must match the detection regex above, or a detected line could survive un-removed.
1369
+ out = out
1370
+ .split("\n")
1371
+ .filter((l) => !/^\s*model_provider\s*=\s*"opencodex"\s*$/.test(l))
1372
+ .join("\n");
1373
+ // Routed root model ids (`model = "provider/slug"`) only make sense while the proxy serves
1374
+ // them — strip on both the legacy re-tag form and the Design B injected-base-url form.
1375
+ if (hadRootOcxProvider || hadInjectedBaseUrl) out = stripRootRoutedModel(out);
1376
+ const managedDefaults = transformManagedSubagentDefaults(out, null);
1377
+ if (managedDefaults.ok) out = managedDefaults.content;
1378
+ out = stripOpencodexCatalogPath(out);
1379
+ if (!temporary.error) out = restorePreservedSettingLines(out);
1380
+ return {
1381
+ content: out.replace(/\n{3,}/g, "\n\n").trimEnd() + "\n",
1382
+ managedDefaultsError: !managedDefaults.ok ? managedDefaults.error : null,
1383
+ temporarySettingsError: temporary.error,
1384
+ };
1385
+ }
1386
+
1387
+ /** Pure transform: strip the opencodex provider block + `model_provider = "opencodex"` lines. */
1388
+ export function stripOpencodexConfig(content: string): string {
1389
+ return stripOpencodexConfigResult(content).content;
1390
+ }
1391
+
1392
+ function hasOpencodexRouting(content: string): boolean {
1393
+ return (
1394
+ content.includes("[model_providers.opencodex]") ||
1395
+ /^\s*model_provider\s*=\s*"opencodex"/m.test(content) ||
1396
+ hasInjectedOpenaiBaseUrl(content)
1397
+ );
1398
+ }
1399
+
1400
+ export function removeCodexConfig(
1401
+ options: { preserveProfile?: boolean } = {},
1402
+ ): { success: boolean; message: string } {
1403
+ if (!existsSync(CODEX_CONFIG_PATH)) {
1404
+ if (!options.preserveProfile && existsSync(CODEX_PROFILE_PATH))
1405
+ unlinkSync(CODEX_PROFILE_PATH);
1406
+ return {
1407
+ success: true,
1408
+ message: `Codex config not found; no native restore was needed${options.preserveProfile ? "." : ", and the Remodex profile was removed if present."}`,
1409
+ };
1410
+ }
1411
+ const rawContent = readFileSync(CODEX_CONFIG_PATH, "utf-8");
1412
+ // Same EOL boundary as inject: strip in LF space, write back in the file's own ending.
1413
+ // The unchanged fast path compares in LF space so an untouched file is never rewritten.
1414
+ const eol = dominantEol(rawContent);
1415
+ const content = applyEol(rawContent, "\n");
1416
+ const had = hasOpencodexRouting(content);
1417
+ const stripped = stripOpencodexConfigResult(content);
1418
+ if (stripped.temporarySettingsError) {
1419
+ return {
1420
+ success: false,
1421
+ message:
1422
+ `Codex config was left unchanged because a Remodex temporary setting could not be verified: ${stripped.temporarySettingsError}. ` +
1423
+ "Inspect $CODEX_HOME/config.toml before stopping native routing.",
1424
+ };
1425
+ }
1426
+ if (had || stripped.content !== content) {
1427
+ atomicWriteFile(CODEX_CONFIG_PATH, applyEol(stripped.content, eol));
1428
+ }
1429
+ if (!options.preserveProfile && existsSync(CODEX_PROFILE_PATH))
1430
+ unlinkSync(CODEX_PROFILE_PATH);
1431
+ const removedMessage = had
1432
+ ? `Removed Remodex routing from Codex config${options.preserveProfile ? "." : " + profile."}`
1433
+ : "Remodex is not present in Codex config.";
1434
+ if (stripped.managedDefaultsError) {
1435
+ const routingMessage = had
1436
+ ? removedMessage
1437
+ : "No Remodex routing was present in Codex config.";
1438
+ return {
1439
+ success: false,
1440
+ message:
1441
+ `${routingMessage} Native Codex sub-agent defaults could not be safely removed: ${stripped.managedDefaultsError}. ` +
1442
+ "The ambiguous marker and adjacent value were preserved; inspect $CODEX_HOME/config.toml before using native Codex.",
1443
+ };
1444
+ }
1445
+ return {
1446
+ success: true,
1447
+ message: removedMessage,
1448
+ };
1449
+ }
1450
+
1451
+ export type CodexRestoreArtifactState = "ok" | "skipped" | "failed";
1452
+
1453
+ export interface CodexRestoreConfigResult {
1454
+ state: CodexRestoreArtifactState;
1455
+ changed: boolean;
1456
+ action: "journal-restored" | "owned-fields-stripped" | "external-provider-preserved" | "failed";
1457
+ message: string;
1458
+ }
1459
+
1460
+ export interface CodexRestoreCatalogResult {
1461
+ state: CodexRestoreArtifactState;
1462
+ changed: boolean;
1463
+ removed: number;
1464
+ kept: number;
1465
+ path: string | null;
1466
+ message: string;
1467
+ }
1468
+
1469
+ export interface CodexRestoreHistoryResult {
1470
+ state: CodexRestoreArtifactState;
1471
+ changed: boolean;
1472
+ reason?: CodexHistoryFailureReason;
1473
+ rows: number;
1474
+ files: number;
1475
+ ejectedRows: number;
1476
+ message: string;
1477
+ }
1478
+
1479
+ export interface CodexNativeRestoreResult {
1480
+ success: boolean;
1481
+ message: string;
1482
+ externalProvider?: string;
1483
+ artifacts: {
1484
+ config: CodexRestoreConfigResult;
1485
+ catalog: CodexRestoreCatalogResult;
1486
+ history: CodexRestoreHistoryResult;
1487
+ };
1488
+ }
1489
+
1490
+ function failedHistoryRestore(reason?: CodexHistoryFailureReason, detail?: string): CodexRestoreHistoryResult {
1491
+ return {
1492
+ state: "failed",
1493
+ changed: false,
1494
+ ...(reason ? { reason } : {}),
1495
+ rows: 0,
1496
+ files: 0,
1497
+ ejectedRows: 0,
1498
+ message: reason === "permission"
1499
+ ? "Codex resume history could NOT be restored because permission was denied."
1500
+ : reason === "busy"
1501
+ ? "Codex resume history could NOT be restored — the Codex app appears to be holding the history database."
1502
+ : detail
1503
+ ? `Codex resume history could NOT be restored: ${detail}`
1504
+ : "Codex resume history could NOT be restored; the reason was not recorded. Run 'rmx doctor'.",
1505
+ };
1506
+ }
1507
+
1508
+ /**
1509
+ * Restore failure wording for a Worker outcome.
1510
+ *
1511
+ * Only a genuine busy result blames the Codex app. An unsafe-path refusal, an
1512
+ * unavailable coordinator database, a permission denial, or a dead/timed-out
1513
+ * worker is a different problem; the old collapse made every one of those read
1514
+ * as "the Codex app is holding the database" (issue #1191). `busy` and
1515
+ * `permission` keep the restore-specific sentence built by
1516
+ * `failedHistoryRestore`; every other reason reuses the single formatter so
1517
+ * the two modules cannot drift apart.
1518
+ */
1519
+ export function failedHistoryRestoreFromOutcome(
1520
+ outcome: Extract<CodexHistoryJobOutcome, { kind: "blocked" | "failed" }>,
1521
+ ): CodexRestoreHistoryResult {
1522
+ if (outcome.kind === "blocked" && outcome.reason === "busy") return failedHistoryRestore("busy");
1523
+ if (outcome.kind === "failed" && outcome.historyFailureReason === "busy") return failedHistoryRestore("busy");
1524
+ if (outcome.kind === "failed" && outcome.historyFailureReason === "permission") {
1525
+ return failedHistoryRestore("permission");
1526
+ }
1527
+ return failedHistoryRestore(undefined, describeHistoryJobFailure(outcome, "restore"));
1528
+ }
1529
+
1530
+ function externalProviderRestoreResult(activeProvider: string): CodexNativeRestoreResult {
1531
+ const message = `External Codex provider ${tomlString(activeProvider)} preserved; no native restore was needed.`;
1532
+ return {
1533
+ success: true,
1534
+ message,
1535
+ externalProvider: activeProvider,
1536
+ artifacts: {
1537
+ config: { state: "skipped", changed: false, action: "external-provider-preserved", message },
1538
+ catalog: { state: "skipped", changed: false, removed: 0, kept: 0, path: null, message },
1539
+ history: { state: "skipped", changed: false, rows: 0, files: 0, ejectedRows: 0, message },
1540
+ },
1541
+ };
1542
+ }
1543
+
1544
+ /** A foreign service claim is an authority boundary, including explicit CLI restore. */
1545
+ function foreignOwnershipRestoreRefusal(message: string): CodexNativeRestoreResult {
1546
+ return {
1547
+ success: false,
1548
+ message: `Codex native restore refused: ${message}`,
1549
+ artifacts: {
1550
+ config: { state: "skipped", changed: false, action: "failed", message },
1551
+ catalog: { state: "skipped", changed: false, removed: 0, kept: 0, path: null, message },
1552
+ history: { state: "skipped", changed: false, rows: 0, files: 0, ejectedRows: 0, message },
1553
+ },
1554
+ };
1555
+ }
1556
+
1557
+ function desiredEnabledRestoreSkip(): CodexNativeRestoreResult {
1558
+ const message = "Codex integration was re-enabled; native restore was skipped.";
1559
+ return skippedRestoreEnvelope(true, message);
1560
+ }
1561
+
1562
+ /**
1563
+ * A schema-complete all-skipped envelope for outcomes decided before any
1564
+ * restore machinery runs. Every `restore --json` path must stay shape-stable
1565
+ * with `CodexNativeRestoreResult`; consumers never special-case early exits.
1566
+ */
1567
+ export function skippedRestoreEnvelope(success: boolean, message: string): CodexNativeRestoreResult {
1568
+ return {
1569
+ success,
1570
+ message,
1571
+ artifacts: {
1572
+ config: { state: "skipped", changed: false, action: "owned-fields-stripped", message },
1573
+ catalog: { state: "skipped", changed: false, removed: 0, kept: 0, path: null, message },
1574
+ history: { state: "skipped", changed: false, rows: 0, files: 0, ejectedRows: 0, message },
1575
+ },
1576
+ };
1577
+ }
1578
+
1579
+ /** The config/profile half of a native restore, reported as one artifact. */
1580
+ function restoreCodexConfigInline(): CodexRestoreConfigResult {
1581
+ try {
1582
+ const journal = restoreJournalState();
1583
+ const restored = journal.configRestored
1584
+ ? { success: true, message: "Codex config restored from Remodex journal." }
1585
+ : removeCodexConfig({ preserveProfile: journal.profileRestored || journal.profileChanged });
1586
+ return restored.success
1587
+ ? {
1588
+ state: "ok",
1589
+ changed: journal.configRestored || journal.profileRestored || journal.profileChanged || restored.message.startsWith("Removed"),
1590
+ action: journal.configRestored ? "journal-restored" : "owned-fields-stripped",
1591
+ message: restored.message,
1592
+ }
1593
+ : { state: "failed", changed: false, action: "failed", message: restored.message };
1594
+ } catch (error) {
1595
+ return { state: "failed", changed: false, action: "failed", message: error instanceof Error ? error.message : String(error) };
1596
+ }
1597
+ }
1598
+
1599
+ /** The catalog half, always inside its own K acquisition. */
1600
+ function restoreCodexCatalogArtifact(revalidateDesiredState: boolean): CodexRestoreCatalogResult {
1601
+ const owningCodexHome = getCodexHome();
1602
+ try {
1603
+ const restored = withCatalogWriteSerialization(owningCodexHome, permit =>
1604
+ revalidateDesiredState && shouldSyncCodexOnStart(loadConfig())
1605
+ ? null
1606
+ : restoreCodexCatalogWithPermit(permit, owningCodexHome));
1607
+ return restored.kind === "completed" && restored.value !== null
1608
+ ? { state: "ok", changed: restored.value.removed > 0, ...restored.value, message: "Codex catalog restored." }
1609
+ : restored.kind === "completed"
1610
+ ? {
1611
+ state: "skipped", changed: false, removed: 0, kept: 0, path: null,
1612
+ message: "Codex integration was re-enabled; native catalog restoration was skipped.",
1613
+ }
1614
+ : {
1615
+ state: "failed", changed: false, removed: 0, kept: 0, path: DEFAULT_CATALOG_PATH,
1616
+ message: `Codex catalog could not be restored: ${restored.reason}.`,
1617
+ };
1618
+ } catch (error) {
1619
+ return {
1620
+ state: "failed", changed: false, removed: 0, kept: 0, path: DEFAULT_CATALOG_PATH,
1621
+ message: error instanceof Error ? error.message : String(error),
1622
+ };
1623
+ }
1624
+ }
1625
+
1626
+ /**
1627
+ * Restore native Codex, running history in a Worker under H.
1628
+ *
1629
+ * On a coordinated home the config/profile restore happens INSIDE the Codex
1630
+ * write lock, publishing a `remove` transition — the same serialization inject
1631
+ * uses. Without it, an older restore could overwrite a config a concurrent
1632
+ * enable had just written under the lock, and then honestly report success
1633
+ * while desired intent said ON. The desired-state re-read under the lock turns
1634
+ * that lost race into the discriminated `desired_enabled` skip.
1635
+ */
1636
+ export async function restoreNativeCodexAsync(
1637
+ options: { revalidateDesiredState?: boolean } = {},
1638
+ ): Promise<CodexNativeRestoreResult> {
1639
+ const activeProvider = currentExternalCodexModelProvider();
1640
+ if (activeProvider) {
1641
+ // External-provider courtesy: only the stale journal is removed. The
1642
+ // history worker must not launch — it would turn a read-mostly courtesy
1643
+ // result into a history mutation on a home we do not own.
1644
+ removeJournal();
1645
+ return externalProviderRestoreResult(activeProvider);
1646
+ }
1647
+
1648
+ // `restore` normally honours a human request even when an unrelated
1649
+ // service-manager probe is unavailable. A recorded FOREIGN home is not an
1650
+ // unrelated probe: it is positive evidence another installation owns these
1651
+ // native artifacts, so do not create profile/claim locks before refusing.
1652
+ if (options.revalidateDesiredState) {
1653
+ const ownership = inspectNativeCodexOwnership();
1654
+ if (ownership.ownership === "foreign") return foreignOwnershipRestoreRefusal(ownership.reason);
1655
+ }
1656
+
1657
+ const eligibility = codexWriteCoordinationEligibility({
1658
+ coordinatorPath: () =>
1659
+ resolveCodexCoordinatorDatabasePath(resolveEffectiveUserIdentity(), getCodexHome()),
1660
+ residue: () => classifyNativeRoutedResidue(),
1661
+ integrationRecord: () => readIntegrationRecord(),
1662
+ });
1663
+
1664
+ let config: CodexRestoreConfigResult;
1665
+ let transitionReceipt: { nativeGeneration: number; currentTxId: string } | undefined;
1666
+
1667
+ if (eligibility.kind === "coordinated") {
1668
+ // The restore has no candidate bytes to witness; freshness comes from the
1669
+ // filesystem reads and the desired-state re-read performed under the lock.
1670
+ const witness = { authoritySnapshotId: "codex-native-restore" };
1671
+ const coordinated = await withCodexWriteLock(
1672
+ {
1673
+ timeoutMs: DEFAULT_INJECT_LOCK_TIMEOUT_MS,
1674
+ admitted: witness,
1675
+ readAdmissionUnderLock: () => witness,
1676
+ },
1677
+ (ctx) => {
1678
+ if (options.revalidateDesiredState && shouldSyncCodexOnStart(loadConfig())) {
1679
+ throw new CodexWriteLockSkipped("desired_enabled");
1680
+ }
1681
+ const published = ctx.coordinator.beginTransition(
1682
+ {
1683
+ nativeGeneration: ctx.expectation.nativeBefore,
1684
+ currentTxId: ctx.currentTxId,
1685
+ },
1686
+ {
1687
+ txId: ctx.expectation.txId,
1688
+ direction: "remove",
1689
+ authoritySnapshotId: ctx.admission.authoritySnapshotId,
1690
+ nextRetryAt: new Date().toISOString(),
1691
+ },
1692
+ );
1693
+ if (published.kind !== "updated") {
1694
+ throw new CodexWriteConflictError(
1695
+ `The Codex transition could not be published: ${published.kind}.`,
1696
+ );
1697
+ }
1698
+ const preImages = captureCodexPreImages();
1699
+ let restored: CodexRestoreConfigResult;
1700
+ try {
1701
+ restored = restoreCodexConfigInline();
1702
+ } catch (error) {
1703
+ const compensated = restoreCodexPreImages(preImages);
1704
+ if (!compensated.complete) throw new CodexPartialWriteError(compensated.unrestored);
1705
+ throw error;
1706
+ }
1707
+ return {
1708
+ config: restored,
1709
+ receipt: {
1710
+ nativeGeneration: ctx.expectation.nativeAfter,
1711
+ currentTxId: ctx.expectation.txId,
1712
+ },
1713
+ };
1714
+ },
1715
+ );
1716
+ if (coordinated.status === "skipped") return desiredEnabledRestoreSkip();
1717
+ if (coordinated.status !== "acquired") {
1718
+ config = {
1719
+ state: "failed",
1720
+ changed: false,
1721
+ action: "failed",
1722
+ message: coordinated.status === "busy"
1723
+ ? `Another process is writing Codex configuration right now (waited ${coordinated.waitedMs}ms). Retry shortly.`
1724
+ : `Codex configuration was not restored: ${coordinated.message}`,
1725
+ };
1726
+ } else {
1727
+ config = coordinated.value.config;
1728
+ transitionReceipt = coordinated.value.receipt;
1729
+ }
1730
+ } else {
1731
+ // Legacy-uncoordinated (or unresolvable) homes keep the unserialized path
1732
+ // they have always had; restore is the escape hatch and must not strand
1733
+ // them. The plain re-read still honors an intervening re-enable.
1734
+ if (options.revalidateDesiredState && shouldSyncCodexOnStart(loadConfig())) {
1735
+ return desiredEnabledRestoreSkip();
1736
+ }
1737
+ config = restoreCodexConfigInline();
1738
+ }
1739
+
1740
+ const catalog = restoreCodexCatalogArtifact(options.revalidateDesiredState === true);
1741
+ const outcome = await runCodexHistoryJob({
1742
+ ...resolveCodexHistoryJobTarget(),
1743
+ ...(options.revalidateDesiredState ? { expectedDesiredEnabled: false } : {}),
1744
+ operation: deriveCodexHistoryOperation({ direction: "restore", resumeHistory: true, legacyMode: false }),
1745
+ });
1746
+ if (transitionReceipt) {
1747
+ resolveCodexHistoryTransition(transitionReceipt, outcome);
1748
+ }
1749
+ const history: CodexRestoreHistoryResult = outcome.kind === "converged"
1750
+ ? {
1751
+ state: "ok", changed: outcome.rows > 0, rows: outcome.rows, files: outcome.files, ejectedRows: 0,
1752
+ message: outcome.rows > 0
1753
+ ? `Resume history restored from Remodex backup (${outcome.rows} thread(s)).`
1754
+ : "Codex resume history was already native.",
1755
+ }
1756
+ : outcome.kind === "skipped"
1757
+ ? { state: "skipped", changed: false, rows: 0, files: 0, ejectedRows: 0, message: "Codex resume history was skipped." }
1758
+ : outcome.kind === "blocked" && (outcome.reason === "desired_disabled" || outcome.reason === "desired_enabled")
1759
+ ? {
1760
+ state: "skipped", changed: false, rows: 0, files: 0, ejectedRows: 0,
1761
+ message: outcome.reason === "desired_disabled"
1762
+ ? "Codex integration was disabled; history restoration was skipped."
1763
+ : "Codex integration was enabled; history restoration was skipped.",
1764
+ }
1765
+ : outcome.kind === "blocked" || outcome.kind === "failed"
1766
+ ? failedHistoryRestoreFromOutcome(outcome)
1767
+ : failedHistoryRestore();
1768
+ const base = catalog.removed > 0
1769
+ ? `${config.message} Catalog restored to ${catalog.kept} native model(s) (dropped ${catalog.removed} proxy-routed).`
1770
+ : config.message;
1771
+ const success = config.state !== "failed"
1772
+ && catalog.state !== "failed"
1773
+ && history.state !== "failed";
1774
+ return {
1775
+ success,
1776
+ message: `${base}${history.state === "failed" ? ` ⚠️ ${history.message}` : ""}`,
1777
+ artifacts: { config, catalog, history },
1778
+ };
1779
+ }
1780
+
1781
+ export function restoreNativeCodex(options: { skipHistory?: boolean; revalidateDesiredState?: boolean } = {}): CodexNativeRestoreResult {
1782
+ const activeProvider = currentExternalCodexModelProvider();
1783
+ if (activeProvider) {
1784
+ removeJournal();
1785
+ return externalProviderRestoreResult(activeProvider);
1786
+ }
1787
+ if (options.revalidateDesiredState && shouldSyncCodexOnStart(loadConfig())) {
1788
+ return desiredEnabledRestoreSkip();
1789
+ }
1790
+ const config = restoreCodexConfigInline();
1791
+ const catalog = restoreCodexCatalogArtifact(options.revalidateDesiredState === true);
1792
+ // Design B (loopback) steady state: threads are already tagged openai, so prove the
1793
+ // no-op with a readonly probe instead of write-opening a DB the Codex app may hold
1794
+ // (Windows: WAL writer lock -> seconds of stalling + a false warning on every stop).
1795
+ // Legacy (non-loopback) installs keep the unconditional write-open restore.
1796
+ let skipWhenProvablyNoop = false;
1797
+ try {
1798
+ skipWhenProvablyNoop = !shouldInjectApiAuthHeader(loadConfig());
1799
+ } catch {
1800
+ /* unreadable config: keep the conservative write-open restore */
1801
+ }
1802
+ // `skipHistory` is how the async wrapper takes this work for itself: the
1803
+ // native files come down here, and history runs in the Worker under H.
1804
+ const rawHistory = options.skipHistory
1805
+ ? { rows: 0, files: 0 }
1806
+ : syncCodexHistoryProvider("openai", undefined, undefined, {
1807
+ skipWhenProvablyNoop,
1808
+ });
1809
+ const history: CodexRestoreHistoryResult = options.skipHistory
1810
+ ? { state: "skipped", changed: false, rows: 0, files: 0, ejectedRows: 0, message: "History restoration runs asynchronously." }
1811
+ : rawHistory.failed
1812
+ ? failedHistoryRestore(rawHistory.failureReason)
1813
+ : {
1814
+ state: "ok",
1815
+ changed: rawHistory.rows > 0 || (rawHistory.ejectedRows ?? 0) > 0,
1816
+ rows: rawHistory.rows,
1817
+ files: rawHistory.files,
1818
+ ejectedRows: rawHistory.ejectedRows ?? 0,
1819
+ message: rawHistory.rows > 0
1820
+ ? `Resume history restored from Remodex backup (${rawHistory.rows} thread(s)).`
1821
+ : "Codex resume history was already native.",
1822
+ };
1823
+ const message = catalog.removed > 0
1824
+ ? `${config.message} Catalog restored to ${catalog.kept} native model(s) (dropped ${catalog.removed} proxy-routed).`
1825
+ : config.message;
1826
+ return {
1827
+ success: config.state !== "failed" && catalog.state !== "failed" && history.state !== "failed",
1828
+ message,
1829
+ artifacts: { config, catalog, history },
1830
+ };
1831
+ }
1832
+
1833
+ export function getCodexConfigPath(): string {
1834
+ return CODEX_CONFIG_PATH;
1835
+ }
1836
+
1837
+ /**
1838
+ * Frame one failed apply history job honestly.
1839
+ *
1840
+ * A genuine lock keeps the established deferred/SKIPPED wording; any other
1841
+ * reason names itself instead of blaming the Codex app/IDE.
1842
+ */
1843
+ export function formatApplyHistoryFailure(outcome: CodexHistoryJobOutcome, legacyMode: boolean): string {
1844
+ // A busy database is a deferral no matter which half observed it: the lock
1845
+ // contended (blocked/busy), or the worker acquired the lock and then found
1846
+ // SQLite busy (failed with a busy history reason). Only those keep the
1847
+ // deferred headline; every other failure is a real "NOT changed".
1848
+ const busy =
1849
+ (outcome.kind === "blocked" && outcome.reason === "busy") ||
1850
+ (outcome.kind === "failed" && outcome.historyFailureReason === "busy");
1851
+ const headline = legacyMode
1852
+ ? "Codex resume history sync SKIPPED"
1853
+ : busy
1854
+ ? "Codex resume history migration deferred"
1855
+ : "Codex resume history NOT changed";
1856
+ return ` ⚠️ ${headline}: ${describeHistoryJobFailure(outcome, "apply", legacyMode)}\n`;
1857
+ }