@chroxy/server 0.10.0 → 0.11.10

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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -1,16 +1,31 @@
1
+ import { assistantResponseText } from './assistant-response.js'
1
2
  import { JsonlSubprocessSession } from './jsonl-subprocess-session.js'
3
+ import { CODEX_EXEC_CUSTOMIZATION } from './provider-customization.js'
2
4
  import { buildBaseSessionOpts } from './base-session.js'
3
5
  import { homedir } from 'os'
4
6
  import { join } from 'path'
5
7
  import { resolveBinary } from './utils/resolve-binary.js'
6
8
  import { buildSpawnEnv } from './utils/spawn-env.js'
9
+ import { assertSafeArgvValue } from './utils/argv-safety.js'
7
10
  import {
8
11
  CONTEXT_WINDOW_HEADROOM,
9
12
  getRatchetCap,
10
13
  maybeRatchetContextWindow,
11
14
  } from './utils/context-window-learn.js'
15
+ import { nonNegInt } from './usage-normalize.js'
12
16
  import { BILLING_CLASSES } from './billing-class.js'
13
17
  import { hasCodexOAuthCreds } from './auth-probes.js'
18
+ import { getRegistryForProvider } from './models.js'
19
+ import {
20
+ getCodexCatalogRow,
21
+ getCodexCatalogRows,
22
+ hasCodexCatalog,
23
+ refreshCodexModels,
24
+ } from './codex-model-catalog.js'
25
+ import {
26
+ CODEX_SANDBOX_MODES as PROTOCOL_CODEX_SANDBOX_MODES,
27
+ CODEX_DEFAULT_SANDBOX as PROTOCOL_CODEX_DEFAULT_SANDBOX,
28
+ } from '@chroxy/protocol'
14
29
 
15
30
  /**
16
31
  * Manages a Codex CLI session using `codex exec --json`.
@@ -32,6 +47,10 @@ import { hasCodexOAuthCreds } from './auth-probes.js'
32
47
  * tool_start { messageId, toolUseId, tool, input }
33
48
  * tool_result { toolUseId, result }
34
49
  * result { cost, duration, usage, sessionId }
50
+ * usage is the DISJOINT split (#6718): the wire's
51
+ * `cached_input_tokens` is a subset of `input_tokens`, so it is
52
+ * re-emitted as `cache_read_input_tokens` with input reduced by
53
+ * that amount. See _mapUsage().
35
54
  * error { message }
36
55
  */
37
56
 
@@ -60,25 +79,28 @@ const BINARY_CANDIDATES = [
60
79
  join(homedir(), '.npm-global/bin/codex'),
61
80
  ]
62
81
 
63
- const CODEX = resolveBinary('codex', BINARY_CANDIDATES)
82
+ // NOTE: the codex binary is intentionally NOT cached in a module-load const.
83
+ // A frozen path is spawned even after XProtect/Gatekeeper quarantines or moves
84
+ // the binary out from under a long-running daemon (#6708 defect #3). The
85
+ // `resolvedBinary` getter re-resolves fresh per access instead.
64
86
 
65
87
  /**
66
88
  * Codex CLI sandbox modes. Source: `codex exec --sandbox <MODE>` accepts
67
89
  * exactly these three values (verified against codex-cli 0.128.0). Exported
68
90
  * so tests and consumers can pin the canonical list without re-declaring it.
69
91
  */
70
- export const CODEX_SANDBOX_MODES = Object.freeze([
71
- 'read-only',
72
- 'workspace-write',
73
- 'danger-full-access',
74
- ])
92
+ // #6689: single-sourced from @chroxy/protocol (the wire contract) so the
93
+ // server, the create_session schema, and both client selectors share exactly
94
+ // one list. Frozen re-export preserves the pre-#6689 API for the server
95
+ // consumers that already `import { CODEX_SANDBOX_MODES } from './codex-session.js'`.
96
+ export const CODEX_SANDBOX_MODES = Object.freeze([...PROTOCOL_CODEX_SANDBOX_MODES])
75
97
 
76
98
  /**
77
99
  * Default sandbox mode when nothing overrides it. Matches the #3846 stopgap
78
100
  * — Codex would otherwise fall back to read-only in any non-trusted dir and
79
101
  * be unable to edit files in fresh chroxy sessions.
80
102
  */
81
- export const CODEX_DEFAULT_SANDBOX = 'workspace-write'
103
+ export const CODEX_DEFAULT_SANDBOX = PROTOCOL_CODEX_DEFAULT_SANDBOX
82
104
 
83
105
  /**
84
106
  * Module-level cache of invalid `CHROXY_CODEX_SANDBOX` values we have
@@ -109,9 +131,19 @@ const _warnedSandboxValues = new Set()
109
131
  * Read at call time (not module-load time) so the override responds to test
110
132
  * harnesses, hot reload, and in-process env changes.
111
133
  *
134
+ * #6638: a per-session `override` (from create_session `codexSandbox`) wins over
135
+ * the env when it is a valid mode — so a session can pick read-only / full-access
136
+ * without changing the server-wide env. An invalid override is ignored and the
137
+ * env → default resolution proceeds (the schema already gates the wire value, so
138
+ * this only bites an internal caller passing garbage).
139
+ *
140
+ * @param {string} [override] - per-session sandbox mode, wins over the env if valid
112
141
  * @returns {'read-only'|'workspace-write'|'danger-full-access'}
113
142
  */
