@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
package/src/types.ts ADDED
@@ -0,0 +1,1531 @@
1
+ import type { KiroOAuthMetadata } from "./oauth/types";
2
+
3
+ export interface OcxParsedRequest {
4
+ modelId: string;
5
+ /** Client-facing model selector retained for Anthropic routes after wire-model normalization. */
6
+ _responseModelId?: string;
7
+ /** Selected OpenAI API virtual-model id retained after it rewrites the upstream wire model. */
8
+ _openAiVirtualSelectedModelId?: string;
9
+ previousResponseId?: string;
10
+ context: OcxContext;
11
+ stream: boolean;
12
+ options: OcxRequestOptions;
13
+ _rawBody?: unknown;
14
+ /** Number of leading raw input items restored from local previous_response_id state. */
15
+ _replayPrefixLen?: number;
16
+ /** True when the proxy expanded a previous_response_id request into a full input replay. */
17
+ _previousResponseInputExpanded?: boolean;
18
+ /** Provider-private stable Cursor conversation id resolved from the Responses previous_response_id chain. */
19
+ _cursorConversationId?: string;
20
+ /** Stable upstream client thread identity, used only to derive provider-scoped continuation ids. */
21
+ _clientThreadId?: string;
22
+ /**
23
+ * Optional authenticated tenant/operator namespace for Cursor thread→conversation derivation.
24
+ * When absent (single-operator local proxy), derivation stays local-scoped.
25
+ */
26
+ _cursorIdentityScope?: string;
27
+ /**
28
+ * True for helper/shadow/compaction turns that must not append into the main Cursor conversation
29
+ * derived from the parent thread id.
30
+ */
31
+ _cursorIsolateConversation?: boolean;
32
+ /** Account-scoped, non-secret Kiro request metadata selected with the OAuth access token. */
33
+ _kiroAuthContext?: Pick<KiroOAuthMetadata, "profileArn" | "apiRegion" | "ssoRegion">;
34
+ /** Provider-private continuation metadata resolved from the Responses previous_response_id chain. */
35
+ _providerContinuation?: OcxProviderContinuationState;
36
+ /**
37
+ * The hosted `{type:"web_search", ...}` tool config, stashed when Codex enables web search. Routed
38
+ * (non-OpenAI) providers can't run it server-side, so the proxy re-exposes it as a function tool and
39
+ * executes searches via the gpt-5.4-mini sidecar (see src/web-search). Absent when not requested.
40
+ */
41
+ _webSearch?: Record<string, unknown>;
42
+ /** Hosted image_generation tool config stashed for the image bridge sidecar (see src/images). */
43
+ _imageGeneration?: { toolNames: Set<string>; originalTool?: Record<string, unknown> };
44
+ /**
45
+ * True when Codex requested structured output (`text.format` = json_schema/json_object). The
46
+ * web-search tool_result is then rendered as compact JSON instead of markdown prose, so its
47
+ * answer/"Sources:" text can't bleed into and corrupt the model's schema-constrained output.
48
+ */
49
+ _structuredOutput?: boolean;
50
+ /**
51
+ * True when the input carried `{type:"compaction_trigger"}` — Codex remote compaction v2 asking
52
+ * this turn to produce a `{type:"compaction"}` output item. Routed adapters can't natively;
53
+ * the server runs the model as a summarizer and the bridge emits a synthetic compaction item
54
+ * (see src/responses/compaction.ts).
55
+ */
56
+ _compactionRequest?: boolean;
57
+ /**
58
+ * True when the current request newly introduced a stored compaction summary/marker. Historical
59
+ * markers restored by previous_response_id expansion were already acknowledged and do not reset
60
+ * provider-private continuation caches again on every later turn.
61
+ */
62
+ _contextCompactionBoundary?: boolean;
63
+ }
64
+
65
+ export interface OcxContext {
66
+ systemPrompt?: string[];
67
+ messages: OcxMessage[];
68
+ tools?: OcxTool[];
69
+ }
70
+
71
+ export type OcxMessage =
72
+ | OcxUserMessage
73
+ | OcxAssistantMessage
74
+ | OcxDeveloperMessage
75
+ | OcxToolResultMessage;
76
+
77
+ export interface OcxUserMessage {
78
+ role: "user";
79
+ content: string | OcxContentPart[];
80
+ timestamp: number;
81
+ }
82
+
83
+ export interface OcxAssistantMessage {
84
+ role: "assistant";
85
+ content: OcxAssistantContentPart[];
86
+ /** Responses message phase, preserved when replaying translated provider output. */
87
+ phase?: OcxMessagePhase;
88
+ model?: string;
89
+ timestamp: number;
90
+ /**
91
+ * Kiro `reasoningContent.redactedContent` for THIS assistant turn — an opaque encrypted blob
92
+ * Kiro replays to preserve model reasoning across turns. Provider-specific and unrenderable, so
93
+ * it rides the message rather than a content part: any other adapter simply ignores it.
94
+ */
95
+ kiroRedactedReasoning?: string;
96
+ }
97
+
98
+ export interface OcxDeveloperMessage {
99
+ role: "developer";
100
+ content: string | OcxContentPart[];
101
+ timestamp: number;
102
+ }
103
+
104
+ export interface OcxToolResultMessage {
105
+ role: "toolResult";
106
+ toolCallId: string;
107
+ toolName: string;
108
+ /** MCP namespace from the originating tool call, if any. */
109
+ toolNamespace?: string;
110
+ /** Text, or content parts when a tool (e.g. Codex view_image) returns an image in its output. */
111
+ content: string | OcxContentPart[];
112
+ /** True when the Responses result contained opaque encrypted output Kiro cannot translate. */
113
+ containsEncryptedContent?: boolean;
114
+ isError: boolean;
115
+ timestamp: number;
116
+ }
117
+
118
+ export interface OcxTextContent {
119
+ type: "text";
120
+ text: string;
121
+ }
122
+
123
+ export interface OcxImageContent {
124
+ type: "image";
125
+ /** A `data:` URL (base64) or a remote https URL — passed through from Codex verbatim, NEVER inlined as text. */
126
+ imageUrl: string;
127
+ /** Fidelity hint from Codex: "low" | "high" | "auto". */
128
+ detail?: string;
129
+ }
130
+
131
+ /** A user/developer message content part: text or an image (vision). */
132
+ export type OcxContentPart = OcxTextContent | OcxImageContent;
133
+
134
+ export interface OcxThinkingContent {
135
+ type: "thinking";
136
+ thinking: string;
137
+ signature?: string;
138
+ itemId?: string;
139
+ /** Raw Anthropic redacted_thinking block payloads to replay verbatim (order preserved). */
140
+ redacted?: string[];
141
+ }
142
+
143
+ export interface OcxToolCall {
144
+ type: "toolCall";
145
+ id: string;
146
+ name: string;
147
+ arguments: Record<string, unknown>;
148
+ customWireName?: string;
149
+ thoughtSignature?: string;
150
+ /** MCP namespace (e.g. "mcp__context7") when this call targets a namespaced tool. */
151
+ namespace?: string;
152
+ }
153
+
154
+ export type OcxAssistantContentPart = OcxTextContent | OcxThinkingContent | OcxToolCall;
155
+
156
+ export interface OcxTool {
157
+ name: string;
158
+ description: string;
159
+ parameters: Record<string, unknown>;
160
+ strict?: boolean;
161
+ /** MCP namespace (e.g. "mcp__context7") for tools flattened out of a Responses "namespace" tool. */
162
+ namespace?: string;
163
+ /** Freeform/custom tool (e.g. apply_patch): the model's call must be relayed as a custom_tool_call. */
164
+ freeform?: boolean;
165
+ /** Client-executed tool discovery (tool_search): the model's call must be relayed as a tool_search_call. */
166
+ toolSearch?: boolean;
167
+ /** Tool definition restored from a prior tool_search output; transports may prioritize it when catalogs are bounded. */
168
+ loadedFromToolSearch?: boolean;
169
+ /** Cursor-only synthetic exact-match edit tool; never inferred from the wire name. */
170
+ cursorStructuredEdit?: true;
171
+ /** Synthetic web_search tool: the model's call is executed by the gpt-5.4-mini sidecar, not relayed to Codex. */
172
+ webSearch?: boolean;
173
+ /** Synthetic image_gen tool: the model's call is executed by the xAI image bridge sidecar, not relayed to Codex. */
174
+ imageGeneration?: boolean;
175
+ /** Synthetic video_gen tool: executed by the xAI video bridge sidecar. */
176
+ videoGeneration?: boolean;
177
+ }
178
+
179
+ /**
180
+ * Wire name a chat model sees for a tool. Namespaced (MCP) tools are flattened to
181
+ * "<namespace>__<name>" so they survive the chat-completions function-tool format;
182
+ * the proxy maps this back to {namespace, name} on the return trip (Codex routes MCP
183
+ * calls by an explicit `namespace` field, not by parsing the name).
184
+ */
185
+ export function namespacedToolName(namespace: string | undefined, name: string): string {
186
+ return namespace ? `${namespace}__${name}` : name;
187
+ }
188
+
189
+ export function toolChoiceAliases(tool: Pick<OcxTool, "namespace" | "name">): string[] {
190
+ const wireName = namespacedToolName(tool.namespace, tool.name);
191
+ return tool.namespace ? [wireName, `${tool.namespace}.${tool.name}`] : [wireName];
192
+ }
193
+
194
+ export function toolAllowedByChoice(tool: Pick<OcxTool, "namespace" | "name">, allowedTools: ReadonlySet<string>): boolean {
195
+ return toolChoiceAliases(tool).some(name => allowedTools.has(name));
196
+ }
197
+
198
+ export function resolveToolChoiceWireName(tools: readonly Pick<OcxTool, "namespace" | "name">[] | undefined, name: string): string {
199
+ const match = tools?.find(tool => toolChoiceAliases(tool).includes(name));
200
+ return match ? namespacedToolName(match.namespace, match.name) : name;
201
+ }
202
+
203
+ /**
204
+ * Whether `modelId` is in a per-provider classification list (e.g. `noVisionModels`). Matches the full
205
+ * id, OR — for Ollama-style ids — the family before the ":size" tag, so a `gpt-oss` entry covers
206
+ * `gpt-oss:120b`/`gpt-oss:20b`. Colon-less ids (e.g. `grok-build-0.1`) still match exactly only.
207
+ */
208
+ export function modelInList(list: string[] | undefined, modelId: string): boolean {
209
+ if (!list || list.length === 0) return false;
210
+ if (list.includes(modelId)) return true;
211
+ const colon = modelId.indexOf(":");
212
+ return colon > 0 && list.includes(modelId.slice(0, colon));
213
+ }
214
+
215
+ export type OcxToolChoice =
216
+ | "auto"
217
+ | "none"
218
+ | "required"
219
+ | { name: string }
220
+ | { allowedTools: string[]; mode: "auto" | "required" };
221
+
222
+ export function isAllowedToolChoice(value: OcxToolChoice | undefined): value is { allowedTools: string[]; mode: "auto" | "required" } {
223
+ return typeof value === "object" && value !== null && "allowedTools" in value;
224
+ }
225
+
226
+ export interface OcxRequestOptions {
227
+ maxOutputTokens?: number;
228
+ temperature?: number;
229
+ topP?: number;
230
+ stopSequences?: string[];
231
+ toolChoice?: OcxToolChoice;
232
+ parallelToolCalls?: boolean;
233
+ reasoning?: string;
234
+ hideThinkingSummary?: boolean;
235
+ serviceTier?: string;
236
+ presencePenalty?: number;
237
+ frequencyPenalty?: number;
238
+ /** Responses prompt-cache affinity key. Passthrough preserves it via _rawBody; routed adapters do not consume it unless their upstream wire supports it. */
239
+ promptCacheKey?: string;
240
+ /**
241
+ * Responses `text.format` (json_schema / json_object), preserved for adapters whose
242
+ * upstream wire has an equivalent. The openai-chat adapter re-nests it as chat
243
+ * `response_format`, the exact inverse of responseFormatToText in src/chat/inbound.ts.
244
+ * The native passthrough ignores it (it forwards `_rawBody.text` verbatim) and Kiro
245
+ * keeps rejecting structured output via `_structuredOutput`.
246
+ */
247
+ textFormat?: {
248
+ type: "json_schema" | "json_object";
249
+ name?: string;
250
+ description?: string;
251
+ schema?: Record<string, unknown>;
252
+ strict?: boolean;
253
+ };
254
+ }
255
+
256
+ export type OcxMessagePhase = "commentary" | "final_answer";
257
+
258
+ /**
259
+ * Provider-private state that must follow a locally expanded `previous_response_id` chain.
260
+ * Kept out of public Responses output and persisted only in the bounded local continuation cache.
261
+ */
262
+ export interface OcxProviderContinuationState {
263
+ cursor?: {
264
+ conversationId?: string;
265
+ checkpointUsable?: boolean;
266
+ };
267
+ kiro?: {
268
+ conversationId?: string;
269
+ };
270
+ [provider: string]: Record<string, unknown> | undefined;
271
+ }
272
+
273
+ export type AdapterEvent =
274
+ | { type: "heartbeat" }
275
+ | { type: "text_delta"; text: string; phase?: OcxMessagePhase }
276
+ | { type: "thinking_delta"; thinking: string }
277
+ // Anthropic extended-thinking round-trip: signature_delta for the current thinking block, and
278
+ // opaque redacted_thinking blocks. Both must be replayed verbatim or tool-use turns 400.
279
+ | { type: "thinking_signature"; signature: string }
280
+ | { type: "redacted_thinking"; data: string }
281
+ // Kiro reasoning round-trip: the encrypted `redactedContent` blob for the CURRENT assistant turn.
282
+ // Never rendered — it only rides the reasoning item's envelope so the next request can replay it.
283
+ | { type: "kiro_redacted_reasoning"; data: string }
284
+ | { type: "reasoning_raw_delta"; text: string }
285
+ | { type: "tool_call_start"; id: string; name: string }
286
+ | { type: "tool_call_delta"; arguments: string }
287
+ | { type: "tool_call_end" }
288
+ /** Internal boundary between a guarded first pass and its one-shot continuation. */
289
+ | { type: "assistant_boundary" }
290
+ // Native web-search activity surfaced by the web-search sidecar so Codex renders a "Searched the
291
+ // web" cell. Emitted as a lifecycle PAIR at real wall-clock moments by src/web-search/loop.ts
292
+ // (routed adapters never emit these): `begin` right before the sidecar runs so Codex shows the
293
+ // "Searching the web" spinner, then `end` once it resolves. The bridge maps begin → an
294
+ // output_item.added(in_progress) and end → the matching output_item.done(completed|failed) under
295
+ // the SAME output index, so the activity animates instead of flashing completed instantly.
296
+ | { type: "web_search_call_begin"; id: string }
297
+ | { type: "web_search_call_end"; id: string; queries: string[]; status?: "completed" | "failed"; sources?: OcxUrlCitation[] }
298
+ | {
299
+ type: "done";
300
+ usage?: OcxUsage;
301
+ stopReason?: string;
302
+ endTurn?: boolean;
303
+ providerState?: OcxProviderContinuationState;
304
+ }
305
+ | {
306
+ type: "incomplete";
307
+ reason: string;
308
+ message?: string;
309
+ usage?: OcxUsage;
310
+ retryable?: boolean;
311
+ endTurn?: boolean;
312
+ providerState?: OcxProviderContinuationState;
313
+ }
314
+ // `usage` carries best-effort partial consumption when a turn dies before a clean done
315
+ // (e.g. cursor upstream 502 mid-stream), so failed requests can log real token counts.
316
+ | {
317
+ type: "error";
318
+ message: string;
319
+ usage?: OcxUsage;
320
+ /** Authoritative upstream/proxy status when known; avoids message-based classification. */
321
+ status?: number;
322
+ /** Responses error type and code when the adapter has a structured provider failure. */
323
+ errorType?: string;
324
+ code?: string;
325
+ retryable?: boolean;
326
+ };
327
+
328
+ /**
329
+ * A web source backing a search answer. Surfaced on the search-end event and rendered by the bridge
330
+ * as a `url_citation` annotation on the following assistant message (the desktop app's Sources chip
331
+ * reads these; the TUI ignores annotations, so this is additive).
332
+ */
333
+ export interface OcxUrlCitation {
334
+ url: string;
335
+ title?: string;
336
+ }
337
+
338
+ /**
339
+ * Canonical usage convention (devlog/260711_claude_inbound/070):
340
+ * - `inputTokens` is the TOTAL prompt size, INCLUDING cache reads and cache writes
341
+ * (OpenAI Responses convention). Anthropic parse sites normalize into this shape.
342
+ * - `cachedInputTokens` is cache READ tokens only (a subset of `inputTokens`).
343
+ * - `cacheReadInputTokens`/`cacheCreationInputTokens` carry the read/write split when
344
+ * the provider reports both; reads mirror `cachedInputTokens`.
345
+ * - `totalTokens` = inputTokens + outputTokens. Never re-add cache detail on top.
346
+ */
347
+ export interface OcxUsage {
348
+ inputTokens: number;
349
+ outputTokens: number;
350
+ /**
351
+ * Absolute active-context size after the response. Stateful providers can expose this separately
352
+ * from their per-attempt usage. Responses serialization derives the input side from
353
+ * `contextTotalTokens - outputTokens` so output is never added to an absolute checkpoint twice.
354
+ */
355
+ contextTotalTokens?: number;
356
+ totalTokens?: number;
357
+ cachedInputTokens?: number;
358
+ cacheReadInputTokens?: number;
359
+ cacheCreationInputTokens?: number;
360
+ reasoningOutputTokens?: number;
361
+ estimated?: boolean;
362
+ }
363
+
364
+ /**
365
+ * Claude Code inbound settings (devlog/260711_claude_inbound). Consumed by the
366
+ * /v1/messages surface, the `rmx claude` launcher, and the GUI Claude page.
367
+ */
368
+ export interface OcxClaudeCodeConfig {
369
+ /** Kill switch for the /v1/messages inbound (GUI "Claude ON" toggle). Default: enabled. */
370
+ enabled?: boolean;
371
+ /**
372
+ * Verbatim passthrough of unmapped claude/anthropic models to api.anthropic.com with the
373
+ * caller's own sk-ant-* credential (Claude Code subscription OAuth). Default: enabled.
374
+ */
375
+ nativePassthrough?: boolean;
376
+ /** Upstream for the native passthrough (tests/enterprise gateways). Default: https://api.anthropic.com */
377
+ anthropicBaseUrl?: string;
378
+ /**
379
+ * Native passthrough body inactivity budget in SECONDS — raw upstream-byte silence
380
+ * while a read is pending, NOT total duration (slow-but-alive streams never trip it;
381
+ * devlog 260716_passthrough_followups/010). Default 90. Min 1. Exactly 0 disables;
382
+ * negative/non-finite values fall back to the default.
383
+ */
384
+ bodyStallSec?: number;
385
+ /**
386
+ * Native passthrough cumulative body byte cap (streamed SSE and buffered non-stream
387
+ * alike) — an OOM/occupancy guard, not a correctness limit. Default 67108864 (64 MiB).
388
+ * Exactly 0 disables; negative/non-finite values fall back to the default.
389
+ */
390
+ bodyMaxBytes?: number;
391
+ /** Default model slot injected as ANTHROPIC_MODEL by `rmx claude`. */
392
+ model?: string;
393
+ /** Haiku/small-fast slot injected as ANTHROPIC_DEFAULT_HAIKU_MODEL (+ legacy SMALL_FAST). */
394
+ smallFastModel?: string;
395
+ /** Inbound model id remaps: exact id first, then date-stripped (`-\d{8}$`). */
396
+ modelMap?: Record<string, string>;
397
+ /**
398
+ * Inject ANTHROPIC_BASE_URL etc. into the macOS user domain via `launchctl setenv`
399
+ * so plain `claude` commands route through the proxy without `rmx claude`. Reverted
400
+ * on stop/shutdown. Default: false (opt-in). macOS only.
401
+ */
402
+ systemEnv?: boolean;
403
+ /**
404
+ * Auth mode for Claude Code inbound requests — a THREE-state intent.
405
+ *
406
+ * "proxy": inject the dummy ANTHROPIC_AUTH_TOKEN so Claude Code routes through the
407
+ * proxy without a real Anthropic key. "subscription": never inject it. UNSET means
408
+ * AUTO: the mode is resolved from detected Claude auth on every launch and every
409
+ * status read (src/claude/auth-mode.ts), so registering a Claude login switches the
410
+ * behaviour with no migration and no stored state.
411
+ *
412
+ * An explicit value always wins over detection and is never rewritten by the auto
413
+ * logic — that is what makes a manual choice stick (devlog 260726_claude_auth_auto).
414
+ */
415
+ authMode?: "proxy" | "subscription";
416
+ /**
417
+ * ISO timestamp of the one-time authMode migration. Before auto existed, choosing
418
+ * "Subscription" DELETED the key, so a pre-upgrade config cannot distinguish an
419
+ * explicit subscription choice from "never chose". Its ABSENCE identifies a
420
+ * pre-upgrade block; the migration writes it once and never re-runs, so a user who
421
+ * later picks Auto (which deletes authMode) is not silently converted back.
422
+ */
423
+ authModeMigratedAt?: string;
424
+ /**
425
+ * Context-window override for Claude Code/Desktop clients (devlog 136 B6):
426
+ * injected as CLAUDE_CODE_MAX_CONTEXT_TOKENS + DISABLE_COMPACT=1 (the official
427
+ * env pair — recognized claude-shaped ids need both). WARNING: DISABLE_COMPACT
428
+ * turns off auto-compaction. Unset = client defaults.
429
+ */
430
+ maxContextTokens?: number;
431
+ /**
432
+ * Opt-in CLAUDE_CODE_ALWAYS_ENABLE_EFFORT=1 injection. Default OFF: opus-shaped
433
+ * aliases already carry output_config.effort on the wire (devlog 136 실측), and
434
+ * forcing effort on every request can leak reasoning params to non-reasoning routes.
435
+ */
436
+ alwaysEnableEffort?: boolean;
437
+ /**
438
+ * Subagent tier slots (devlog 260712 B2): injected as ANTHROPIC_DEFAULT_*_MODEL so
439
+ * Claude Code's Agent-tool aliases (opus/sonnet/haiku/fable + parent-inherit) route
440
+ * to proxy models. haiku falls back to smallFastModel (one effective value feeds
441
+ * both ANTHROPIC_DEFAULT_HAIKU_MODEL and legacy ANTHROPIC_SMALL_FAST_MODEL).
442
+ */
443
+ tierModels?: { opus?: string; sonnet?: string; haiku?: string; fable?: string };
444
+ /**
445
+ * Auto-context (devlog 260712 020): when not false, routed/native models whose
446
+ * authoritative window is > 200k AND >= the compact window get the [1m] marker
447
+ * (Claude Code then accounts 1M) and CLAUDE_CODE_AUTO_COMPACT_WINDOW is injected
448
+ * so compaction fires at the real budget. 2.1.207 semantics (binary-verified):
449
+ * effective compact window = min(believed window, env) — one global env behaves
450
+ * like a per-model floor. Default: enabled. Inert while maxContextTokens is set
451
+ * (the legacy DISABLE_COMPACT pair takes rule-1 precedence in the CLI).
452
+ */
453
+ autoContext?: boolean;
454
+ /** Compact-window tokens for auto-context. Default 350_000. */
455
+ autoCompactWindow?: number;
456
+ /**
457
+ * Bundled-skill content elision for ROUTED (non-Anthropic) models (devlog 260712
458
+ * 060): Skill-tool results whose skill name matches an entry here are replaced
459
+ * with a short stub in the anthropic->responses translation. Third-party models
460
+ * are not trained on these Anthropic doc bundles, and claude-api alone injects
461
+ * ~136k tokens (GitHub anthropics/claude-code#74473). Native Anthropic
462
+ * passthrough never goes through the translation, so Claude models keep the
463
+ * full content. Default: ["claude-api"]. Empty array = explicitly off.
464
+ */
465
+ blockedSkills?: string[];
466
+ /**
467
+ * Sync the featured subagent roster (config.subagentModels + main model) into
468
+ * ~/.claude/agents/ocx-*.md custom agent definitions at launch (devlog 260712
469
+ * 070) so any routed model is dispatchable as a subagent_type — the Agent
470
+ * tool's model argument is a hard 4-alias enum, but definition frontmatter is
471
+ * free. Only ocx-*.md files are owned/pruned. Default: enabled.
472
+ */
473
+ injectAgents?: boolean;
474
+ /**
475
+ * Optional Claude Code effort pinned in every generated ocx-* subagent
476
+ * definition. Unset inherits the parent session effort.
477
+ */
478
+ subagentEffort?: "low" | "medium" | "high" | "xhigh" | "max";
479
+ /** Claude-originated web-search override. Unset fields inherit the global sidecar settings. */
480
+ webSearchSidecar?: { backend?: "openai" | "anthropic"; model?: string };
481
+ /** Claude-originated vision override. Unset fields inherit the global sidecar settings. */
482
+ visionSidecar?: { backend?: "openai" | "anthropic"; model?: string };
483
+ /** Persisted Claude Desktop four-family routing profile. */
484
+ desktopProfile?: OcxClaudeDesktopProfile;
485
+ /** Auto-reconcile Desktop 3P config when provider catalog changes. Default: enabled. */
486
+ desktopAutoApply?: boolean;
487
+ /**
488
+ * When false, omit `native/*` rows from Claude Desktop show/export/apply. Default: enabled.
489
+ * Routing-sidecar alias decoding is unchanged — only the Desktop model list writer.
490
+ */
491
+ desktopNativeModels?: boolean;
492
+ }
493
+
494
+ export type OcxClaudeDesktopFamily = "opus" | "fable" | "sonnet" | "haiku";
495
+
496
+ export interface OcxClaudeDesktopAssignment {
497
+ family: OcxClaudeDesktopFamily;
498
+ alias: string;
499
+ }
500
+
501
+ export interface OcxClaudeDesktopProfile {
502
+ version: 1;
503
+ assignments: Record<string, OcxClaudeDesktopAssignment>;
504
+ defaults: Record<OcxClaudeDesktopFamily, string | null>;
505
+ /** SHA-256 fingerprint of the last successfully applied 3P config content. */
506
+ appliedFingerprint?: string;
507
+ /** ISO timestamp of the last successful apply. */
508
+ appliedAt?: string;
509
+ }
510
+
511
+ /**
512
+ * Opt-in archived-session auto-cleanup policy (issue #42 Phase 3).
513
+ * Persisted under `OcxConfig.storageCleanupPolicy`. Default `enabled: false`.
514
+ */
515
+ export interface StorageCleanupPolicy {
516
+ /** When false/unset, the engine never mutates. Default false. */
517
+ enabled: boolean;
518
+ /** Run when archived session bytes exceed this threshold. */
519
+ trigger: { archivedBytesOver: number };
520
+ /** Either shrink archives toward a byte floor, or remove the oldest N%. */
521
+ target: { reduceToBytes?: number } | { removeOldestPercent?: number };
522
+ schedule: "startup" | "daily" | "weekly" | "manual";
523
+ /** Default quarantine. Permanent only when explicitly set. */
524
+ mode: "quarantine" | "permanent";
525
+ lastRun?: { at: number; freedBytes: number; removed: number };
526
+ /** Epoch ms when the next scheduled evaluation is due. */
527
+ nextRun?: number;
528
+ }
529
+
530
+ /** 사용자가 대시보드에서 직접 추가한 커스텀 모델 정의. */
531
+ export interface OcxCustomModel {
532
+ /** 고유 ID (crypto.randomUUID()) */
533
+ id: string;
534
+ /** 프로바이더 키 (기존 providers[name]) */
535
+ provider: string;
536
+ /** 모델 슬러그 (프로바이더 접두사 없는 bare id) */
537
+ modelId: string;
538
+ /** 인간 가독 표시명 (선택, 슬래시 불가) */
539
+ displayName?: string;
540
+ /** 컨텍스트 윈도우 (토큰) */
541
+ contextWindow?: number;
542
+ /** 입력 모달리티 (선택, 기본 ["text"]) */
543
+ inputModalities?: string[];
544
+ /** 추가 시각 (ISO 8601) */
545
+ addedAt?: string;
546
+ }
547
+
548
+ /**
549
+ * A generated `ocx_` data-plane key. `key` is the secret itself and never leaves
550
+ * the server except in the one-time POST /api/keys response; every other surface
551
+ * sees only the masked prefix.
552
+ */
553
+ export interface OcxApiKeyEntry {
554
+ id: string;
555
+ name: string;
556
+ key: string;
557
+ createdAt: string;
558
+ }
559
+
560
+ /**
561
+ * Durable per-client intent. One key today, deliberately.
562
+ *
563
+ * A top-level `codexEnabled` would force every later client to invent an
564
+ * unrelated name and its own helpers; a ten-key union recreated the coupling
565
+ * that failed two audits, because every phase then had to touch every client's
566
+ * write path. A one-key object keeps the extension point without letting this
567
+ * phase claim ownership over a client it does not implement.
568
+ */
569
+ export interface OcxClientIntegrationsConfig {
570
+ /** Durable desired state for native Codex. MISSING MEANS ON. */
571
+ codex?: boolean;
572
+ /** Durable desired state for Grok Build. MISSING MEANS ON. */
573
+ grok?: boolean;
574
+ /** Durable desired state for Claude Desktop. MISSING MEANS ON. */
575
+ "claude-desktop"?: boolean;
576
+ }
577
+
578
+ export interface OcxConfig {
579
+ port: number;
580
+ /** Maximum usage-log bytes read for one management snapshot. */
581
+ managementUsageMaxReadBytes?: number;
582
+ providers: Record<string, OcxProviderConfig>;
583
+ /**
584
+ * Per-source model-picker visibility. Missing keys mean visible.
585
+ *
586
+ * This does not disable routing or remove credentials. It only controls
587
+ * discovery surfaces such as Codex Desktop and Android model selectors.
588
+ */
589
+ modelSourceVisibility?: Record<string, boolean>;
590
+ defaultProvider: string;
591
+ /** OpenAI provider-contract migration marker (v2 = single `openai` provider with account mode). */
592
+ openaiProviderTierVersion?: 1 | 2;
593
+ /** One-time migration marker for Antigravity's static-catalog defaults. */
594
+ googleAntigravityStaticCatalogVersion?: 1 | 2;
595
+ /** Claude Code inbound + launcher settings. */
596
+ claudeCode?: OcxClaudeCodeConfig;
597
+ /**
598
+ * Per-client durable intent. This phase owns only `codex`; later phases extend
599
+ * one key at a time rather than widening a shared union.
600
+ */
601
+ clientIntegrations?: OcxClientIntegrationsConfig;
602
+ /**
603
+ * Up to 5 Codex-facing catalog ids to feature first. Values may be bare catalog ids,
604
+ * exact account-qualified "<selector>/<native-openai-model>" ids, or routed
605
+ * "<provider>/<model>" ids. With account selectors, one bare native choice can expand
606
+ * into a selector-qualified group; Codex still advertises only the first 5 visible rows.
607
+ */
608
+ subagentModels?: string[];
609
+ /**
610
+ * Priority-ordered fallback models for spawned sub-agents. When the requested
611
+ * model is quota-exhausted or recently failed, Remodex rewrites the child
612
+ * turn to the next available entry before routing.
613
+ */
614
+ subagentModelFallback?: string[];
615
+ /**
616
+ * TTL (ms) for cached sub-agent model availability probes. Default 60_000.
617
+ */
618
+ subagentModelFallbackPollMs?: number;
619
+ injectionModel?: string;
620
+ /**
621
+ * Opt in to synchronizing the selected injection model into Codex's native
622
+ * sub-agent defaults. Only meaningful while `injectionModel` is set.
623
+ */
624
+ syncCodexSubagentDefaults?: boolean;
625
+ /**
626
+ * Optional reasoning effort the delegation prompt tells the agent to pass in spawn_agent calls
627
+ * (`reasoning_effort` argument). Only meaningful while `injectionModel` is set; validated against
628
+ * the Codex ladder (src/reasoning-effort.ts CODEX_REASONING_LEVELS) at the API boundary.
629
+ */
630
+ injectionEffort?: string;
631
+ /**
632
+ * Explicit sideband websocket base for realtime/live joins, mirroring upstream's
633
+ * `experimental_realtime_ws_base_url`. The value is a ROOT (or a recognized
634
+ * `/realtime`, `/realtime/calls/<id>`, `/live/<id>` endpoint form, which is
635
+ * stripped back to the root); `/v1` is appended during normalization. Intended
636
+ * for local development against a fake realtime server — plaintext `http`/`ws`
637
+ * is accepted only for loopback hosts, and URL userinfo is rejected; both
638
+ * failures close to the canonical `https://api.openai.com/v1`. Configured by
639
+ * editing this file; there is deliberately no management-API or GUI surface.
640
+ */
641
+ experimentalRealtimeWsBaseUrl?: string;
642
+ /**
643
+ * Model ids the user has EXCLUDED from the Grok Build managed block. Absent or empty
644
+ * means "everything visible", which is the historical behaviour — so an existing
645
+ * config keeps the fence it already had.
646
+ *
647
+ * Exclusion list rather than an inclusion list on purpose: a newly added provider
648
+ * model should appear in Grok by default, exactly as it does today. An inclusion list
649
+ * would silently hide every future model behind a switch nobody knew to flip.
650
+ */
651
+ grokExcludedModels?: string[];
652
+ /**
653
+ * When true, OpenAI-routed requests include `service_tier: "priority"` (fast inference).
654
+ * When false, service_tier is stripped so requests use default speed.
655
+ * Undefined = passthrough (don't modify what the client sends).
656
+ */
657
+ fastMode?: boolean;
658
+ /**
659
+ * Windows/macOS SSE passthrough stream shape (#314 mitigation).
660
+ * On Windows, "auto" (default) selects eager relay only on a runtime proven
661
+ * to carry the Bun#32111 fix. On macOS, "auto" always stays on legacy tee and
662
+ * eager relay is explicit-only. "eager-relay" opts into the new relay (and
663
+ * accepts #32111 crash risk on Bun 1.3.14); "legacy-tee" pins the tee path.
664
+ * Persisted in config.json so service users can select the stream shape.
665
+ * See src/lib/bun-stream-caps.ts.
666
+ */
667
+ streamMode?: "auto" | "legacy-tee" | "eager-relay";
668
+ /**
669
+ * Custom override for the injected v2 multi-agent guidance body (the text inside
670
+ * the <multi_agent_mode> tags). After guidance is enabled and the v2 surface and
671
+ * catalog-state gates pass, a configured injectionModel is sufficient to render it;
672
+ * otherwise an eligible roster or fallback is required. Placeholders: `{{model}}` -> the
673
+ * effective preferred model for the request (a bare native model is account-qualified
674
+ * only when the request targets an explicit account selector; unresolved or ambiguous
675
+ * bare values become "", while unresolved explicit routed or account-qualified values
676
+ * remain unchanged),
677
+ * `{{effort}}` -> injectionEffort, `{{roster}}` -> the resolved sub-agent roster
678
+ * block ("" when nothing resolves), `{{fallback}}` -> the configured subagent
679
+ * model fallback guidance block ("" when unset).
680
+ */
681
+ injectionPrompt?: string;
682
+ /**
683
+ * Proxy-authored multi-agent developer guidance. Undefined/true = enabled for
684
+ * backward compatibility; false suppresses both v1 and v2 guidance injection.
685
+ */
686
+ multiAgentGuidanceEnabled?: boolean;
687
+ /**
688
+ * Global hard ceiling for the reasoning effort of EVERY proxied turn (main agent AND
689
+ * sub-agents). Ladder value "low".."max"; incoming efforts ranking above it are rewritten
690
+ * in both request shapes before any adapter or clamp. Unset = no cap. codex-rs converts
691
+ * ultra -> max client-side, so e.g. a "high" cap sends ultra/max-tier turns as high.
692
+ */
693
+ effortCap?: string;
694
+ /**
695
+ * Hard ceiling applied ONLY to sub-agent turns — requests carrying codex-rs's spawned-child
696
+ * markers (`x-openai-subagent` header, or `subagent_kind` inside `x-codex-turn-metadata`).
697
+ * Lets the main agent keep its tier while delegated children are capped. When both caps are
698
+ * set, the lower one wins for sub-agents. See src/server/effort-policy.ts.
699
+ */
700
+ subagentEffortCap?: string;
701
+ /**
702
+ * Models hidden from Codex discovery without blocking direct proxy calls. Routed provider ids
703
+ * are excluded from the catalog + /v1/models entirely. Account-qualified native ids hide only
704
+ * their generated selector row and are omitted from raw /v1/models. BARE native GPT ids hide
705
+ * the bare row plus every generated selector row and omit that model family from raw discovery.
706
+ */
707
+ disabledModels?: string[];
708
+ /** 사용자가 대시보드에서 직접 추가한 커스텀 모델 목록. */
709
+ customModels?: OcxCustomModel[];
710
+ /**
711
+ * Internal, versioned evidence for reconciling custom-model deletions with
712
+ * pre-marker Codex catalog rows. Consumers must parse this defensively so a
713
+ * future state written by a newer binary survives older whole-config saves.
714
+ */
715
+ customModelCatalogMigration?: unknown;
716
+ /**
717
+ * Shadow call intercept: redirect Codex's hard-coded helper calls (title generation,
718
+ * commit messages, skill orchestration) to a user-chosen model. Default intercepted
719
+ * source models: gpt-5.4-mini (older clients) and gpt-5.6-luna (Codex 0.145.0+).
720
+ * Opt-in; disabled by default. Matching maintenance/helper requests are forced to low.
721
+ * Normal Codex turns identified by request_kind=turn are never rewritten.
722
+ */
723
+ shadowCallIntercept?: {
724
+ /** When true, requests for known shadow/helper source models are rewritten to the configured model. */
725
+ enabled?: boolean;
726
+ /** Replacement model id (e.g. "gpt-5.5"). */
727
+ model?: string;
728
+ /** Optional override of intercepted source-model prefixes (default: gpt-5.4-mini, gpt-5.6-luna). */
729
+ sourceModels?: string[];
730
+ };
731
+ /**
732
+ * 3-state multi-agent surface override:
733
+ * - "v1": force ALL models to v1 surface (override upstream pins)
734
+ * - "default" | undefined: respect upstream model pins (sol/terra=v2, luna=v1, rest=codex flag)
735
+ * - "v2": force ALL models to v2 surface (override upstream pins)
736
+ */
737
+ multiAgentMode?: "v1" | "default" | "v2";
738
+ /** Provider-level Codex-visible context caps. Values only lower known model context windows. */
739
+ providerContextCaps?: Record<string, number>;
740
+ /** Global Codex-visible context cap value (tokens). Falls back to DEFAULT_PROVIDER_CONTEXT_CAP. */
741
+ contextCapValue?: number;
742
+ /** Bind hostname. Default "127.0.0.1" (loopback only). Set "0.0.0.0" to expose on all interfaces. */
743
+ hostname?: string;
744
+ /**
745
+ * Optional second listener bound to 127.0.0.1 that admits data-plane requests without a
746
+ * credential (issue #1102).
747
+ *
748
+ * Why a separate listener rather than an exemption on the main one: when `hostname` is a
749
+ * wildcard, every caller needs `x-opencodex-api-key`, but a `codex app-server` spawned
750
+ * directly from the resolved entrypoint never goes through the generated shim and so never
751
+ * inherits the token. Exempting "loopback-looking peers" on the public listener would be
752
+ * unsound — `requestIP()` only proves the last transport hop, and Docker Desktop port
753
+ * forwarding, host-network containers, WSL mirrored networking and tunnels all terminate
754
+ * remote connections locally. Binding a second socket to 127.0.0.1 makes the kernel refuse
755
+ * remote connections outright, so there is no address to judge.
756
+ *
757
+ * The public listener's admission policy is unchanged. This adds an explicit local trust
758
+ * surface: every process on the machine can reach it, spend account quota, and consume paid
759
+ * provider credentials. Off by default; not for multi-tenant hosts.
760
+ *
761
+ * The port is required when enabled and must differ from the proxy port. An OS-assigned port
762
+ * would change across restarts, which would break already-running app-servers holding the
763
+ * previous `base_url` — the exact symptom #1102 reported and we disproved for token rotation.
764
+ */
765
+ unauthenticatedLoopbackListener?:
766
+ | { enabled: false }
767
+ | { enabled: true; port: number };
768
+ /**
769
+ * Outbound HTTP(S) proxy URL for provider requests (e.g. "http://user:pass@proxy:8080", or
770
+ * "${HTTPS_PROXY}"-style env reference). Mirrored into HTTP_PROXY/HTTPS_PROXY at startup when
771
+ * those are unset — Bun's fetch honors them for all outbound calls; localhost is excluded.
772
+ */
773
+ proxy?: string;
774
+ /**
775
+ * Upstream stall timeout (seconds). After this many seconds of no upstream data, emits
776
+ * response.incomplete. Default 300. Min 1.
777
+ */
778
+ stallTimeoutSec?: number;
779
+ /** Connect timeout (ms) for upstream fetch — covers DNS, TCP, TLS, and response header. Default 200000. */
780
+ connectTimeoutMs?: number;
781
+ /** Graceful shutdown drain timeout (ms). Active turns are aborted after this deadline. Default 5000. */
782
+ shutdownTimeoutMs?: number;
783
+ /** Advertise supports_websockets so Codex opens the WS endpoint. Default false; set true to opt in. */
784
+ websockets?: boolean;
785
+ /**
786
+ * Opt-in auto-cleanup policy for archived Codex sessions (issue #42 Phase 3).
787
+ * Default OFF (`enabled` false / unset). Never enabled implicitly.
788
+ * See `src/storage/policy.ts`.
789
+ */
790
+ storageCleanupPolicy?: StorageCleanupPolicy;
791
+ /** Generated API keys for external access to the proxy's /v1/responses endpoint. */
792
+ apiKeys?: OcxApiKeyEntry[];
793
+ /** Auto-start/sync the proxy from the Codex shim before launching Codex. Default true. */
794
+ codexAutoStart?: boolean;
795
+ /** Restore an installed shim after a stable external Codex update replaces it. Default true. */
796
+ codexShimAutoRestore?: boolean;
797
+ /**
798
+ * Compatibility mode: temporarily rewrite Codex resume-history metadata while the proxy is active
799
+ * so Codex App can show old OpenAI chats and Remodex-created exec chats under its default
800
+ * interactive-source/provider filters. Default true; originals are backed up and restored by
801
+ * `rmx stop` / `rmx restore`. Set false to opt out of history remapping.
802
+ */
803
+ syncResumeHistory?: boolean;
804
+ /** Freshness window (ms) for the per-provider live `/models` cache. Defaults to 5 min. */
805
+ modelCacheTtlMs?: number;
806
+ /** Evictable retained app-state budget in MiB. Default 256; valid 64..4096. */
807
+ appOwnedMemoryBudgetMb?: number;
808
+ /** Anthropic prompt-cache retention: "short" = 5-min ephemeral (default), "long" = 1-hour extended, "none" = disabled. */
809
+ cacheRetention?: "none" | "short" | "long";
810
+ /** Web-search sidecar: route web_search for non-OpenAI models through a gpt-mini via ChatGPT passthrough. */
811
+ webSearchSidecar?: OcxWebSearchSidecarConfig;
812
+ /** Vision sidecar: describe images via a gpt vision model so text-only models can "see" them. */
813
+ visionSidecar?: OcxVisionSidecarConfig;
814
+ /** /v1/images relay for codex's built-in image_gen tool. */
815
+ images?: OcxImagesConfig;
816
+ /** /v1/alpha/search relay for codex's built-in web search client. */
817
+ search?: OcxSearchConfig;
818
+ /** Codex multi-account pool. */
819
+ codexAccounts?: CodexAccount[];
820
+ /** Account ids administratively excluded from future pool selection until resumed. */
821
+ pausedCodexAccountIds?: string[];
822
+ /**
823
+ * Selection order per account id, higher used earlier; absent = 0. Keyed by id
824
+ * rather than stored on `codexAccounts` rows so the Desktop login (`__main__`),
825
+ * which has no row, can be ordered too. Range -100..100.
826
+ */
827
+ codexAccountPriorities?: Record<string, number>;
828
+ /**
829
+ * Account id the operator last selected by hand. Suppresses upward priority
830
+ * preemption until that account crosses the auto-switch threshold. Stores the
831
+ * id (not a flag) so a stale pin cannot outlive the selection it described.
832
+ */
833
+ activeCodexAccountPinned?: string;
834
+ /**
835
+ * Public model-selector namespaces bound to one Codex account. Values are stored account ids;
836
+ * `"@main"` selects the Codex Desktop/main auth.json account. Account display aliases
837
+ * are intentionally separate from these selectors.
838
+ */
839
+ codexAccountNamespaces?: Record<string, string>;
840
+ /**
841
+ * Picker visibility override for account-qualified native models. When omitted, a non-empty
842
+ * selector map remains visible for compatibility with hand-written configurations.
843
+ */
844
+ codexAccountPickerEnabled?: boolean;
845
+ /** Active pool account id for next session. undefined = main (passthrough as-is). */
846
+ activeCodexAccountId?: string;
847
+ /** Auto-switch threshold (0-100). Default 80. 0 = disabled. */
848
+ autoSwitchThreshold?: number;
849
+ /** New-session account rotation strategy for the Codex pool. Default quota (today's behaviour). */
850
+ accountPoolStrategy?: OcxAccountPoolRotationStrategy;
851
+ /** Successful new-session binds retained on one round-robin selection. Default 1; range 1..100. */
852
+ accountPoolStickyLimit?: number;
853
+ /** Consecutive non-2xx upstream responses before switching future new threads. Default 3. 0 = disabled. */
854
+ upstreamFailoverThreshold?: number;
855
+ /**
856
+ * Opt-in provider-origin circuit threshold for proven pre-connection reachability failures.
857
+ * Default 0 (disabled); range 0..20. The circuit never counts timeouts or HTTP responses.
858
+ */
859
+ upstreamHostCircuitThreshold?: number;
860
+ /**
861
+ * Opt-in Anthropic OAuth account pool (#294). Default OFF.
862
+ * Failover on 429 + sticky affinity; new sessions may pick lowest known 5h usage.
863
+ * Experimental — see docs and GUI warning before enabling.
864
+ */
865
+ anthropicAccountPool?: {
866
+ enabled?: boolean;
867
+ /** Usage % threshold for new-session auto-pick. Default 80. 0 = disabled (affinity/active only). */
868
+ autoSwitchThreshold?: number;
869
+ /** New-session rotation strategy. Default quota (today's behaviour). */
870
+ strategy?: OcxAccountPoolRotationStrategy;
871
+ /** Successful new-session binds retained on one round-robin selection. Default 1; range 1..100. */
872
+ stickyLimit?: number;
873
+ };
874
+ /** Virtual `combo/<id>` models spanning concrete provider/model targets (issue #133). */
875
+ combos?: Record<string, OcxComboConfig>;
876
+ /**
877
+ * Routing policy profiles (Router Intelligence, RI-04+): explicitly requested
878
+ * `policy/<id>` (or configured alias) models select among an explicit
879
+ * candidate allowlist using hard capability requirements and deterministic
880
+ * scoring. Existing model ids are never routed through profiles implicitly.
881
+ */
882
+ routingProfiles?: Record<string, OcxRoutingProfileConfig>;
883
+ /** Background proactive token refresh ("Token Guardian"). Off by default; see OcxTokenGuardianConfig. */
884
+ tokenGuardian?: OcxTokenGuardianConfig;
885
+ /** Additional exact origins allowed for CORS (e.g. HTTPS or chrome-extension://<id>). Loopback origins are always allowed. */
886
+ corsAllowOrigins?: string[];
887
+ }
888
+
889
+ export type OcxAccountPoolRotationStrategy = "quota" | "round-robin" | "fill-first";
890
+
891
+ export type OcxComboStrategy = "failover" | "round-robin";
892
+ export type OcxComboDefaultEffort = "low" | "medium" | "high" | "xhigh" | "max" | "ultra";
893
+
894
+ export interface OcxComboTarget {
895
+ provider: string;
896
+ model: string;
897
+ /** Relative SWRR batch weight. Default 1; valid range 1..10000. */
898
+ weight?: number;
899
+ }
900
+
901
+ export interface OcxComboConfig {
902
+ targets: OcxComboTarget[];
903
+ /** Ordered failover (default) or deterministic smooth weighted round-robin. */
904
+ strategy?: OcxComboStrategy;
905
+ /** Successful requests retained on one RR selection batch. Default 1; range 1..100. */
906
+ stickyLimit?: number;
907
+ /** Used when the client omits reasoning.effort. null/omitted leaves the target default unchanged. */
908
+ defaultEffort?: OcxComboDefaultEffort | null;
909
+ /**
910
+ * Optional public model name replacing the default `combo/<id>` slug. Bare names
911
+ * without "/" are allowed (e.g. "deepseek-v4-flash") so the combo can answer to a
912
+ * mandated model id; exact-match requests route here before any provider resolution.
913
+ */
914
+ alias?: string;
915
+ /**
916
+ * Explicitly allow a bare OpenAI-native alias (for example `gpt-5.6-sol`) to
917
+ * be represented by this routed combo. Never inferred from `alias`.
918
+ */
919
+ nativeAlias?: boolean;
920
+ /** Display-only label for the public catalog row. Required for native aliases. */
921
+ displayName?: string;
922
+ }
923
+
924
+ export type OcxRoutingUnknownEvidenceMode = "allow" | "penalize" | "exclude";
925
+
926
+ export interface OcxRoutingProfileCandidate {
927
+ provider: string;
928
+ model: string;
929
+ }
930
+
931
+ export interface OcxRoutingProfileRequirements {
932
+ /** Minimum model context window in tokens. */
933
+ minContextWindow?: number;
934
+ /** Minimum remaining quota headroom fraction (0..1). */
935
+ minQuotaHeadroom?: number;
936
+ tools?: boolean;
937
+ imageInput?: boolean;
938
+ structuredOutput?: boolean;
939
+ reasoningEffort?: string;
940
+ serviceTier?: string;
941
+ localOnly?: boolean;
942
+ remoteAllowed?: boolean;
943
+ /** Special encrypted Codex task readability (ChatGPT forward pool). */
944
+ encryptedCodexTasks?: boolean;
945
+ }
946
+
947
+ export interface OcxRoutingProfileOptimize {
948
+ latency?: number;
949
+ health?: number;
950
+ cost?: number;
951
+ quota?: number;
952
+ }
953
+
954
+ export interface OcxRoutingProfileLimits {
955
+ /** Hard per-request estimated-cost ceiling in USD. */
956
+ maxEstimatedCostUsd?: number;
957
+ }
958
+
959
+ export interface OcxRoutingProfileUnknownEvidence {
960
+ capability?: OcxRoutingUnknownEvidenceMode;
961
+ health?: OcxRoutingUnknownEvidenceMode;
962
+ quota?: OcxRoutingUnknownEvidenceMode;
963
+ cost?: OcxRoutingUnknownEvidenceMode;
964
+ }
965
+
966
+ export interface OcxRoutingProfileConfig {
967
+ /**
968
+ * Explicit candidate allowlist (`provider/model` refs). No implicit
969
+ * expansion in v1.
970
+ */
971
+ candidates: OcxRoutingProfileCandidate[];
972
+ /** Optional public model name replacing the default `policy/<id>` slug. */
973
+ alias?: string;
974
+ /** Hard requirements evaluated before scoring. */
975
+ require?: OcxRoutingProfileRequirements;
976
+ /** Optimization weights; normalized deterministically. */
977
+ optimize?: OcxRoutingProfileOptimize;
978
+ limits?: OcxRoutingProfileLimits;
979
+ /** How unknown evidence is handled per dimension. */
980
+ unknownEvidence?: OcxRoutingProfileUnknownEvidence;
981
+ }
982
+
983
+ /**
984
+ * Per-provider proactive-refresh policy. The guardian only ever touches a provider whose EFFECTIVE
985
+ * policy is "proactive"; "lazy-only" keeps today's on-demand refresh, "disabled" forbids the
986
+ * guardian entirely (used for providers whose ToS actively enforces against non-official-client
987
+ * token traffic, e.g. Anthropic subscription OAuth). See devlog 260703_oauth-multi-account-refresh-and-tos.
988
+ */
989
+ export type RefreshPolicy = "proactive" | "lazy-only" | "disabled";
990
+
991
+ export interface OcxTokenGuardianConfig {
992
+ /** Global kill-switch. Default false — the guardian does nothing unless explicitly enabled. */
993
+ enabled?: boolean;
994
+ /** Seconds between refresh sweeps. Default 21600 (6h). Min 60. */
995
+ tickSeconds?: number;
996
+ /** Random 0..jitterSeconds added before each sweep to de-synchronize. Default 300. */
997
+ jitterSeconds?: number;
998
+ /** Max concurrent refreshes per sweep. Default 3. Min 1. */
999
+ concurrency?: number;
1000
+ /** Extra lead (seconds) beyond one tick when deciding a token is "expiring soon". Default 900. */
1001
+ leadSeconds?: number;
1002
+ /** First backoff (seconds) after a permanent refresh failure. Default 300. */
1003
+ failureBackoffBaseSeconds?: number;
1004
+ /** Backoff ceiling (seconds). Default 3600. */
1005
+ failureBackoffMaxSeconds?: number;
1006
+ /** Optional Codex pool session warmup sweep. Default false to avoid background synthetic traffic. */
1007
+ codexWarmupEnabled?: boolean;
1008
+ /** Max age before a Codex pool account is revalidated via `/codex/responses`. Default 691200 (8d). */
1009
+ codexWarmupMaxAgeSeconds?: number;
1010
+ /** Model used for optional Codex pool warmup. Default gpt-5.4-mini. */
1011
+ codexWarmupModel?: string;
1012
+ }
1013
+
1014
+ export interface OcxImagesConfig {
1015
+ /** Optional custom API-key provider for /v1/images relays. Built-in OpenAI tiers remain automatic. */
1016
+ provider?: string;
1017
+ /** Upstream timeout (ms) for one image generation/edit call (bridge xAI + /v1/images relay). Default 60000 for the bridge; relay may use a higher default (300000). */
1018
+ timeoutMs?: number;
1019
+ /** Master switch for the image bridge. Default false — set true to enable paid xAI Grok Imagine generation. */
1020
+ bridgeEnabled?: boolean;
1021
+ /** xAI image model id. Default "grok-imagine-image-quality" (see DEFAULT_MODEL in images/plan.ts). */
1022
+ bridgeModel?: string;
1023
+ /** Max image-generation loop iterations before forced-final. Default 3; clamped to [0, 10]. */
1024
+ maxRounds?: number;
1025
+ /** Max files retained under artifacts/. Oldest deleted when exceeded. Default 200. */
1026
+ artifactsKeepCount?: number;
1027
+ /** Master switch for the video bridge. Default false — must be explicitly opted in. */
1028
+ videoBridgeEnabled?: boolean;
1029
+ /** Model for xAI video generation. Default "grok-imagine-video". */
1030
+ videoBridgeModel?: string;
1031
+ /** Max video-gen rounds before forced-final. Default 2 (video is slower than image). */
1032
+ videoMaxRounds?: number;
1033
+ /** Per-video generation timeout (ms) including polling. Default 300000 (5 min). */
1034
+ videoTimeoutMs?: number;
1035
+ }
1036
+
1037
+ export interface OcxSearchConfig {
1038
+ /**
1039
+ * Total upstream deadline (ms) for one /v1/alpha/search relay. Default 200000. The endpoint
1040
+ * is non-streaming JSON (headers arrive only when the search completes), so this is a whole-
1041
+ * request budget — deliberately NOT connectTimeoutMs, which is a header-arrival budget.
1042
+ */
1043
+ timeoutMs?: number;
1044
+ }
1045
+
1046
+ export interface OcxVisionSidecarConfig {
1047
+ /** Master switch. Default: enabled when the selected backend has a usable credential. */
1048
+ enabled?: boolean;
1049
+ /** Description backend. Unset prefers a usable stored Anthropic OAuth credential, else OpenAI. */
1050
+ backend?: "openai" | "anthropic";
1051
+ /** Vision model that describes images. */
1052
+ model?: string;
1053
+ /** Max description cache misses admitted in one main-model turn. Zero disables description calls. */
1054
+ maxDescriptionsPerTurn?: number;
1055
+ /** Sidecar fetch timeout (ms). */
1056
+ timeoutMs?: number;
1057
+ }
1058
+
1059
+ export interface OcxWebSearchSidecarConfig {
1060
+ /** Master switch. Default: enabled when a forward (ChatGPT) provider exists and the caller is logged in. */
1061
+ enabled?: boolean;
1062
+ /**
1063
+ * Which backend actually runs the server-side search. "openai" replays the hosted web_search via
1064
+ * the ChatGPT forward provider (gpt-mini sidecar); "anthropic" runs web_search_20250305 on a Claude
1065
+ * model authenticated by the STORED anthropic OAuth credential. Unset resolves to "anthropic" when a
1066
+ * usable anthropic OAuth credential exists, else "openai".
1067
+ */
1068
+ backend?: "openai" | "anthropic";
1069
+ /** Sidecar model that runs the real server-side web_search (must be a native ChatGPT model). */
1070
+ model?: string;
1071
+ /** Reasoning effort for the sidecar — "minimal" (non-thinking) keeps it fast/cheap. */
1072
+ reasoning?: string;
1073
+ /** Max searches executed per main-model turn (loop guard). */
1074
+ maxSearchesPerTurn?: number;
1075
+ /** Sidecar fetch timeout (ms). */
1076
+ timeoutMs?: number;
1077
+ /**
1078
+ * Config-file-only deadline (ms) for continuous routed-model response-body raw-byte inactivity
1079
+ * during a web-search turn. Default 200000. Must be an integer from 1 through 2147483647.
1080
+ */
1081
+ routedModelStallTimeoutMs?: number;
1082
+ }
1083
+
1084
+ export interface OpenRouterProviderRouting {
1085
+ /** OpenRouter provider slugs to try first, in priority order. */
1086
+ order?: string[];
1087
+ /** Restrict routing to these OpenRouter provider slugs. */
1088
+ only?: string[];
1089
+ /** Whether OpenRouter may use providers outside `order`. Defaults to OpenRouter's policy. */
1090
+ allowFallbacks?: boolean;
1091
+ }
1092
+
1093
+ export interface ResponsesItemIdRepairConfig {
1094
+ /** Exact `message` item ids that the proxy should rewrite to request-local canonical ids. */
1095
+ message?: string[];
1096
+ /** Exact `reasoning` item ids that the proxy should rewrite to request-local canonical ids. */
1097
+ reasoning?: string[];
1098
+ /** Backfill missing `output_item.done` / terminal snapshot ids from the matching output_index. */
1099
+ repairMissingTerminalIds?: boolean;
1100
+ /**
1101
+ * Treat existing message/reasoning ids without the canonical `msg_`/`rs_` prefix (e.g. bare
1102
+ * UUIDs from DeepSeek's Responses route) as invalid and mint canonical replacements (#938).
1103
+ * function_call ids and call_id pairing are never rewritten.
1104
+ */
1105
+ repairInvalidIds?: boolean;
1106
+ }
1107
+
1108
+ /**
1109
+ * Same-target 429 wait-and-retry policy (`providers.<name>.retryOn429`). When present and not
1110
+ * explicitly disabled, the proxy waits and replays the identical request on the same key before
1111
+ * any key failover. All fields optional; the runtime applies defaults (attempts=3,
1112
+ * intervalMs=5000, maxIntervalMs=60000, respectRetryAfter=true, enabled=true).
1113
+ */
1114
+ export interface RateLimitRetryPolicy {
1115
+ /** Master switch. The presence of the object also enables the policy (default true). */
1116
+ enabled?: boolean;
1117
+ /** Extra replay attempts after the first 429 (1..20, default 3). */
1118
+ attempts?: number;
1119
+ /** Fixed wait between attempts when the upstream sends no usable Retry-After (default 5000). */
1120
+ intervalMs?: number;
1121
+ /** Cap for any single wait, including an upstream Retry-After (default 60000). */
1122
+ maxIntervalMs?: number;
1123
+ /** Prefer the upstream Retry-After header when present and parseable (default true). */
1124
+ respectRetryAfter?: boolean;
1125
+ }
1126
+
1127
+ export type ReasoningControlKind = "effort" | "toggle" | "automatic" | "unsupported" | "unknown";
1128
+
1129
+ /** Canonical model reasoning capability shared by discovery, catalogs, routing, and clients. */
1130
+ export type ReasoningControl =
1131
+ | { readonly kind: "effort"; readonly efforts: string[]; readonly defaultEffort?: string; readonly required: boolean }
1132
+ | { readonly kind: "toggle"; readonly defaultEnabled?: boolean }
1133
+ | { readonly kind: "automatic"; readonly required: boolean }
1134
+ | { readonly kind: "unsupported" }
1135
+ | { readonly kind: "unknown" };
1136
+
1137
+ /**
1138
+ * One configured provider entry. `authMode` (default `"key"`) decides whether same-target 429
1139
+ * retries are allowed; OAuth/forward credentials and local runtimes are never replayed.
1140
+ */
1141
+ export interface OcxProviderConfig {
1142
+ adapter: string;
1143
+ /** Cursor MCP compatibility bounds; positive integers when configured. */
1144
+ mcpMaxTools?: number;
1145
+ mcpMaxSchemaBytes?: number;
1146
+ mcpMaxResultBytes?: number;
1147
+ /**
1148
+ * Per-model wire override, keyed by the upstream native model id (after namespace
1149
+ * and combo resolution). A single gateway can front models that speak different
1150
+ * wires — Grok needs the Responses API for hosted web_search while a sibling model
1151
+ * is fine on chat completions (#404).
1152
+ *
1153
+ * Only OpenAI-shaped wires may be selected; see MODEL_ADAPTER_OVERRIDE_ALLOWED.
1154
+ * Absent or empty means the provider-wide `adapter` applies to everything, exactly
1155
+ * as before.
1156
+ */
1157
+ modelAdapters?: Record<string, string>;
1158
+ baseUrl: string;
1159
+ /**
1160
+ * Optional relative resource path for key-auth openai-responses requests. Must start with `/`
1161
+ * and must not include a URL scheme, query string, or fragment. When omitted, the adapter keeps
1162
+ * the legacy `/v1/responses` construction.
1163
+ */
1164
+ responsesPath?: string;
1165
+ /**
1166
+ * Command Code protocol version sent as `x-command-code-version` on /alpha/generate requests.
1167
+ * The internal endpoint's schema drifts with the CLI version; operators can pin a known-good
1168
+ * version here instead of waiting for a code change. Absent uses the adapter's current default.
1169
+ */
1170
+ commandCodeVersion?: string;
1171
+ /**
1172
+ * Responses upstream that stores nothing server-side (DeepSeek documents "the API
1173
+ * is stateless"). Stateful request parameters are dropped, `store` is pinned false,
1174
+ * and orphaned tool results left by a replay miss are repaired rather than
1175
+ * forwarded to an upstream that cannot resolve their pair.
1176
+ */
1177
+ statelessResponses?: boolean;
1178
+ /**
1179
+ * Whether this provider's Responses route honours the OpenAI `service_tier`
1180
+ * parameter. Tri-state: `true` lets fast mode inject/remove the field (an unset
1181
+ * fast mode preserves a caller-supplied value); `false` strips the field and
1182
+ * never injects, because an upstream documented as not supporting the parameter
1183
+ * must not receive it; absent (`undefined`) leaves the provider unclassified —
1184
+ * caller-supplied values are preserved untouched, and fast mode never injects.
1185
+ * An explicit config value always wins over the registry default.
1186
+ */
1187
+ supportsServiceTier?: boolean;
1188
+ /**
1189
+ * Responses upstream whose native contract accepts plaintext reasoning replay
1190
+ * (DeepSeek documents reasoning items with plaintext content). When set, the
1191
+ * passthrough serializer keeps `reasoning_text` content on replayed reasoning
1192
+ * items instead of blanking it the way the ChatGPT backend requires; proxy-minted
1193
+ * `ocxr1` envelopes are still stripped because no upstream can decrypt them.
1194
+ */
1195
+ preserveResponsesReasoningContent?: boolean;
1196
+ /**
1197
+ * Explicit opt-in for non-registry private-network destinations such as localhost, RFC1918,
1198
+ * link-local, or unique-local upstreams. Metadata endpoints remain blocked.
1199
+ */
1200
+ allowPrivateNetwork?: boolean;
1201
+ /** Keep provider settings on disk but exclude it from routing and model/catalog listings. */
1202
+ disabled?: boolean;
1203
+ /**
1204
+ * Codex account-selection mode. Valid ONLY on the canonical built-in `openai` forward provider.
1205
+ * "pool" (default) rotates main + added Codex accounts through the affinity/quota/cooldown/
1206
+ * failover engine; "direct" pins the caller's main Codex login and never touches pool state.
1207
+ */
1208
+ codexAccountMode?: CodexAccountMode;
1209
+ apiKey?: string;
1210
+ /**
1211
+ * Key-auth header style for Anthropic-compatible providers.
1212
+ * Defaults to the native Anthropic `x-api-key`; gateways may require
1213
+ * `Authorization: Bearer <key>` instead.
1214
+ */
1215
+ apiKeyTransport?: "x-api-key" | "bearer";
1216
+ /**
1217
+ * Multi-key pool (API-key twin of OAuth multiauth). `apiKey` always mirrors the ACTIVE
1218
+ * entry so routing stays single-key; managed via /api/providers/keys. A legacy bare
1219
+ * `apiKey` seeds a one-entry pool on first management touch.
1220
+ */
1221
+ apiKeyPool?: Array<{ id: string; key: string; label?: string; addedAt?: number }>;
1222
+ defaultModel?: string;
1223
+ models?: string[];
1224
+ /**
1225
+ * Fetch the provider's live `/models` endpoint. Defaults to true.
1226
+ * Set false when `models` is an intentional allowlist or a provider's live catalog is too large
1227
+ * or too flaky for startup/catalog sync.
1228
+ */
1229
+ liveModels?: boolean;
1230
+ /**
1231
+ * Per-provider catalog allowlist. When non-empty, ONLY these model ids are emitted to Codex's
1232
+ * catalog and `/v1/models` — live discovery still runs, this just narrows what ships (so a proxy
1233
+ * exposing thousands of models, or an aggregator like OpenRouter, doesn't bloat the catalog).
1234
+ * Empty/undefined = expose all. The admin `/api/models` list is unaffected (it always shows the
1235
+ * full set so the user can pick). See devlog issue_052_provider-model-allowlist.
1236
+ */
1237
+ selectedModels?: string[];
1238
+ /** Provider-wide fallback when context metadata is absent; otherwise caps the reported window. */
1239
+ contextWindow?: number;
1240
+ /** Per-model fallback when context metadata is absent; otherwise caps the reported window. */
1241
+ modelContextWindows?: Record<string, number>;
1242
+ /** Model-specific Codex catalog input modalities, e.g. ["text"] or ["text", "image"]. */
1243
+ modelInputModalities?: Record<string, string[]>;
1244
+ /** Model-specific max input token limits. Values cap auto_compact_token_limit. */
1245
+ modelMaxInputTokens?: Record<string, number>;
1246
+ /**
1247
+ * Provider-wide fallback for chat-completions `max_tokens` when the caller omits
1248
+ * Responses `max_output_tokens`. Adapters still let an explicit request win.
1249
+ */
1250
+ defaultMaxOutputTokens?: number;
1251
+ /** Model-specific fallback output token budgets. Exact/model-pattern entries beat the provider default. */
1252
+ modelMaxOutputTokens?: Record<string, number>;
1253
+ headers?: Record<string, string>;
1254
+ /** Default provider-routing preferences for models sent through the canonical OpenRouter API. */
1255
+ openRouterRouting?: OpenRouterProviderRouting;
1256
+ /** Exact model-id overrides for `openRouterRouting`. Each matching entry replaces the default. */
1257
+ modelOpenRouterRouting?: Record<string, OpenRouterProviderRouting>;
1258
+ /**
1259
+ * "key" (default): authenticate upstream with `apiKey`.
1260
+ * "forward": relay the caller's incoming auth headers verbatim (OAuth passthrough; gpt only).
1261
+ * "oauth": resolve a stored OAuth access token (auto-refreshed) and use it as the Bearer key.
1262
+ * Only the openai-responses adapter implements "forward"; openai-chat uses its own key/token.
1263
+ * "local": local runtime (Ollama etc.) — no remote key required. Valid only for
1264
+ * providers whose registry entry declares authKind "local" (management API enforces).
1265
+ */
1266
+ authMode?: "key" | "forward" | "oauth" | "local";
1267
+ /** Allow an explicitly key/oauth provider to run without a credential (for keyless local proxies). */
1268
+ keyOptional?: boolean;
1269
+ /**
1270
+ * Free-tier pricing flag for UI/catalog (Free badge, Free filter). Not the same as
1271
+ * `keyOptional` — free tiers may still require an API key (e.g. NVIDIA NIM free credits).
1272
+ */
1273
+ freeTier?: boolean;
1274
+ /** Optional human note shown in the providers UI (not used for routing). */
1275
+ note?: string;
1276
+ /** Strip one trailing bracketed suffix from model ids before sending them upstream. */
1277
+ modelSuffixBracketStrip?: boolean;
1278
+ /**
1279
+ * Override the guardian's proactive-refresh policy for this provider. When unset, the provider's
1280
+ * built-in risk-tiered default applies (see OAUTH_PROVIDERS in src/oauth/index.ts). Set "proactive"
1281
+ * to opt this provider into background refresh; "disabled"/"lazy-only" to forbid/limit it.
1282
+ */
1283
+ refreshPolicy?: RefreshPolicy;
1284
+ /**
1285
+ * Provider-wide Codex-visible reasoning tiers for routed models. Use only Codex-supported labels
1286
+ * here (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `ultra`); translate provider aliases with
1287
+ * `reasoningEffortMap` / `modelReasoningEffortMap` below.
1288
+ */
1289
+ reasoningEfforts?: string[];
1290
+ /** Model-specific Codex-visible reasoning tiers. An empty array means “do not expose effort”. */
1291
+ modelReasoningEfforts?: Record<string, string[]>;
1292
+ /** Model-specific default Codex reasoning tier; must also be present in the visible tier list. */
1293
+ modelDefaultReasoningEfforts?: Record<string, string>;
1294
+ /**
1295
+ * Models whose upstream rejects an omitted/disabled reasoning effort. A `true` entry makes
1296
+ * Runtime normalize missing, `none`, invalid, and stale selections to the model's configured
1297
+ * default (or the lowest supported tier) before routing. Explicit `false` overrides a registry
1298
+ * default for custom-compatible deployments.
1299
+ */
1300
+ modelReasoningRequired?: Record<string, boolean>;
1301
+ /**
1302
+ * Runtime-only resolved capability state. Routing stamps the selected model here so adapters can
1303
+ * distinguish unknown/automatic/toggle from confirmed unsupported without persisting guesses.
1304
+ */
1305
+ modelReasoningControls?: Record<string, ReasoningControlKind>;
1306
+ /**
1307
+ * Model-specific Codex reasoning-summary capability. Set false when an OpenAI-compatible
1308
+ * Responses backend rejects Codex summary-delivery fields for that model.
1309
+ */
1310
+ modelSupportsReasoningSummaries?: Record<string, boolean>;
1311
+ /**
1312
+ * Per-model wire value for Responses `stream_options.reasoning_summary_delivery`.
1313
+ * Presence also advertises reasoning-summary support for that routed model.
1314
+ */
1315
+ modelReasoningSummaryDelivery?: Record<string, ReasoningSummaryDelivery>;
1316
+ /**
1317
+ * Exact-model hosted tools that win collisions with Codex client tool declarations.
1318
+ * Use for non-forward Responses gateways that reserve a hosted tool namespace server-side.
1319
+ */
1320
+ modelPreferHostedTools?: Record<string, string[]>;
1321
+ /**
1322
+ * Provider-local repair for Responses gateways whose lifecycle snapshots omit canonical
1323
+ * fields or closing events (#893). Disabled by default and applied only to client-facing
1324
+ * SSE/JSON; raw inspection state remains authoritative.
1325
+ */
1326
+ responsesSnapshotRepair?: boolean;
1327
+ /** Provider-wide mapping from Codex effort labels to upstream `reasoning_effort` values. */
1328
+ reasoningEffortMap?: Record<string, string>;
1329
+ /** Model-specific mapping from Codex effort labels to upstream `reasoning_effort` values. */
1330
+ modelReasoningEffortMap?: Record<string, Record<string, string>>;
1331
+ /** OpenAI-compatible gateway reasoning wire shape. Default sends `reasoning_effort`. */
1332
+ reasoningWireFormat?: "gateway-object";
1333
+ /**
1334
+ * Model ids that do NOT support a reasoning/thinking parameter. The openai-chat adapter drops
1335
+ * reasoning_effort for these even when Codex selects a reasoning level (e.g. xAI grok-build-0.1).
1336
+ */
1337
+ noReasoningModels?: string[];
1338
+ /** Model ids that reject caller-specified temperature. */
1339
+ noTemperatureModels?: string[];
1340
+ /** Model ids that reject caller-specified top_p. */
1341
+ noTopPModels?: string[];
1342
+ /** Model ids that reject caller-specified presence/frequency penalty values. */
1343
+ noPenaltyModels?: string[];
1344
+ /**
1345
+ * Allow multiple tool calls per completion. DEFAULT-ON for openai-chat providers (the
1346
+ * buffered stream parser assembles interleaved/fragmented multi-call turns safely);
1347
+ * set `false` to force `parallel_tool_calls:false` upstream and drop the catalog's
1348
+ * `supports_parallel_tool_calls` bit for that provider. Non-chat adapters advertise
1349
+ * only on explicit `true`. See devlog/_plan/260709_parallel_tool_calls.
1350
+ */
1351
+ parallelToolCalls?: boolean;
1352
+ /**
1353
+ * Opt-in: forward `prompt_cache_key` to the upstream `/chat/completions` body.
1354
+ * OpenAI-specific extension; strict backends (Groq, Cerebras, etc.) reject unknown
1355
+ * fields. Default off; only enable for providers that document this parameter.
1356
+ */
1357
+ promptCacheKey?: boolean;
1358
+ /**
1359
+ * Provider-local passthrough SSE repair for broken openai-responses gateways that reuse exact
1360
+ * placeholder message/reasoning ids or omit the terminal id after a stable added event.
1361
+ * Disabled by default; function_call ids and call_id pairing are never rewritten.
1362
+ */
1363
+ responsesItemIdRepair?: ResponsesItemIdRepairConfig;
1364
+ /** Model ids whose tool_choice only accepts `auto` or `none`; forced/named choices are downgraded. */
1365
+ autoToolChoiceOnlyModels?: string[];
1366
+ /** Model ids that expect prior assistant `reasoning_content` to be preserved in chat history. */
1367
+ preserveReasoningContentModels?: string[];
1368
+ /**
1369
+ * Opt-in same-target 429 retry policy. Codex itself never retries 429 (it retries 5xx only,
1370
+ * openai/codex#30471), and single-key pools have no failover, so the proxy waits and replays
1371
+ * the identical request on the same key before any failover. Pre-stream only: a 429 arrives
1372
+ * before any response bytes are relayed, so the replay is lossless.
1373
+ */
1374
+ retryOn429?: RateLimitRetryPolicy;
1375
+ /**
1376
+ * Model ids whose OpenAI-compatible chat endpoint accepts `reasoning_split: true` and returns
1377
+ * thinking separately in `reasoning_content` / `reasoning_details` instead of visible content.
1378
+ */
1379
+ reasoningSplitModels?: string[];
1380
+ /**
1381
+ * Model ids whose reasoning is a vendor `thinking: {type}` toggle on the
1382
+ * chat-completions wire (MiMo v2.x, GLM 5/5.1 style), NOT an OpenAI `reasoning_effort` ladder.
1383
+ * The openai-chat adapter translates the mapped effort into the thinking toggle for these.
1384
+ */
1385
+ thinkingToggleModels?: string[];
1386
+ /**
1387
+ * Model ids whose reasoning is a `thinking_budget` integer on the chat-completions wire
1388
+ * (Qwen3.x style), NOT an OpenAI `reasoning_effort` ladder. The openai-chat adapter maps the
1389
+ * Codex effort to a budget fraction.
1390
+ */
1391
+ thinkingBudgetModels?: string[];
1392
+ /** Anthropic-compatible gateways that need custom tool names escaped on the wire. */
1393
+ escapeBuiltinToolNames?: boolean;
1394
+ /**
1395
+ * Anthropic-compatible gateways (e.g. AgentRouter) that may close the stream before
1396
+ * `message_stop`. With this enabled the adapter completes an otherwise-clean EOF only when
1397
+ * visible text was received or an open tool call has complete JSON-object arguments; all
1398
+ * other EOFs remain truncation errors. Absent = strict default behavior.
1399
+ */
1400
+ anthropicEofTolerance?: boolean;
1401
+ /**
1402
+ * Model ids that do NOT accept image inputs. The proxy gives them "eyes" via the vision sidecar:
1403
+ * attached images are described by a gpt vision model and replaced with text before the call.
1404
+ */
1405
+ noVisionModels?: string[];
1406
+ /**
1407
+ * Google adapter mode. "ai-studio" (default) = Generative Language API + x-goog-api-key.
1408
+ * "vertex" = Vertex AI project/location endpoints with GCP ADC (or x-goog-api-key).
1409
+ * "cloud-code-assist" = Google Antigravity (Cloud Code Assist) OAuth + CCA envelope.
1410
+ */
1411
+ googleMode?: "ai-studio" | "vertex" | "cloud-code-assist";
1412
+ /** Vertex AI GCP project id (or GOOGLE_CLOUD_PROJECT / GCLOUD_PROJECT env). */
1413
+ project?: string;
1414
+ /** Vertex AI location, e.g. "us-central1" or "global" (or GOOGLE_CLOUD_LOCATION env). */
1415
+ location?: string;
1416
+ /**
1417
+ * Cursor adapter only: MCP servers Remodex starts/connects and exposes to the Cursor agent
1418
+ * as callable tools. Each entry is spawned (stdio `command`) or connected (`url`) lazily per
1419
+ * stream; their tools are advertised to the Cursor server and executed against the live server.
1420
+ */
1421
+ mcpServers?: Record<string, import("./adapters/cursor/mcp-config").CursorMcpServerConfig>;
1422
+ /**
1423
+ * Cursor adapter only: opt-in external executor for computer-use / record-screen. Remodex is
1424
+ * headless and cannot control a screen itself; provide commands here only when running on a host
1425
+ * that can. With no executor, these tools honestly report "not supported".
1426
+ */
1427
+ desktopExecutor?: import("./adapters/cursor/native-exec-desktop").DesktopExecutorConfig;
1428
+ /**
1429
+ * Cursor adapter only: unsafe opt-in escape hatch for Cursor server-driven built-in local
1430
+ * read/write/delete/ls/grep/shell/fetch execution. Prefer `nativeLocalExec: "on"` for new
1431
+ * configs; this legacy boolean remains a server-local explicit opt-in for existing operators.
1432
+ * Defaults to false so remote Cursor messages cannot bypass Codex approval/sandbox semantics.
1433
+ * Explicit MCP and desktop executors remain controlled by their own opt-in config.
1434
+ */
1435
+ unsafeAllowNativeLocalExec?: boolean;
1436
+ /**
1437
+ * Cursor adapter only: native local exec policy mode (exec-policy.ts).
1438
+ * "off" (default) rejects server-driven local exec; "on" always allows it for this
1439
+ * provider and should be used only for a trusted local experiment on a host where every
1440
+ * data-plane caller is trusted. "codex-sandbox" is accepted for backwards compatibility
1441
+ * but is fail-closed like "off": Responses instructions/system/developer text is
1442
+ * caller-controlled prose, and Remodex has no trustworthy per-request attestation that it
1443
+ * reflects a real Codex sandbox state. The default loopback bind admits ANY local process
1444
+ * without auth (including other local users on multi-user machines), and
1445
+ * isAllowedRequestOrigin blocks non-loopback browser origins by default but not
1446
+ * loopback-origin or origin-less callers.
1447
+ */
1448
+ nativeLocalExec?: "off" | "codex-sandbox" | "on";
1449
+ }
1450
+
1451
+ export const REASONING_SUMMARY_DELIVERY_VALUES = [
1452
+ "sequential",
1453
+ "sequential_cutoff",
1454
+ "concurrent",
1455
+ "concurrent_cutoff",
1456
+ ] as const;
1457
+
1458
+ export type ReasoningSummaryDelivery = typeof REASONING_SUMMARY_DELIVERY_VALUES[number];
1459
+
1460
+ /** Trusted runtime ownership for Codex-account credentials. Never persisted per provider. */
1461
+ export type CodexAccountMode = "direct" | "pool";
1462
+
1463
+ export const OPENAI_PROVIDER_TIER_VERSION = 2 as const;
1464
+
1465
+ /**
1466
+ * Wires that a per-model `modelAdapters` override may select.
1467
+ *
1468
+ * Deliberately narrow: provider-specific adapters (cursor, kiro, google, ...) carry
1469
+ * their own credential and base-URL semantics, so exposing them here would widen the
1470
+ * auth boundary rather than pick a wire. Widening this set needs a per-adapter
1471
+ * credential threat model first (#404).
1472
+ */
1473
+ export const MODEL_ADAPTER_OVERRIDE_ALLOWED: ReadonlySet<string> = new Set([
1474
+ "openai-chat",
1475
+ "openai-responses",
1476
+ ]);
1477
+
1478
+ /**
1479
+ * Providers whose listed model ids must be driven over the Anthropic wire even when
1480
+ * the provider's configured adapter says otherwise — the upstream only speaks
1481
+ * Anthropic for these models.
1482
+ */
1483
+ const ANTHROPIC_WIRE_MODELS: Record<string, ReadonlySet<string>> = {
1484
+ "opencode-go": new Set(["minimax-m2.5", "minimax-m2.7", "minimax-m3"]),
1485
+ };
1486
+
1487
+ /**
1488
+ * True when the upstream speaks exactly one wire for this model, so a configured
1489
+ * override must not apply.
1490
+ *
1491
+ * Deliberately independent of the provider's current adapter: the wire resolver runs
1492
+ * more than once per request, and a check phrased as "pin differs from the current
1493
+ * adapter" would pass on the first pass and then let the override win on the second.
1494
+ */
1495
+ export function isWirePinnedModel(providerName: string, modelId: string): boolean {
1496
+ return ANTHROPIC_WIRE_MODELS[providerName]?.has(modelId) ?? false;
1497
+ }
1498
+
1499
+ /** The wire a pinned model must use, or undefined when the model is not pinned. */
1500
+ export function pinnedWireAdapter(providerName: string, modelId: string): string | undefined {
1501
+ return isWirePinnedModel(providerName, modelId) ? "anthropic" : undefined;
1502
+ }
1503
+
1504
+ export interface CodexAccount {
1505
+ id: string;
1506
+ email: string;
1507
+ /** User-owned display label; never participates in routing or identity checks. */
1508
+ alias?: string;
1509
+ plan?: string;
1510
+ chatgptAccountId?: string;
1511
+ logLabel?: string;
1512
+ isMain: boolean;
1513
+ }
1514
+
1515
+ export interface CodexAccountCredentials {
1516
+ accessToken: string;
1517
+ refreshToken: string;
1518
+ expiresAt: number;
1519
+ chatgptAccountId: string;
1520
+ }
1521
+
1522
+ export interface CodexAccountCredentialRecord {
1523
+ credential?: CodexAccountCredentials;
1524
+ generation: number;
1525
+ refreshGrantFingerprint?: string;
1526
+ deletedAt?: number;
1527
+ replacedAt?: number;
1528
+ lastCodexValidatedAt?: number;
1529
+ lastCodexValidationStatus?: "ok" | "failed";
1530
+ lastCodexValidationError?: string;
1531
+ }