114
- export function resolveCodexSandbox() {
143
+ export function resolveCodexSandbox(override) {
144
+ if (typeof override === 'string' && CODEX_SANDBOX_MODES.includes(override.trim())) {
145
+ return override.trim()
146
+ }
115
147
  const raw = process.env.CHROXY_CODEX_SANDBOX
116
148
  if (typeof raw !== 'string' || raw.length === 0) return CODEX_DEFAULT_SANDBOX
117
149
  const trimmed = raw.trim()
@@ -131,6 +163,51 @@ export function resolveCodexSandbox() {
131
163
  return CODEX_DEFAULT_SANDBOX
132
164
  }
133
165
 
166
+ /**
167
+ * Serialize a string as a TOML **basic string** for a `codex exec -c key=<v>`
168
+ * override. Exported for unit testing.
169
+ *
170
+ * Why this exists (#7766): before #7727 the `model` id reaching
171
+ * `buildCodexArgs` was always one of six compiled-in literals, so raw
172
+ * interpolation into `model="${id}"` was safe by construction. Tri-state
173
+ * validation removed that construction — on the unrestricted branch the id is
174
+ * an arbitrary operator-supplied string — and argv-shape safety (one element,
175
+ * no shell) does NOT extend to the TOML grammar codex parses that element
176
+ * under. That is the "validated value handed on to something that parses it
177
+ * under a different grammar" entry in `docs/false-safety-guards.md`.
178
+ *
179
+ * JSON's string escaping is a SUBSET of TOML 1.0's basic-string escaping with
180
+ * exactly two known exceptions, both listed below: `JSON.stringify` escapes
181
+ * `"` and the backslash, emits the short forms `\\b \\f \\n \\r \\t` that TOML
182
+ * also defines, and `\\uXXXX` for every other control character — all of which
183
+ * TOML accepts. Everything else passes through unchanged, which is why an
184
+ * ordinary id still round-trips to the byte-identical `model="gpt-5-codex"`
185
+ * this produced before.
186
+ *
187
+ * Exception 1 — DEL (U+007F). The one character TOML forbids raw in a basic
188
+ * string but JSON leaves alone, so it is escaped afterwards by the `.replace`
189
+ * below.
190
+ *
191
+ * Exception 2 — a LONE SURROGATE, and it is NOT fixed here. ES2019
192
+ * well-formed `JSON.stringify` emits `\\udXXX` for an unpaired surrogate
193
+ * (`toTomlBasicString('a\\uD800b')` → `"a\\ud800b"`), but TOML's `\\uXXXX`
194
+ * must name a Unicode SCALAR value and a surrogate is not one, so that output
195
+ * is invalid TOML. Reachable post-#7727: on the unrestricted branch
196
+ * `handleSetModel` only trims and checks non-empty, so a client can send
197
+ * `{"model":"\\ud800"}`. The outcome is a CLOSED failure — codex's own TOML
198
+ * parser rejects the `-c` override and the turn errors out; the value is still
199
+ * one argv element, there is no shell, and no second `-c` appears, so nothing
200
+ * escapes into the grammar. It is deliberately NOT stripped or replaced: the
201
+ * contract these tests pin is escaped-not-sanitised, and silently rewriting an
202
+ * id would mangle a value the operator supplied rather than surface a bad one.
203
+ *
204
+ * @param {string} value
205
+ * @returns {string} a quoted, escaped TOML basic string
206
+ */
207
+ export function toTomlBasicString(value) {
208
+ return JSON.stringify(String(value)).replace(/\u007f/g, '\\u007F')
209
+ }
210
+
134
211
  /**
135
212
  * Build the argv passed to `codex exec`. Exported for unit testing.
136
213
  *
@@ -162,12 +239,38 @@ export function resolveCodexSandbox() {
162
239
  * interpolated into argv passed directly to `spawn()` — no shell, so shell
163
240
  * metacharacters can't escape.
164
241
  *
165
- * - `model` is interpolated into `-c model="${model}"` *without* re-validation
166
- * here. **Callers MUST pre-validate the model ID against
167
- * `CodexSession.getAllowedModels()` before calling.** The production gate is
168
- * `handleSetModel` in `handlers/settings-handlers.js`, which rejects any
169
- * value not in the per-provider allowlist before `session.setModel()`
170
- * writes to `this.model`.
242
+ * - `model` is serialized into `-c model=<toml basic string>` *without*
243
+ * re-validation here. **The caller-side gate is TRI-STATE since #7727 and is
244
+ * NOT an allowlist in general** — `CodexSession.getAllowedModels()` returns
245
+ * the binary's own catalog ids when it has one and `null` (unrestricted)
246
+ * when it does not, so pre-#7727 statements that this argument is always one
247
+ * of six compiled-in ids are no longer true. Read that as: on the
248
+ * unrestricted branch this receives an arbitrary non-empty string the
249
+ * operator asked for (`handleSetModel` still rejects a non-string /
250
+ * whitespace-only id, and `providers.allowAnyModel` could already produce
251
+ * exactly this before #7727).
252
+ *
253
+ * TWO independent things keep that safe, and the second is new in #7766
254
+ * because the first was being asked to do work it cannot do:
255
+ *
256
+ * 1. `spawn()` without a shell, so the value is ONE argv element: no shell
257
+ * metacharacter can escape into a second process, and no second `-c`
258
+ * override can be introduced. That bounds the blast radius to "whatever
259
+ * codex's own TOML parser makes of this one element".
260
+ * 2. `toTomlBasicString()` escapes the value, so it cannot escape the TOML
261
+ * string EITHER. This prose used to stop at (1) and claim that a quote
262
+ * merely produced "invalid TOML that Codex CLI rejects" — an unverified
263
+ * claim about a third-party parser's error handling, standing in for
264
+ * escaping we were not doing (`docs/false-safety-guards.md`: a guard
265
+ * whose comment describes a stronger check than its code performs). A
266
+ * `"` plus a newline is a plausible way to close the string and open a
267
+ * second key INSIDE the same argv element, and an argv-shape assertion
268
+ * says nothing about that. Escaping removes the question rather than
269
+ * answering it.
270
+ *
271
+ * `tests/codex-session.test.js` executes both halves against a hostile id —
272
+ * the argv shape, the escaping, and the absence of a `shell` option on the
273
+ * spawn path — so neither claim survives only in prose (#7646).
171
274
  *
172
275
  * - `threadId` (#3865) is **trusted because it comes from Codex CLI's own
173
276
  * `thread.started` JSONL stdout** — captured in `_processJsonlLine`, never
@@ -182,39 +285,97 @@ export function resolveCodexSandbox() {
182
285
  * alternate spawn path), preserve these invariants or add validation here.
183
286
  *
184
287
  * @param {string} text User prompt
185
- * @param {string|null} model Optional model ID. Caller must validate against
186
- * `CodexSession.getAllowedModels()`. If falsy,
187
- * no `-c model=` flag is appended — Codex CLI
188
- * uses its own default.
288
+ * @param {string|null} model Optional model ID. The caller-side gate is
289
+ * TRI-STATE since #7727, so this is NOT
290
+ * guaranteed to come from an allowlist — see the
291
+ * SECURITY INVARIANT above for what does hold. If
292
+ * falsy, no `-c model=` flag is appended — Codex
293
+ * CLI uses its own default.
189
294
  * @param {string|null} threadId Optional Codex thread_id captured from a
190
295
  * previous turn's `thread.started` event.
191
296
  * When set, switches to `exec resume <id>`
192
297
  * form so the CLI replays prior conversation
193
298
  * state instead of treating each message as
194
299
  * a fresh thread (#3865).
300
+ * @param {string} [sandboxOverride] #6638 — per-session sandbox mode; wins over
301
+ * the CHROXY_CODEX_SANDBOX env / default if valid.
195
302
  * @returns {string[]}
196
303
  */
197
- export function buildCodexArgs(text, model, threadId = null) {
198
- // INVARIANT: --sandbox must be passed to the parent `exec`, not to the
304
+ export function buildCodexArgs(text, model, threadId = null, sandboxOverride = undefined) {
305
+ // INVARIANT 1: --sandbox must be passed to the parent `exec`, not to the
199
306
  // `resume` subcommand. `codex exec resume --sandbox ...` errors out with
200
307
  // `unexpected argument '--sandbox' found` (verified against codex-cli
201
- // 0.128.0) because --sandbox is only declared on the parent `exec` command.
202
- // Keep --sandbox BEFORE the `resume` subcommand on the resume path.
203
- const sandbox = resolveCodexSandbox()
308
+ // 0.128.0, still true on 0.154.0) because --sandbox is only declared on the
309
+ // parent `exec` command. Keep --sandbox BEFORE the `resume` subcommand.
310
+ //
311
+ // INVARIANT 2 (#7342/#7291): `text` is TERMINATED, never bare. It is the raw
312
+ // client chat message, and it used to sit in a bare positional slot on both
313
+ // branches, where codex option-PARSED it. Measured on codex-cli 0.154.0:
314
+ //
315
+ // codex exec "- first bullet" --json …
316
+ // → error: unexpected argument '- ' found
317
+ // tip: to pass '- ' as a value, use '-- - ' (exit 2)
318
+ // codex exec --sandbox read-only resume <id> "--thread-source=x" --json …
319
+ // → consumed as an OPTION; the prompt slot falls empty and codex drops
320
+ // to "Reading prompt from stdin..." (exit 1)
321
+ //
322
+ // `resume` also declares --dangerously-bypass-approvals-and-sandbox, so the
323
+ // second shape was a sandbox-escape primitive and not merely a parse bug. A
324
+ // leading dash is LEGITIMATE input ("- first bullet"), so the fix is the `--`
325
+ // terminator (utils/argv-safety.js case 2), not rejection.
326
+ //
327
+ // Everything after `--` is POSITIONAL, which is why every flag — and the
328
+ // resume SESSION_ID, itself a positional — is emitted BEFORE it, and why
329
+ // `text` must stay the LAST element. Appending a flag after it would silently
330
+ // turn that flag into part of the prompt.
331
+ //
332
+ // #7868 — unlike `text`, `threadId` can never LEGITIMATELY start with `-`:
333
+ // it is chroxy's own identifier (a codex `thread_id`, or a client-supplied
334
+ // resume target already required to be a canonical UUID at the WS layer —
335
+ // see handlers/conversation-handlers.js's CONVERSATION_ID_RE), never free-
336
+ // form chat text. So the correct shape here is case 1 (reject), not a `--`
337
+ // terminator — which would not even help, since the SESSION_ID positional
338
+ // must stay BEFORE the separator (INVARIANT above). Before this, nothing in
339
+ // buildCodexArgs itself constrained threadId's shape: safety depended
340
+ // entirely on every external producer already happening to constrain it,
341
+ // which is the exact "someone remembers to sweep" pattern this issue's own
342
+ // lint exists to close. `resume` declares
343
+ // --dangerously-bypass-approvals-and-sandbox, so a producer that ever
344
+ // relaxed that external constraint would have reopened a sandbox-escape
345
+ // primitive, not just a parse nuisance.
346
+ if (threadId) assertSafeArgvValue(threadId, 'threadId')
347
+ const sandbox = resolveCodexSandbox(sandboxOverride)
204
348
  const args = threadId
205
- ? ['exec', '--sandbox', sandbox, 'resume', threadId, text, '--json', '--skip-git-repo-check']
206
- : ['exec', text, '--json', '--skip-git-repo-check', '--sandbox', sandbox]
349
+ ? ['exec', '--sandbox', sandbox, 'resume', '--json', '--skip-git-repo-check']
350
+ : ['exec', '--json', '--skip-git-repo-check', '--sandbox', sandbox]
207
351
  if (model) {
208
- args.push('-c', `model="${model}"`)
352
+ // #7766 — SERIALIZED, not interpolated. See the SECURITY INVARIANT above.
353
+ args.push('-c', `model=${toTomlBasicString(model)}`)
209
354
  }
355
+ // Positionals, in order: [SESSION_ID] on the resume form, then the prompt
356
+ // behind the terminator.
357
+ if (threadId) args.push(threadId)
358
+ args.push('--', text)
210
359
  return args
211
360
  }
212
361
 
213
362
  // Per-provider model metadata — #2956.
214
- // Source of truth for `set_model` validation, fallback model list, and
215
- // per-model context window/label surfaced in the dashboard dropdown. Keep
216
- // this list small and explicit until Codex CLI grows a native
217
- // `supportedModels()` equivalent.
363
+ //
364
+ // #7726 DEMOTED this from "the roster" to a CATALOGUED label/window SEED. The
365
+ // binary answers `model/list` with its own roster (codex-model-catalog.js), and
366
+ // once that catalog is in hand it REPLACES this list in getFallbackModels() —
367
+ // a union would mean a retired model never dies. These six remain as the
368
+ // cold-boot seed (before any probe has resolved) and as the label/window
369
+ // lookup for an id the catalog does not carry; every row they produce is
370
+ // stamped `provenance: 'catalogued'` so a hand-maintained row is LABELLED as
371
+ // hand-maintained instead of masquerading as provider truth (the #7348 class).
372
+ //
373
+ // #7727 finished the demotion: this table is NO LONGER a validation roster at
374
+ // all. It is consumed by exactly two things — `CODEX_FALLBACK_MODELS` (the
375
+ // cold-boot picker) and `getModelMetadata`'s label/window LOOKUP for a still-
376
+ // known id. `getAllowedModels()` reads the catalog and nothing else; there is
377
+ // deliberately no `CODEX_ALLOWED_MODELS` constant here for a future edit to
378
+ // reach for.
218
379
  //
219
380
  // Context-window values come from the OpenAI model docs; `contextWindow` is
220
381
  // used both in the token-usage HUD and as the Codex-side override for the
@@ -239,18 +400,93 @@ const CODEX_MODEL_METADATA = Object.freeze({
239
400
  'o3': { label: 'o3', contextWindow: 200_000 },
240
401
  })
241
402
 
242
- const CODEX_ALLOWED_MODELS = Object.freeze(Object.keys(CODEX_MODEL_METADATA))
403
+ /**
404
+ * #7731 (GUARD-1) — the ids of `CODEX_MODEL_METADATA` that the shipped binary
405
+ * NO LONGER OFFERS, declared rather than inferred.
406
+ *
407
+ * The seed above is a hand-maintained list sitting beside a set that moves with
408
+ * OpenAI's releases, which is this repo's #1 recurring defect shape. #7726
409
+ * removed its authority (the binary's `model/list` is the roster) but left it
410
+ * free to ROT: a row nothing serves any more keeps its label/window lookup and
411
+ * keeps seeding the cold-boot picker, and nothing goes red.
412
+ *
413
+ * This roster is what the parity guard (`tests/model-catalog-parity.test.js`)
414
+ * measures the seed against: every seed id must be either present in the
415
+ * producer's own catalog or named HERE, and every id named here must still be
416
+ * in the seed. A retired model therefore has to be declared in a diff instead
417
+ * of lingering, and a stale declaration cannot outlive the row it describes.
418
+ *
419
+ * All six are listed today because none of them is in the roster codex-cli
420
+ * 0.154.0 serves (`gpt-6-astra, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna,
421
+ * gpt-5.5, gpt-5.3-codex-spark` — recorded on epic #7721, comment 5644101381,
422
+ * and restated at the top of `codex-model-catalog.js`). "Deprecated" here means
423
+ * exactly that and nothing more: not offered by the binary this repo has
424
+ * evidence for, kept as a label/window LOOKUP for a historical id. Nothing
425
+ * reads this set at runtime — it changes no roster, no validation and no wire
426
+ * field, so a row's presence here is a claim about the producer, never a
427
+ * behaviour change.
428
+ */
429
+ const CODEX_DEPRECATED_SEED_IDS = Object.freeze(new Set([
430
+ 'gpt-5-codex',
431
+ 'gpt-5',
432
+ 'gpt-4.1',
433
+ 'gpt-4o',
434
+ 'o1',
435
+ 'o3',
436
+ ]))
243
437
 
244
- const CODEX_FALLBACK_MODELS = Object.freeze(CODEX_ALLOWED_MODELS.map(id => {
438
+ // #7727 — `CODEX_ALLOWED_MODELS` is DELETED, not merely unreferenced. It was
439
+ // `Object.keys(CODEX_MODEL_METADATA)`, returned verbatim by
440
+ // `getAllowedModels()`, and it is the frozen-roster lockout this issue retires:
441
+ // every model the binary actually serves today (gpt-5.5, gpt-6-astra, …) was
442
+ // rejected by it, leaving `providers.allowAnyModel: ["codex"]` as the only way
443
+ // to run codex at all (#6378). Removing the NAME is the structural half of the
444
+ // fix — a later edit cannot `return` a constant that does not exist, and this
445
+ // file no longer holds a six-id array for one to reach for.
446
+ const CODEX_FALLBACK_MODELS = Object.freeze(Object.keys(CODEX_MODEL_METADATA).map(id => {
245
447
  const meta = CODEX_MODEL_METADATA[id]
246
448
  return Object.freeze({
247
449
  id,
248
450
  label: meta.label,
249
451
  fullId: id,
250
452
  contextWindow: meta.contextWindow,
453
+ // #7726 — hand-maintained, and says so on the wire.
454
+ provenance: 'catalogued',
251
455
  })
252
456
  }))
253
457
 
458
+ /**
459
+ * #7726 — one catalog row to the `{id,label,fullId,contextWindow,...}` entry
460
+ * shape both `getFallbackModels()` and `getModelMetadata()` hand the registry.
461
+ *
462
+ * `contextWindow` is the row's value or explicit `null` — never a fabricated
463
+ * number and never borrowed from a same-named static row. models.js preserves
464
+ * an explicit null instead of substituting DEFAULT_CONTEXT_WINDOW, so the
465
+ * dashboard omits the chip rather than showing an invented 200k (#5418/#5444).
466
+ *
467
+ * `reasoningLevels` / `defaultReasoningLevel` are OMITTED when the row has
468
+ * none, rather than emitted empty: `withModelMetadata` (models.js) skips
469
+ * undefined/null, so an absent key means "not recorded" on the wire, which is
470
+ * the contract #7723 established for these fields.
471
+ */
472
+ function catalogEntry(row) {
473
+ const entry = {
474
+ id: row.id,
475
+ label: typeof row.label === 'string' && row.label.length > 0 ? row.label : row.id,
476
+ fullId: row.id,
477
+ contextWindow: Number.isInteger(row.contextWindow) && row.contextWindow > 0 ? row.contextWindow : null,
478
+ description: typeof row.description === 'string' ? row.description : '',
479
+ provenance: typeof row.provenance === 'string' && row.provenance.length > 0 ? row.provenance : 'discovered',
480
+ }
481
+ if (Array.isArray(row.reasoningLevels) && row.reasoningLevels.length > 0) {
482
+ entry.reasoningLevels = row.reasoningLevels
483
+ }
484
+ if (typeof row.defaultReasoningLevel === 'string' && row.defaultReasoningLevel.length > 0) {
485
+ entry.defaultReasoningLevel = row.defaultReasoningLevel
486
+ }
487
+ return entry
488
+ }
489
+
254
490
  /**
255
491
  * Headroom multiplier for the learn-loop. Re-exported from the shared
256
492
  * `CONTEXT_WINDOW_HEADROOM` constant in `utils/context-window-learn.js`
@@ -293,6 +529,12 @@ export function _maybeRatchetContextWindow(session, modelId, inputTokens) {
293
529
  }
294
530
 
295
531
  export class CodexSession extends JsonlSubprocessSession {
532
+ static canonicalAssistantResponses = true
533
+
534
+ static get customizationDescriptor() {
535
+ return CODEX_EXEC_CUSTOMIZATION
536
+ }
537
+
296
538
  // ------------------------------------------------------------------
297
539
  // Static provider identity — required by JsonlSubprocessSession
298
540
  // ------------------------------------------------------------------
@@ -302,7 +544,16 @@ export class CodexSession extends JsonlSubprocessSession {
302
544
  }
303
545
 
304
546
  static get resolvedBinary() {
305
- return CODEX
547
+ // Re-resolve fresh on every access (NOT a frozen module-load const) so a
548
+ // binary quarantined / moved / reinstalled after daemon start is spawned
549
+ // from its CURRENT path — and matches what preflight verified (#6708).
550
+ //
551
+ // #8609 — CHROXY_CODEX_BIN (config `codexBinary`) names the client to
552
+ // launch. No PATH lookup: this exact path is what preflight/provenance
553
+ // verifies, so a bad path fails at preflight naming it. Read per access.
554
+ const override = typeof process.env.CHROXY_CODEX_BIN === 'string' ? process.env.CHROXY_CODEX_BIN.trim() : ''
555
+ if (override) return override
556
+ return resolveBinary('codex', BINARY_CANDIDATES)
306
557
  }
307
558
 
308
559
  static get apiKeyEnv() {
@@ -352,12 +603,21 @@ export class CodexSession extends JsonlSubprocessSession {
352
603
  return {
353
604
  permissions: false,
354
605
  inProcessPermissions: false,
606
+ permissionFloor: false,
607
+ autoPermissionMode: false,
608
+ nativeSandbox: true,
355
609
  modelSwitch: true,
356
610
  permissionModeSwitch: false,
357
611
  planMode: false,
358
612
  resume: false,
359
613
  terminal: false,
360
614
  thinkingLevel: false,
615
+ // #7725: codex has its own reasoning-effort knob, but the Claude magic
616
+ // keywords mean nothing to it and the daemon never scans for them here.
617
+ // Kept SEPARATE from `thinkingLevel` precisely so #7730 can flip that one
618
+ // on without the client also promising keyword escalation.
619
+ thinkingKeywords: false,
620
+ thinkingLevelEffective: false, // #8700: no report of the applied level
361
621
  // #3932: declared explicitly so the capability matrix matches across
362
622
  // providers — claude-tui is the only one that sets this to false.
363
623
  streaming: true,
@@ -365,12 +625,60 @@ export class CodexSession extends JsonlSubprocessSession {
365
625
  }
366
626
 
367
627
  /**
368
- * Model IDs this provider accepts in `set_model`. Returns a plain array so
369
- * the settings handler can surface it to the client on rejection.
370
- * @returns {string[]}
628
+ * #7727 — TRI-STATE model validation, read by BOTH gates:
629
+ * `getProviderAllowedModels` (handlers/settings-handlers.js, the `set_model`
630
+ * path) and `_resolveCreateSessionPlan` (session-manager.js, the
631
+ * create-session path).
632
+ *
633
+ * - **catalog in hand** → its ids, and they are AUTHORITATIVE. The binary
634
+ * answered `model/list`; anything it did not name cannot be started, so
635
+ * rejecting is the provider's own truth rather than a chroxy opinion.
636
+ * - **no catalog** (never probed, probe failed, or the binary answered
637
+ * with ZERO rows) → `null`, i.e. UNRESTRICTED. Both gates map a
638
+ * non-array to "accept any non-empty id verbatim" — the ollama rule
639
+ * (#5418) — and the id is then validated by codex itself.
640
+ *
641
+ * Two returns are forbidden here, and each has its own red-proof in
642
+ * `tests/codex-model-validation.test.js`:
643
+ *
644
+ * - **the static seed.** "I could not ask" collapsing back into "these
645
+ * six" is precisely the lockout #7726/#7727 exist to remove, and it is
646
+ * the shape `anthropic-compatible-session.js:405-412` uses
647
+ * (`catalogIds -> entry.models -> null`) — correct THERE, because its
648
+ * middle rung is an operator-declared list, and wrong here, because
649
+ * ours is a hand-maintained seed that no longer matches any shipped
650
+ * binary. Deliberately NOT copied.
651
+ * - **an empty array.** It is the dangerous near-miss: `session-manager`
652
+ * skips it (`length > 0`) while `set_model` treats it as a DENY-ALL
653
+ * (`[]` is truthy, `[].includes(x)` is false) — so the same value means
654
+ * "unvalidated" at one gate and "nothing is allowed" at the other, and
655
+ * it reads as an authoritative allowlist to every future reader. A
656
+ * zero-row answer therefore takes the `null` branch, exactly like a
657
+ * failed probe: `hasCodexCatalog()` is false for BOTH, and
658
+ * `getCodexCatalogState()` is what tells them apart when that matters.
659
+ *
660
+ * The catalog is read DIRECTLY — not through `getFallbackModels()` and not
661
+ * through the models registry. The registry's roster is
662
+ * `discovered ∪ the statics captured at construction` (the #7761 deviation
663
+ * recorded on #7757: `createModelsRegistry` snapshots `getFallbackModels()`
664
+ * once, always before the first probe resolves, and `updateModels` merges
665
+ * the captured rows back), so validating against it would accept a stale
666
+ * hand-maintained id the binary does not serve. `tests/codex-model-
667
+ * validation.test.js` pins that divergence in both directions.
668
+ *
669
+ * `providers.allowAnyModel: ["codex"]` (#6378) is now a redundant
670
+ * workaround rather than the only way to run this provider — it still
671
+ * short-circuits both gates ahead of this method, and is deliberately kept.
672
+ *
673
+ * @returns {string[]|null} the catalog ids, or null = unrestricted.
371
674
  */
372
675
  static getAllowedModels() {
373
- return CODEX_ALLOWED_MODELS
676
+ // A fresh array per call: the catalog rows are frozen, but the ARRAY a
677
+ // caller receives must not be a handle onto module state (the
678
+ // deepseek/anthropic-compatible rule — a caller `.push()`ing into the
679
+ // allowlist must not widen it for everyone).
680
+ if (hasCodexCatalog()) return getCodexCatalogRows().map((row) => row.id)
681
+ return null
374
682
  }
375
683
 
376
684
  /**
@@ -382,9 +690,70 @@ export class CodexSession extends JsonlSubprocessSession {
382
690
  * @returns {ReadonlyArray<{id:string,label:string,fullId:string,contextWindow:number}>}
383
691
  */
384
692
  static getFallbackModels() {
693
+ // #7726 — REPLACE, not union, AT THIS FUNCTION. Once the binary has
694
+ // answered `model/list`, its roster is what this RETURNS; the six static
695
+ // rows do not ride along here, because a union means a model OpenAI
696
+ // retired never disappears. Pre-catalog (cold boot, probe not resolved,
697
+ // probe failed) the catalogued seed keeps the picker useful. `hasCatalog`
698
+ // is the sentinel-aware check: a catalog that was never fetched and one
699
+ // that came back empty are different facts, and neither of them may be
700
+ // reported as a roster.
701
+ //
702
+ // AND IT NOW ALSO HOLDS AT THE WIRE (#7761). It did not until that issue:
703
+ // the codex registry snapshots this function's result ONCE, at construction
704
+ // (`getRegistryForProvider` → `fallbackModels: getFallbackModels()`,
705
+ // models.js) — which always happens while the catalog is still UNSET, so
706
+ // the captured roster is always the six statics, and `updateModels` used to
707
+ // merge back every one the refresh omitted (the #3075 under-reporting
708
+ // union). Net `available_models` was `discovered ∪ {gpt-5-codex, gpt-5,
709
+ // gpt-4.1, gpt-4o, o1, o3}` in every process, PERMANENTLY — no path builds
710
+ // the registry after the catalog exists, so a restart reproduced it rather
711
+ // than clearing it, and `gpt-4.1`'s 1M window then minted a `gpt-4.1[1m]`
712
+ // chip that exists in no catalog (#7747). #7761 scoped BOTH rules to the
713
+ // Claude registry (identity check on the fallback roster), so a discovered
714
+ // codex roster now REPLACES at the wire as well. The registry-level test in
715
+ // codex-model-catalog.test.js pins that in BOTH directions — the discovered
716
+ // ids are present AND every static the refresh did not discover is absent —
717
+ // so a re-widening cannot land quietly. The captured roster is still stale
718
+ // by construction; it is simply no longer consulted once a refresh lands.
719
+ //
720
+ // The precise scope, because "REPLACES at the wire" on its own overstates
721
+ // it: the statics ARE still what `available_models` carries BEFORE any
722
+ // roster is learned — cold boot with no cache, probe unresolved, probe
723
+ // failed — which is the seed doing its job, not the union. What #7761/#7776
724
+ // removed is the seed riding back in ON TOP of a roster the binary reported,
725
+ // and that now holds at all three merge sites in models.js (`updateModels`,
726
+ // `loadCache`, `applyOverlay`'s cache-warmed branch). Stated at the
727
+ // observable rather than at the rule, because the two differ: the UNION no
728
+ // longer re-adds them, and rows a pre-fix build already PERSISTED are still
729
+ // served until the migration runs — `saveCache()` wrote `activeModels`, and
730
+ // the file is what boots. `loadCache`'s one-time schema-marker migration
731
+ // (models.js, `migrateLegacyStaticSeed`) is what takes them out of the file;
732
+ // absent that, they would be served indefinitely on an install whose probe
733
+ // never succeeds. Validation (`getAllowedModels`) is a separate roster and is
734
+ // untouched: #7727 is where the catalogue becomes authoritative there, so
735
+ // until it lands an id this function stopped OFFERING can still be ACCEPTED.
736
+ if (hasCodexCatalog()) {
737
+ return Object.freeze(getCodexCatalogRows().map((row) => Object.freeze(catalogEntry(row))))
738
+ }
385
739
  return CODEX_FALLBACK_MODELS
386
740
  }
387
741
 
742
+ /**
743
+ * #7731 — the ids of this provider's IN-REPO seed that the producer no longer
744
+ * offers (see `CODEX_DEPRECATED_SEED_IDS`). A fresh Set per call so a caller
745
+ * cannot widen the declaration for everyone; nothing in the runtime reads it.
746
+ *
747
+ * The parity guard treats "a provider with a catalog source AND an in-repo
748
+ * seed" as required to declare this — a provider that gains a catalog source
749
+ * and forgets it goes red rather than acquiring a seed nothing can retire.
750
+ *
751
+ * @returns {Set<string>}
752
+ */
753
+ static get deprecatedSeedModelIds() {
754
+ return new Set(CODEX_DEPRECATED_SEED_IDS)
755
+ }
756
+
388
757
  /**
389
758
  * Lookup metadata for a known Codex model. Returns null for unknown
390
759
  * ids so the registry can fall through to its generic heuristic
@@ -394,6 +763,17 @@ export class CodexSession extends JsonlSubprocessSession {
394
763
  * @returns {{id:string,label:string,fullId:string,contextWindow:number,description?:string}|null}
395
764
  */
396
765
  static getModelMetadata(modelId) {
766
+ if (typeof modelId !== 'string' || modelId.length === 0) return null
767
+ // #7726 — the discovered row wins: it carries the binary's own label, its
768
+ // reasoning levels, and a context window that came from the Codex CLI's
769
+ // cache or is honestly null.
770
+ const row = getCodexCatalogRow(modelId)
771
+ if (row) return catalogEntry(row)
772
+ // Not in the catalog (or no catalog yet): fall back to the catalogued seed
773
+ // for a LOOKUP only. This is not a membership decision — getFallbackModels
774
+ // above is the roster — so an id the seed still knows keeps its real label
775
+ // and window instead of falling through to the registry's generic 200k
776
+ // heuristic. An unknown id stays null, exactly as before.
397
777
  const meta = CODEX_MODEL_METADATA[modelId]
398
778
  if (!meta) return null
399
779
  return {
@@ -402,6 +782,69 @@ export class CodexSession extends JsonlSubprocessSession {
402
782
  fullId: modelId,
403
783
  contextWindow: meta.contextWindow,
404
784
  description: meta.description || '',
785
+ provenance: 'catalogued',
786
+ }
787
+ }
788
+
789
+ /**
790
+ * #7726 — refresh the codex model catalog from the app-server's own
791
+ * `model/list` and feed it into the codex models registry.
792
+ *
793
+ * This is the hook `scheduleProviderModelsRefresh` (ws-history.js) calls,
794
+ * fire-and-forget, whenever it sends `available_models` for this provider.
795
+ * Resolves to the refreshed list when the picker CHANGED, else null. Never
796
+ * throws and never blocks: every failure path resolves null and leaves the
797
+ * previous catalog untouched.
798
+ *
799
+ * With no `client` in `deps` this spawns a SHORT-LIVED app-server for the
800
+ * probe — the no-session/create-session path, which is exactly where the
801
+ * frozen roster used to reject the operator's configured model. A live
802
+ * session passes its own client instead (CodexAppServerSession.start).
803
+ *
804
+ * `deps` is the test seam (client / createClient / registry / now / ttlMs /
805
+ * timeoutMs / windows).
806
+ *
807
+ * `bin` and `env` are passed as THUNKS, not values (#7757 review).
808
+ * `resolvedBinary` re-runs a synchronous `execFileSync('which', …)` on every
809
+ * read by design (#6708) and `buildSpawnEnv` walks the environment; this
810
+ * method runs on the post-auth `available_models` path for the DEFAULT
811
+ * provider, so building them eagerly meant a blocking child process on every
812
+ * push — including the calls that carry a live client (never spawns) and the
813
+ * ones the TTL gate drops without probing. `probeCodexCatalog` calls the
814
+ * thunk on the one branch that actually spawns.
815
+ */
816
+ static refreshModels(deps = {}) {
817
+ try {
818
+ return refreshCodexModels({
819
+ ...deps,
820
+ registry: deps.registry || getRegistryForProvider('codex'),
821
+ // #8059 review (Suggestion 1 / S1) — a caller with NEITHER a live
822
+ // `client` NOR a verified `bin` thunk now gets REFUSED, not a silent
823
+ // unverified spawn off `this.resolvedBinary`. #8030 set this precedent
824
+ // for the one-shot summarizer/title calls (`defaultRunOneShot` throws
825
+ // when no verified `resolveExecutable` is supplied,
826
+ // summarize-session.js:207-210); this no-session probe has the exact
827
+ // same shape and the exact same risk, so it gets the same default.
828
+ // `bin` is only ever CALLED on the no-client spawn branch
829
+ // (`probeCodexCatalog`) — a `client`-carrying caller (the live
830
+ // session's own refresh) never reaches it, so this default is inert
831
+ // for that path. Today's only no-client caller (`ws-history.js`'s
832
+ // `scheduleProviderModelsRefresh`) always supplies `bin`, so this is
833
+ // a safety net for the NEXT no-client caller that forgets to, not a
834
+ // behaviour change for any caller that exists today.
835
+ bin: 'bin' in deps ? deps.bin : () => {
836
+ const err = new Error('CodexSession.refreshModels: no live client and no verified `bin` were supplied — refusing an unverified spawn (#8036/S1). Pass a `client`, or a `bin` built from a verified resolver (e.g. SessionManager.verifyOneShotExecutable).')
837
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
838
+ throw err
839
+ },
840
+ cwd: 'cwd' in deps ? deps.cwd : undefined,
841
+ env: 'env' in deps ? deps.env : () => buildSpawnEnv('codex'),
842
+ })
843
+ } catch {
844
+ // A refresh is advisory. A throw here (a registry build that blew up, a
845
+ // binary resolver that threw) must not become an unhandled rejection in
846
+ // the post-auth path.
847
+ return Promise.resolve(null)
405
848
  }
406
849
  }
407
850
 
@@ -416,6 +859,7 @@ export class CodexSession extends JsonlSubprocessSession {
416
859
  args: ['--version'],
417
860
  candidates: BINARY_CANDIDATES,
418
861
  installHint: 'install Codex CLI',
862
+ overrideEnv: 'CHROXY_CODEX_BIN', // #8609
419
863
  },
420
864
  credentials: {
421
865
  envVars: ['OPENAI_API_KEY'],
@@ -500,8 +944,37 @@ export class CodexSession extends JsonlSubprocessSession {
500
944
  super(buildBaseSessionOpts(opts, {
501
945
  provider: opts.provider || 'codex',
502
946
  model: opts.model || DEFAULT_MODEL,
947
+ // This adapter cannot intercept Auto. Do not inherit the subprocess
948
+ // layer's Auto default when the caller omitted a permission mode.
949
+ permissionMode: opts.permissionMode || 'approve',
503
950
  resumeSessionId: opts.resumeSessionId,
504
951
  }))
952
+ // #6638: per-session sandbox override — honored on the exec path too, so a
953
+ // read-only/full-access session isn't a silent no-op under CHROXY_CODEX_APPSERVER=0.
954
+ this._codexSandbox = opts.codexSandbox || null
955
+ // #6929 review — resolve ONCE here rather than on every `_buildArgs`/
956
+ // `getCodexSandbox()` call. `opts.codexSandbox` is fixed for the life of this
957
+ // session and nothing between construction and the first spawn can change it,
958
+ // so resolving now and reusing the stored value keeps every turn's `--sandbox`
959
+ // AND the displayed `getCodexSandbox()` value in permanent agreement — a later
960
+ // `CHROXY_CODEX_SANDBOX` env change can no longer retroactively change what a
961
+ // running session reports (display/reality drift).
962
+ this._resolvedCodexSandbox = resolveCodexSandbox(this._codexSandbox)
963
+ }
964
+
965
+ /**
966
+ * #6901: the ACTIVE/resolved sandbox mode this session runs under, so
967
+ * `SessionManager.listSessions()` can surface it in `session_list`
968
+ * (`SessionInfo.codexSandbox`) for a running codex session. #6929 review:
969
+ * returns the value resolved ONCE at construction (see ctor) instead of
970
+ * re-resolving `CHROXY_CODEX_SANDBOX` on every call, so a later env change
971
+ * can't make the display drift from what this session's turns actually spawn
972
+ * with. Display-only: a mid-session change needs a new session (Codex
973
+ * applies `--sandbox` fresh per turn here, but always with this same value).
974
+ * @returns {string} one of CODEX_SANDBOX_MODES
975
+ */
976
+ getCodexSandbox() {
977
+ return this._resolvedCodexSandbox
505
978
  }
506
979
 
507
980
  // ------------------------------------------------------------------
@@ -509,7 +982,7 @@ export class CodexSession extends JsonlSubprocessSession {
509
982
  // ------------------------------------------------------------------
510
983
 
511
984
  _buildArgs(text) {
512
- return buildCodexArgs(text, this.model, this.resumeSessionId)
985
+ return buildCodexArgs(text, this.model, this.resumeSessionId, this._resolvedCodexSandbox)
513
986
  }
514
987
 
515
988
  _buildChildEnv() {
@@ -535,7 +1008,9 @@ export class CodexSession extends JsonlSubprocessSession {
535
1008
  const item = event.item
536
1009
  if (!item) break
537
1010
 
538
- if (item.type === 'agent_message' && item.text) {
1011
+ if (item.type === 'agent_message') {
1012
+ this.emit('assistant_response', { responseId: item.id, text: assistantResponseText(item.text) })
1013
+ if (typeof item.text !== 'string' || !item.text) break
539
1014
  if (!ctx.didStreamStart) {
540
1015
  this.emit('stream_start', { messageId: ctx.messageId })
541
1016
  ctx.didStreamStart = true
@@ -566,8 +1041,12 @@ export class CodexSession extends JsonlSubprocessSession {
566
1041
  ctx.didStreamStart = false
567
1042
  }
568
1043
  const usage = event.usage || {}
569
- const inputTokens = usage.input_tokens || 0
570
- const outputTokens = usage.output_tokens || 0
1044
+ // #6718: the ratchet below keys off the INCLUSIVE prompt size — codex
1045
+ // reports `input_tokens` as the whole prompt with `cached_input_tokens`
1046
+ // as a SUBSET of it, and a cache-heavy turn still occupies that much
1047
+ // context window. The emitted usage uses the DISJOINT split instead
1048
+ // (see _mapUsage); the two must not be conflated.
1049
+ const inputTokens = nonNegInt(usage.input_tokens)
571
1050
  // #3857 learn-loop: when Codex reports an `input_tokens` value that
572
1051
  // exceeds the registered context window for the active model, the
573
1052
  // static window is stale (this is exactly how we found the original
@@ -588,10 +1067,8 @@ export class CodexSession extends JsonlSubprocessSession {
588
1067
  this.emit('result', {
589
1068
  cost: null,
590
1069
  duration: null,
591
- usage: {
592
- input_tokens: inputTokens,
593
- output_tokens: outputTokens,
594
- },
1070
+ usage: this._mapUsage(usage),
1071
+ declarationEligible: !event.error,
595
1072
  sessionId: this.resumeSessionId,
596
1073
  })
597
1074
  break
@@ -601,4 +1078,53 @@ export class CodexSession extends JsonlSubprocessSession {
601
1078
  break
602
1079
  }
603
1080
  }
1081
+
1082
+ /**
1083
+ * #6718 — map a `turn.completed` usage payload onto chroxy's accounting keys.
1084
+ *
1085
+ * Codex reports cached tokens as a SUBSET of `input_tokens` (OpenAI's
1086
+ * `prompt_tokens_details` convention; corroborated in-repo by the context
1087
+ * ratchet above, which treats `input_tokens` as the full prompt). Chroxy's
1088
+ * accumulator keys are ADDITIVE (Anthropic shape: input EXCLUDES cache
1089
+ * reads), so split into uncached input + cache_read. The subtraction is
1090
+ * clamped, so a future codex build that switched to additive reporting would
1091
+ * undercount input rather than go negative.
1092
+ *
1093
+ * Before this fix the exec path emitted only `input_tokens`/`output_tokens`
1094
+ * and dropped the cached count entirely — session-manager `_trackUsage`
1095
+ * reads `cache_read_input_tokens`, so codex-exec cache tokens never reached
1096
+ * `cumulativeUsage`. The app-server path got the same fix in #6717/#6692;
1097
+ * this is the deliberate mirror of `CodexAppServerSession._mapUsage`, and
1098
+ * the two splits must stay identical — a divergent split between the default
1099
+ * and the `CHROXY_CODEX_APPSERVER=0` opt-out is worse than no split at all.
1100
+ *
1101
+ * Extracted as a method (rather than inlined) so the mapping is directly
1102
+ * unit-testable without spawning a subprocess — the reason #6717 could not
1103
+ * safely fix this path (the old shim harness reimplemented the parse loop).
1104
+ *
1105
+ * @param {object} usage raw `turn.completed` usage object (may be empty)
1106
+ * @returns {{input_tokens:number,output_tokens:number,cache_read_input_tokens:number,cached_input_tokens:number}}
1107
+ */
1108
+ _mapUsage(usage) {
1109
+ const u = usage || {}
1110
+ // Snake_case is the `codex exec --json` wire shape; camelCase is accepted
1111
+ // purely so this stays interchangeable with the app-server `_mapUsage`,
1112
+ // whose JSON-RPC wire is camel. Key PRECEDENCE is deliberately identical
1113
+ // to the app-server mirror (camel first) rather than "native wire first":
1114
+ // both orders behave the same on either real wire (the other casing is
1115
+ // absent), but a payload carrying BOTH casings would otherwise be split
1116
+ // differently by the two codex drivers — the exact divergence the
1117
+ // "must stay identical" rule above exists to prevent.
1118
+ const rawInput = nonNegInt(u.inputTokens ?? u.input_tokens)
1119
+ const cached = nonNegInt(u.cachedInputTokens ?? u.cached_input_tokens)
1120
+ return {
1121
+ input_tokens: nonNegInt(rawInput - cached),
1122
+ output_tokens: nonNegInt(u.outputTokens ?? u.output_tokens),
1123
+ cache_read_input_tokens: cached,
1124
+ // Deprecated duplicate of cache_read_input_tokens — mirrors the
1125
+ // app-server payload for one release so any external reader of the raw
1126
+ // result sees the same shape on both codex paths (#6692).
1127
+ cached_input_tokens: cached,
1128
+ }
1129
+ }
604
1130
  }