@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  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 +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  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-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,16 +1,31 @@
1
- import { mkdtempSync, rmSync } from 'fs'
1
+ import { assistantResponseText } from './assistant-response.js'
2
+ import { mkdirSync, writeFileSync, rmSync } from 'fs'
3
+ import { randomUUID } from 'crypto'
2
4
  import { tmpdir } from 'os'
3
- import { join, basename, extname } from 'path'
4
- import { BaseSession, buildBaseSessionOpts, DEFAULT_RESULT_TIMEOUT_MS } from './base-session.js'
5
+ import { join, basename, extname, posix as posixPath, win32 as win32Path } from 'path'
6
+ import { BaseSession, buildBaseSessionOpts, DEFAULT_RESULT_TIMEOUT_MS, reportInputAdmission } from './base-session.js'
7
+ import { CODEX_APPSERVER_CUSTOMIZATION } from './provider-customization.js'
8
+ import { sweepStaleOwnedDirs, ensureOwnedBaseDir, OWNER_PID_FILE } from './utils/stale-session-dirs.js'
5
9
  import { isOperatorTimeoutInRange } from './duration.js'
6
10
  import { nonNegInt, synthesizeModelUsage } from './usage-normalize.js'
7
11
  import { CodexSession, resolveCodexSandbox } from './codex-session.js'
8
12
  import { CodexAppServerClient } from './codex-app-server-client.js'
13
+ import { parseCodexUserAgent, capabilitiesForVersion, parseSemver, compareSemver } from './codex-protocol-capabilities.js'
14
+ import { findNewestBundledCodexClient } from './codex-bundled-client.js'
15
+ import {
16
+ MODEL_UNSUPPORTED_CODE, detectModelRejection, codexClientKey, recordModelRejection,
17
+ rejectedDefaultFor, rejectedModelsFor, suggestFallbackModel,
18
+ } from './codex-model-rejections.js'
19
+ import { describeCodexError, formatCodexError, rawCodexErrorForLog, UNREADABLE_CODEX_ERROR } from './codex-error-text.js'
9
20
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
10
21
  import { materializeAttachments, buildAttachmentsPromptSuffix } from './claude-tui-attachments.js'
11
22
  import { buildSpawnEnv } from './utils/spawn-env.js'
23
+ import { maybeRatchetContextWindow } from './utils/context-window-learn.js'
24
+ import { getRegistryForProvider } from './models.js'
12
25
  import { labelBinarySpawnFailure } from './utils/verify-binary.js'
13
26
  import { createLogger, loggerForSession } from './logger.js'
27
+ import { USAGE_LIMIT_CODE } from './claude-tui/usage-limit.js'
28
+ import { NATIVE_RESUME_DRIVER, NATIVE_RESUME_VERSION, nativeRestoreError, nativeMachineId, bindNativeOwnership, validateLocator, validateEcho, policyNoBroader, writeBindings, resumeParams, sandboxMode } from './codex-native-resume.js'
14
29
 
15
30
  // Image extensions codex can attach for VISION via a `localImage` input item.
16
31
  const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg'])
@@ -25,6 +40,19 @@ const MAX_PENDING_FILE_CHANGES = 500
25
40
  // tool_result can't balloon the transcript or the persisted history ring.
26
41
  const MAX_MCP_RESULT_CHARS = 10_000
27
42
 
43
+ // #8710: cap on the ids of codex turns codex itself has ended (see
44
+ // `_noteNativeTurnEnded`). Stragglers only trail the last turn or two.
45
+ const MAX_ENDED_NATIVE_TURN_IDS = 32
46
+
47
+ // #7729/#8710: notifications about the SESSION rather than a turn, and their
48
+ // handlers. One table, so the three places that must agree on the set — with a
49
+ // turn open, with none, and for a turn that has already ended — cannot drift.
50
+ const SESSION_SCOPED_HANDLERS = new Map([
51
+ ['thread/tokenUsage/updated', (session, params) => session._onTokenUsage(params)],
52
+ // #7729 — codex moved this thread to another model server-side.
53
+ ['model/rerouted', (session, params) => session._onModelRerouted(params)],
54
+ ])
55
+
28
56
  // #6629: bounded backstop for codex's OWN response-stream reconnect loop. #6623
29
57
  // keeps the turn OPEN on a transient `Reconnecting... N/M` error so codex can
30
58
  // recover, and the only pre-existing backstop was the 30-min result timeout.
@@ -106,6 +134,9 @@ function resolveReconnectDeadlineMs(optValue, logger = log) {
106
134
  }
107
135
 
108
136
  const log = createLogger('codex-app-server')
137
+ const CODEX_FIRST_PARTY_API_BASE_URL = 'https://api.openai.com/v1'
138
+ const CODEX_FIRST_PARTY_CHATGPT_BASE_URL = 'https://chatgpt.com/backend-api/'
139
+ const CODEX_FIRST_PARTY_NATIVE_BASE_URL = 'https://chatgpt.com/backend-api/codex'
109
140
 
110
141
  /**
111
142
  * Codex session driven through the `codex app-server` JSON-RPC protocol
@@ -117,9 +148,9 @@ const log = createLogger('codex-app-server')
117
148
  * notifications onto Chroxy's standard event contract.
118
149
  *
119
150
  * PHASE 2 (#6605) surfaces codex's APPROVALS through Chroxy's permission
120
- * pipeline. `approvalPolicy` is derived from the session's permission mode
121
- * (`auto` → `never`, else `on-request`), so codex asks before running a command
122
- * or editing a file; the server → client approval RPC
151
+ * pipeline. `approvalPolicy` is `on-request` in EVERY permission mode (#8619:
152
+ * Auto included — `never` would emit no approval RPC at all), so codex asks
153
+ * before running a command or editing a file; the server → client approval RPC
123
154
  * (`item/commandExecution/requestApproval` / `item/fileChange/requestApproval`)
124
155
  * is routed into a PermissionManager exactly like SdkSession's `canUseTool`
125
156
  * bridge — it emits `permission_request`, waits for the user's
@@ -138,6 +169,44 @@ const log = createLogger('codex-app-server')
138
169
  * CodexSession's statics so both paths report identically.
139
170
  */
140
171
  export class CodexAppServerSession extends BaseSession {
172
+ static canonicalAssistantResponses = true
173
+
174
+ static get customizationDescriptor() { return CODEX_APPSERVER_CUSTOMIZATION }
175
+ static get inputRequiresReady() { return true }
176
+
177
+ get providerBinaryVersion() { return this.codexVersion || 'unknown' }
178
+ // #8609 — WHICH codex this session launched, and a newer bundled one it did not.
179
+ get providerBinaryPath() { return this._spawnedBinary || null }
180
+ get providerNewerBinary() { return this._newerBinary }
181
+ /** #8909 — models the backend refused for this session's client + auth route (read live from the ledger). */
182
+ get providerRejectedModels() {
183
+ return this.codexVersion ? [...rejectedModelsFor(this._clientKey())] : []
184
+ }
185
+ get providerRuntimeCapabilities() {
186
+ return {
187
+ ...(this.codexCapabilities || {}),
188
+ nativeResume: this._nativeResumeCapability,
189
+ // This is the exact admission boundary used by sendMessage below. Busy is
190
+ // deliberately excluded: an established busy session accepts follow-ups
191
+ // through BaseSession's existing outgoing queue.
192
+ inputReady: Boolean(this._processReady && this._client),
193
+ }
194
+ }
195
+ static get nativeResumeDriver() { return NATIVE_RESUME_DRIVER }
196
+
197
+ get nativeResumeState() {
198
+ if (!this._nativeLocator) return this._nativeResumeSaved ? structuredClone(this._nativeResumeSaved) : null
199
+ return {
200
+ ...structuredClone(this._nativeLocator),
201
+ permissionMode: this.permissionMode,
202
+ model: { requested: this.model || null, observed: this.bootedModel, provider: this._nativeLocator.model.provider },
203
+ effort: { requested: this._reasoningEffortOverride, observed: this._bootedReasoningEffort },
204
+ settingsVerified: !this._nativeSettingsUnverified,
205
+ skillsPrepended: this._skillsPrepended,
206
+ threadTotals: this._threadTotals ? { ...this._threadTotals } : null,
207
+ }
208
+ }
209
+
141
210
  // -- Provider identity (delegated to CodexSession so both paths agree) --
142
211
  static get providerName() { return 'codex' }
143
212
  static get displayLabel() { return 'OpenAI Codex (app-server)' }
@@ -152,18 +221,63 @@ export class CodexAppServerSession extends BaseSession {
152
221
  static getAllowedModels() { return CodexSession.getAllowedModels() }
153
222
  static getFallbackModels() { return CodexSession.getFallbackModels() }
154
223
  static getModelMetadata(id) { return CodexSession.getModelMetadata(id) }
224
+ // #7731 — delegated for the same reason `refreshModels` is: `getProvider('codex')`
225
+ // resolves THIS class, so a declaration that lives only on CodexSession is
226
+ // invisible to anything that asks the provider registry.
227
+ static get deprecatedSeedModelIds() { return CodexSession.deprecatedSeedModelIds }
228
+ // #7726 — REQUIRED, not decorative. `providers.js` registers
229
+ // `PROVIDERS['codex'] = CodexSession` with the models registry, but
230
+ // `getProvider('codex')` returns THIS class (#6616) and that is what
231
+ // `scheduleProviderModelsRefresh` (ws-history.js) resolves and calls. A
232
+ // `refreshModels` that exists only on CodexSession is therefore never
233
+ // invoked, and the symptom is a picker that looks like flaky discovery
234
+ // rather than a wiring bug.
235
+ static refreshModels(deps) { return CodexSession.refreshModels(deps) }
236
+ // Explicit connection routes are supported only on app-server because its
237
+ // account/read RPC can prove the active auth method before thread/start.
238
+ static get agentConnectionRoutes() { return ['native', 'api'] }
239
+ static get agentConnectionCredentialKey() { return 'OPENAI_API_KEY' }
155
240
 
156
241
  static get capabilities() {
157
242
  return {
158
243
  // Phase 2 (#6605): approvals are surfaced through the permission pipeline.
159
244
  permissions: true,
160
245
  inProcessPermissions: true, // requires respondToPermission + respondToQuestion
246
+ // #7825/#8619: Auto is a real mode on this adapter because it does NOT
247
+ // map to `approvalPolicy:'never'` (which emits no requestApproval RPC and
248
+ // so has no pre-execution seam). Every mode keeps `on-request`, so every
249
+ // native approval still reaches the PermissionManager, whose auto-mode
250
+ // path resolves what passes the protected-path / secret-read floor and
251
+ // prompts on a floor hit. Keep native sandbox truth separate: every mode
252
+ // only surfaces approvals the native runtime requests, and sandbox-
253
+ // authorized tools execute without an RPC in ANY mode — so no mode can
254
+ // claim complete Chroxy floor interception, and `permissionFloor` stays
255
+ // false (enforcement `unknown`, never `chroxy`).
256
+ permissionFloor: false,
257
+ autoPermissionMode: true,
258
+ nativeSandbox: true,
161
259
  modelSwitch: true,
162
260
  permissionModeSwitch: true, // mode drives approvalPolicy + PermissionManager
163
261
  planMode: false,
164
- resume: false, // matches exec CodexSession; app-server resume is a follow-up
262
+ resume: false, // per-session projection becomes true only after verified native resume
165
263
  terminal: false,
166
- thinkingLevel: false,
264
+ // #7730 — codex has a REAL reasoning control, and this is the driver that
265
+ // can reach it: `model/list` advertises `supportedReasoningEfforts` per
266
+ // model, `thread/start` seeds one through its `config` map, and
267
+ // `turn/start` takes `effort` as a first-class per-turn field. The
268
+ // offered levels come from the ACTIVE MODEL's catalog row, never from a
269
+ // repo-wide list — see `setThinkingLevel` below and the per-model gate in
270
+ // `handlers/settings-handlers.js`.
271
+ thinkingLevel: true,
272
+ // #7725: same as the exec driver — the Claude magic keywords are not
273
+ // scanned for on any codex path. Explicit so #7730's `thinkingLevel`
274
+ // flip cannot drag the keyword highlight along with it: the composer's
275
+ // keyword highlight reads THIS flag, so flipping the one above lights the
276
+ // dropdown and nothing else.
277
+ thinkingKeywords: false,
278
+ // #8700: the level codex reports is already `thinkingLevel` itself (the
279
+ // booted effort when no override is set), so there is no separate report.
280
+ thinkingLevelEffective: false,
167
281
  streaming: true,
168
282
  // #6888: despite inProcessPermissions:true (this session's
169
283
  // respondToPermission delegates to the shared PermissionManager, which DOES
@@ -174,6 +288,13 @@ export class CodexAppServerSession extends BaseSession {
174
288
  // as an oversight: tracked by #6885 ("Codex deny reason either reaches the
175
289
  // model or is documented as unsupported"). Flip to true once that lands.
176
290
  denyReason: false,
291
+ // #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
292
+ // idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
293
+ // cleared by `interrupt()`), and reports admission through
294
+ // `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
295
+ // can travel it as an ordinary user turn. session-wake.js gates on this with
296
+ // strict `=== true`; absent means NOT supported. Never duck-typed.
297
+ daemonTurnInput: true,
177
298
  }
178
299
  }
179
300
 
@@ -184,10 +305,77 @@ export class CodexAppServerSession extends BaseSession {
184
305
  provider: opts.provider || 'codex',
185
306
  model: opts.model || null,
186
307
  }))
308
+ this._nativeResumeSaved = opts.nativeResume || null
309
+ this._nativeRestore = opts.isRestore === true || this._nativeResumeSaved !== null
310
+ this._nativeLocator = null
311
+ this._nativeResumeCapability = 'unknown'
312
+ this._nativeSettingsUnverified = false
313
+ this._nativeHostResolver = typeof opts.nativeHostResolver === 'function' ? opts.nativeHostResolver : nativeMachineId
314
+ this._nativeOwnerResolver = typeof opts.nativeOwnerResolver === 'function' ? opts.nativeOwnerResolver : () => process.getuid?.()
315
+ this._nativeResumePersist = typeof opts.nativeResumePersist === 'function' ? opts.nativeResumePersist : null
316
+ this._connectionAuthRoute = opts.connectionAuthRoute || null
317
+ this._connectionChildEnv = opts.connectionChildEnv && typeof opts.connectionChildEnv === 'object'
318
+ ? { ...opts.connectionChildEnv }
319
+ : null
187
320
  this._client = null
188
321
  this._threadId = null
322
+ // #7730 — the reasoning effort, split in two on PURPOSE.
323
+ //
324
+ // `_reasoningEffortOverride` is the operator's explicit choice (a
325
+ // `set_thinking_level`, null until one arrives) and is the ONLY value the
326
+ // param builders send: seeding `thread/start` with codex's own echoed
327
+ // effort, or replaying it on every `turn/start`, would pin the thread to a
328
+ // value codex chose for itself — the same trap `_buildTurnParams` documents
329
+ // for `model`. `_bootedReasoningEffort` is what codex reported at
330
+ // `thread/start` (from the operator's `~/.codex/config.toml`), and exists
331
+ // so the control can SHOW the session's real effort before anyone touches
332
+ // it. `get thinkingLevel` composes the two in that precedence.
333
+ this._reasoningEffortOverride = null
334
+ this._bootedReasoningEffort = null
335
+ // #7729 — injectable JSON-RPC client factory (subclass-local opt, read off
336
+ // `opts` directly; NOT a BaseSession opt). Production leaves it null and
337
+ // start() builds a real CodexAppServerClient; a test supplies a stub so
338
+ // start() can be executed rather than reproduced.
339
+ this._clientFactory = typeof opts.clientFactory === 'function' ? opts.clientFactory : null
340
+ this._binaryFailureLabeler = typeof opts.binaryFailureLabeler === 'function'
341
+ ? opts.binaryFailureLabeler
342
+ : labelBinarySpawnFailure
343
+ // #7724 — filled from the `initialize` handshake in start(). Null / all-UNKNOWN
344
+ // before the handshake AND after an unparseable userAgent: a cannot-check must
345
+ // not read as a no, so callers probe (probeMethod) instead of disabling.
346
+ this.codexUserAgent = null
347
+ this.codexVersion = null
348
+ this.codexCapabilities = capabilitiesForVersion(null)
349
+ // #8609 — a newer client bundled in a desktop app ({path, version}), found
350
+ // after the handshake; null when none / not newer. `bundledClientFinder` is a
351
+ // test seam for the app-bundle probe.
352
+ this._newerBinary = null
353
+ // #8609 — verified auth route ('native' | 'api') once the handshake has
354
+ // checked it; null when the connection pinned none. The backend's model
355
+ // rejection is route-dependent, so the rejection ledger keys on it.
356
+ this._observedAuthRoute = null
357
+ // #8609 — a start-time substitute for a rejected catalog default. Deliberately
358
+ // NOT `this.model`: that is the operator's explicit choice and is persisted.
359
+ this._defaultFallbackModel = null
360
+ this._findBundledClient = typeof opts.bundledClientFinder === 'function'
361
+ ? opts.bundledClientFinder : findNewestBundledCodexClient
189
362
  this._activeTurn = null // { messageId, turnId, didStreamStart }
363
+ // #8710 — codex turns codex has ended (`turn/completed`, or a terminal
364
+ // `error`); a notification still naming one is a straggler, not a live turn.
365
+ this._endedNativeTurnIds = new Set()
366
+ // #7769 — per-TURN, and reset in sendMessage(). It used to live for the
367
+ // lifetime of the session, so a turn that carried no
368
+ // `thread/tokenUsage/updated` re-reported the PREVIOUS turn's numbers and
369
+ // session-manager's `_trackUsage` accumulated them a second time.
190
370
  this._lastUsage = null
371
+ // #7794 — per-turn occupancy snapshot built from the same notification.
372
+ this._lastOccupancy = null
373
+ // #7773 — codex's `tokenUsage.total` is CUMULATIVE over the thread (proven
374
+ // live: see _turnUsageBreakdown). These two make the per-turn figure a
375
+ // DELTA of it: `_threadTotals` tracks the newest cumulative breakdown seen,
376
+ // `_turnBaselineTotals` freezes it at turn start.
377
+ this._threadTotals = null
378
+ this._turnBaselineTotals = null
191
379
  this._skillsPrepended = false // #6606 — inject the skills prefix once, on turn 1
192
380
  this._turnAbort = null // per-turn AbortController — cancels pending approvals
193
381
  this._reconnectWatchdog = null // #6629 — bounded backstop for a wedged reconnect
@@ -250,13 +438,109 @@ export class CodexAppServerSession extends BaseSession {
250
438
  return this._resolvedCodexSandbox || resolveCodexSandbox(this._codexSandbox)
251
439
  }
252
440
 
253
- _buildChildEnv() { return buildSpawnEnv('codex') }
441
+ _buildChildEnv() {
442
+ return this._connectionChildEnv ? { ...this._connectionChildEnv } : buildSpawnEnv('codex')
443
+ }
444
+
445
+ _buildClientArgs() {
446
+ if (!this._connectionAuthRoute) return ['app-server']
447
+ if (!['native', 'api'].includes(this._connectionAuthRoute)) {
448
+ const err = new Error('Unsupported Codex connection authentication route. Select native or API authentication.')
449
+ err.code = 'CODEX_AUTH_ROUTE_UNSUPPORTED'
450
+ throw err
451
+ }
452
+ // #7852: openai_base_url overrides Codex's auth-dependent inference URL.
453
+ // Pin the ChatGPT backend for native login and the API backend for API keys;
454
+ // using the API URL for both sends subscription tokens to the wrong service.
455
+ // Keep explicit overrides so user config cannot redirect either connection.
456
+ const inferenceBaseUrl = this._connectionAuthRoute === 'native'
457
+ ? CODEX_FIRST_PARTY_NATIVE_BASE_URL
458
+ : CODEX_FIRST_PARTY_API_BASE_URL
459
+ return [
460
+ 'app-server',
461
+ '-c', 'model_provider="openai"',
462
+ '-c', `openai_base_url="${inferenceBaseUrl}"`,
463
+ '-c', `chatgpt_base_url="${CODEX_FIRST_PARTY_CHATGPT_BASE_URL}"`,
464
+ ]
465
+ }
466
+
467
+ async _verifyConnectionAuthRoute() {
468
+ if (!this._connectionAuthRoute) return
469
+ const configResult = await this._client.request('config/read', { cwd: this.cwd, includeLayers: false })
470
+ if (configResult?.config?.model_provider !== 'openai') {
471
+ const err = new Error('Codex could not verify the built-in OpenAI provider for this explicit connection.')
472
+ err.code = 'CODEX_PROVIDER_ROUTE_UNAVAILABLE'
473
+ throw err
474
+ }
475
+ const result = await this._client.request('account/read', { refreshToken: false })
476
+ const actual = result?.account?.type === 'chatgpt'
477
+ ? 'native'
478
+ : result?.account?.type === 'apiKey'
479
+ ? 'api'
480
+ : 'none'
481
+ if (actual !== this._connectionAuthRoute) {
482
+ const err = new Error(
483
+ this._connectionAuthRoute === 'native'
484
+ ? 'Codex native login is unavailable for this connection. Run `codex login`; API credentials are not used as a fallback.'
485
+ : 'Codex API authentication is unavailable for this connection. Configure OPENAI_API_KEY; native login is not used as a fallback.'
486
+ )
487
+ err.code = this._connectionAuthRoute === 'native'
488
+ ? 'NATIVE_LOGIN_REQUIRED'
489
+ : 'API_AUTH_ROUTE_UNAVAILABLE'
490
+ throw err
491
+ }
492
+ return actual
493
+ }
494
+
495
+ _verifyStartedConnectionRoute(started, actualAuthRoute) {
496
+ if (!this._connectionAuthRoute) return
497
+ if (started?.modelProvider !== 'openai') {
498
+ const err = new Error('Codex started this thread with a model provider outside the explicit OpenAI connection route.')
499
+ err.code = 'CODEX_PROVIDER_ROUTE_MISMATCH'
500
+ throw err
501
+ }
502
+ if (!this.agentConnection) return
503
+ this.agentConnection.authentication = {
504
+ ...this.agentConnection.authentication,
505
+ observed: actualAuthRoute === 'native' ? 'native' : 'api-key',
506
+ }
507
+ this.agentConnection.entitlement = actualAuthRoute === 'api'
508
+ ? { route: 'api', status: 'available' }
509
+ : { route: 'subscription', status: 'unknown' }
510
+ this.agentConnection.readiness = {
511
+ state: 'ready',
512
+ reasonCode: null,
513
+ message: 'The selected authentication and first-party provider route was verified by Codex.',
514
+ recoveryAction: null,
515
+ }
516
+ this.agentConnection.provenance = {
517
+ ...this.agentConnection.provenance,
518
+ observedAt: new Date().toISOString(),
519
+ }
520
+ }
254
521
 
255
522
  // ------------------------------------------------------------------
256
523
  // Lifecycle
257
524
  // ------------------------------------------------------------------
258
525
 
259
526
  async start() {
527
+ try { return await this._startAppServer() }
528
+ catch (err) {
529
+ this._processReady = false
530
+ this._nativeResumeCapability = false
531
+ this._nativeLocator = null // retain original recipe if restore was rejected
532
+ try { this._client?.kill() } catch { /* already stopped */ }
533
+ if (this._nativeRestore && !String(err?.code || '').startsWith('CODEX_NATIVE_')) {
534
+ const failed = nativeRestoreError('REJECTED', 'the original native thread could not be resumed; retry it or explicitly create a new session')
535
+ failed.cause = err
536
+ throw failed
537
+ }
538
+ throw err
539
+ }
540
+ }
541
+
542
+ async _startAppServer() {
543
+ if (this._nativeRestore) validateLocator(this._nativeResumeSaved, this.permissionMode)
260
544
  // #6929 review — resolve AND STORE here, the actual `thread/start` apply
261
545
  // site, so getCodexSandbox() can report what this thread really got instead
262
546
  // of re-resolving the env (and potentially drifting from it) on every call.
@@ -265,10 +549,21 @@ export class CodexAppServerSession extends BaseSession {
265
549
  // Capture the EXACT binary the client will spawn so the spawn-time backstop
266
550
  // (#6708) verifies that path — in start()'s catch AND later in
267
551
  // _onClientExit — rather than a fresh re-resolve.
268
- const attemptedBinary = CodexAppServerSession.resolvedBinary
552
+ //
553
+ // #8038: routed through the shared binary gate instead of the bare static
554
+ // read. app-server spawns exactly once per session (at `start()`), but that
555
+ // one spawn was STILL an unverified fresh resolve — `this._spawnPreflight`
556
+ // (wired by SessionManager whenever create-time preflight ran) was already
557
+ // sitting on this instance unused. A refusal here throws BEFORE
558
+ // `_createClient`, so no child process is spawned; SessionManager's
559
+ // `_handleAsyncStartFailure` handles the rejection the same way it handles
560
+ // any other start() failure (fresh → session_create_failed with the gate's
561
+ // code; restore → parked).
562
+ const attemptedBinary = this._gatedSpawnBinary('codex')
269
563
  this._spawnedBinary = attemptedBinary
270
- this._client = new CodexAppServerClient({
564
+ this._client = this._createClient({
271
565
  bin: attemptedBinary,
566
+ args: this._buildClientArgs(),
272
567
  cwd: this.cwd,
273
568
  env: this._buildChildEnv(),
274
569
  logger: log,
@@ -277,15 +572,13 @@ export class CodexAppServerSession extends BaseSession {
277
572
  this._client.on('serverRequest', (r) => this._onServerRequest(r))
278
573
  this._client.on('exit', (e) => this._onClientExit(e))
279
574
 
280
- let started
575
+ let init
281
576
  try {
282
- await this._client.initialize({ name: 'chroxy', version: '1' })
283
- started = await this._client.request('thread/start', {
284
- approvalPolicy: this._approvalPolicy(), // #6605 P2 — derived from permission mode
285
- cwd: this.cwd,
286
- sandbox,
287
- ...(this.model ? { model: this.model } : {}),
288
- })
577
+ // #7724 — the handshake result is the ONLY in-band version signal, and it
578
+ // reports the binary serving THIS session (not whatever is on PATH). It
579
+ // gates FEATURES only: nothing below refuses to start, and an unparseable
580
+ // userAgent leaves every gate UNKNOWN so callers probe rather than assume.
581
+ init = await this._client.initialize({ name: 'chroxy', version: '1' })
289
582
  } catch (err) {
290
583
  // #6708 — the app-server child is spawned inside initialize(); a missing/
291
584
  // quarantined codex binary surfaces here as an initialize rejection (the
@@ -293,7 +586,7 @@ export class CodexAppServerSession extends BaseSession {
293
586
  // session_create_failed names the quarantine + fix rather than an opaque
294
587
  // "codex app-server exited". Only relabels when the binary is actually
295
588
  // unhealthy; otherwise the original protocol error rethrows unchanged.
296
- const labeled = labelBinarySpawnFailure({
589
+ const labeled = this._binaryFailureLabeler({
297
590
  attemptedPath: err?.path || this._spawnedBinary,
298
591
  binary: 'codex',
299
592
  prefix: 'Failed to start codex app-server',
@@ -301,40 +594,588 @@ export class CodexAppServerSession extends BaseSession {
301
594
  if (labeled) throw new Error(labeled)
302
595
  throw err
303
596
  }
597
+ this._captureHandshake(init)
598
+ this._noteNewerBundledClient()
599
+ const actualAuthRoute = await this._verifyConnectionAuthRoute()
600
+ this._observedAuthRoute = actualAuthRoute || null
601
+ if (!this._nativeRestore) this._avoidRejectedDefaultModel()
602
+ if (this._nativeRestore) this._verifyNativeOwnership(init)
603
+ const started = await this._client.request(
604
+ this._nativeRestore ? 'thread/resume' : 'thread/start',
605
+ this._nativeRestore ? this._buildResumeParams() : this._buildThreadParams(sandbox),
606
+ )
607
+ if (this._nativeRestore) this._verifyNativeResume(started, init)
608
+ if (typeof started?.thread?.id !== 'string' || !started.thread.id) throw nativeRestoreError('THREAD_INVALID', 'native thread identity was missing')
609
+ this._verifyStartedConnectionRoute(started, actualAuthRoute)
304
610
  this._threadId = started?.thread?.id || null
305
- // #6608 — do NOT set this.resumeSessionId in Phase 1: capabilities.resume is
306
- // false, and SessionManager persists resumeSessionId as the conversationId to
307
- // resume on restart. Leaving it null keeps the two consistent. The live thread
308
- // id is tracked on this._threadId (used for turn/start + interrupt). Wiring
309
- // real app-server resume (thread/resume) is a follow-up.
611
+ // #7729 — the `thread/start` RESPONSE echoes the model codex actually
612
+ // resolved (from ~/.codex/config.toml when chroxy sent none). Capture it
613
+ // BEFORE `ready` so the emitted payload — and every later session_info
614
+ // render — names a real model instead of the null this session is
615
+ // constructed with by design.
616
+ this._captureBootedModel(started)
617
+ // #7730 — and the effort it resolved, from the same response. Also BEFORE
618
+ // `ready`, so the very first `thinking_level_changed` replay names the
619
+ // operator's real `~/.codex/config.toml` setting rather than nothing.
620
+ this._captureBootedReasoningEffort(started)
621
+ if (!this._nativeRestore) this._captureNativeStart(started, init)
622
+ if (this._nativeLocator) {
623
+ this.resumeSessionId = this._threadId
624
+ if (this._nativeRestore && !this._nativeResumePersist) throw nativeRestoreError('PERSIST_UNAVAILABLE', 'durable native state writer is unavailable')
625
+ if (this._nativeResumePersist && this._nativeResumePersist() !== true) {
626
+ throw nativeRestoreError('PERSIST_FAILED', 'native identity could not be saved before readiness')
627
+ }
628
+ if (this._nativeRestore) this._nativeResumeCapability = true
629
+ }
310
630
  this._log = loggerForSession('codex-app-server', this._threadId || 'no-thread')
311
631
  this._processReady = true
312
- ;(this._log || log).info(`codex app-server ready (thread=${this._threadId} sandbox=${sandbox})`)
313
- this.emit('ready', { model: this.model })
632
+ ;(this._log || log).info(`codex app-server ready (thread=${this._threadId} sandbox=${this.getCodexSandbox()})`)
633
+ // #7726 — ask THIS binary for its own model roster, on the client that is
634
+ // already up. Fire-and-forget on purpose: a wedged or old binary must not
635
+ // delay `ready`, and every failure path inside leaves the previous catalog
636
+ // untouched. Deliberately AFTER thread/start, so a catalog probe can never
637
+ // be what breaks session creation.
638
+ this._refreshModelCatalog()
639
+ // #7729 — report the model this thread is REALLY running. `this.model` is
640
+ // the operator's explicit override and is null whenever codex was left to
641
+ // pick; `bootedModel` is what it picked. Same precedence as
642
+ // session-manager's session_info render, so the two cannot disagree.
643
+ this.emit('ready', { model: this._effectiveModelId() })
644
+ }
645
+
646
+ _buildResumeParams() { return resumeParams(this._nativeResumeSaved) }
647
+
648
+ _nativeOwnership(init) {
649
+ return bindNativeOwnership({ cwd: this.cwd, codexHome: init?.codexHome, machineId: this._nativeHostResolver(), ownerId: this._nativeOwnerResolver() })
650
+ }
651
+
652
+ _verifyNativeOwnership(init) {
653
+ const saved = this._nativeResumeSaved
654
+ if (this.codexVersion !== NATIVE_RESUME_VERSION) throw nativeRestoreError('VERSION_UNVERIFIED', 'this serving binary has not verified the saved resume contract')
655
+ const current = this._nativeOwnership(init)
656
+ for (const key of ['hostBinding', 'storeBinding', 'codexHome', 'cwdBinding', 'cwd']) {
657
+ if (current[key] !== saved[key]) throw nativeRestoreError('OWNERSHIP_MISMATCH', 'the native store, machine owner or working directory has moved')
658
+ }
659
+ const writes = writeBindings(saved.sandboxPolicy, current.cwd, this._buildChildEnv())
660
+ if (JSON.stringify(writes) !== JSON.stringify(saved.writeBindings)) throw nativeRestoreError('WRITE_OWNERSHIP_MISMATCH', 'saved writable roots or temporary directory ownership has changed')
661
+ }
662
+
663
+ _verifyNativeResume(started, init) {
664
+ this._verifyNativeOwnership(init)
665
+ const echo = validateEcho(started), saved = this._nativeResumeSaved
666
+ if (echo.thread.id !== saved.threadId) throw nativeRestoreError('THREAD_MISMATCH', 'native runtime returned a different thread identity')
667
+ const echoedOwnership = bindNativeOwnership({ cwd: echo.cwd, codexHome: init.codexHome, machineId: this._nativeHostResolver(), ownerId: this._nativeOwnerResolver() })
668
+ if (echoedOwnership.cwdBinding !== saved.cwdBinding) throw nativeRestoreError('CWD_MISMATCH', 'native runtime returned a different working directory')
669
+ if (!policyNoBroader(echo.sandbox, saved.sandboxPolicy, saved.cwd)) throw nativeRestoreError('POLICY_BROADER', 'native sandbox rights are broader or unknown')
670
+ if (echo.model !== saved.model.observed || echo.modelProvider !== saved.model.provider || echo.reasoningEffort !== saved.effort.observed) throw nativeRestoreError('SETTINGS_MISMATCH', 'native model or reasoning effort changed while restoring')
671
+ this.model = saved.model.requested
672
+ this._reasoningEffortOverride = saved.effort.requested
673
+ this._skillsPrepended = saved.skillsPrepended
674
+ this._threadTotals = saved.threadTotals ? { ...saved.threadTotals } : null
675
+ this._nativeUsageBaselineUnknown = saved.threadTotals === null
676
+ this._resolvedCodexSandbox = sandboxMode(echo.sandbox)
677
+ this._nativeLocator = {
678
+ ...structuredClone(saved), sandboxMode: sandboxMode(echo.sandbox), sandboxPolicy: structuredClone(echo.sandbox),
679
+ writeBindings: writeBindings(echo.sandbox, saved.cwd, this._buildChildEnv()), binaryVersion: this.codexVersion,
680
+ }
681
+ }
682
+
683
+ _captureNativeStart(started, init) {
684
+ try {
685
+ if (this.codexVersion !== NATIVE_RESUME_VERSION) throw nativeRestoreError('VERSION_UNVERIFIED', 'native restart continuity is not verified for this binary version')
686
+ const echo = validateEcho(started), ownership = this._nativeOwnership(init)
687
+ const actualCwd = bindNativeOwnership({ cwd: echo.cwd, codexHome: init.codexHome, machineId: this._nativeHostResolver(), ownerId: this._nativeOwnerResolver() })
688
+ if (actualCwd.cwdBinding !== ownership.cwdBinding || sandboxMode(echo.sandbox) !== this._resolvedCodexSandbox) throw nativeRestoreError('POLICY_MISMATCH', 'native cwd or sandbox differs from the requested boundary')
689
+ this._nativeLocator = {
690
+ schemaVersion: 1, provider: 'codex', driver: NATIVE_RESUME_DRIVER, binaryVersion: this.codexVersion,
691
+ threadId: echo.thread.id, ...ownership,
692
+ sandboxMode: sandboxMode(echo.sandbox), sandboxPolicy: structuredClone(echo.sandbox),
693
+ writeBindings: writeBindings(echo.sandbox, ownership.cwd, this._buildChildEnv()),
694
+ approvalPolicy: echo.approvalPolicy, approvalsReviewer: echo.approvalsReviewer, permissionMode: this.permissionMode,
695
+ model: { requested: this.model || null, observed: echo.model, provider: echo.modelProvider },
696
+ effort: { requested: this._reasoningEffortOverride, observed: echo.reasoningEffort },
697
+ skillsPrepended: false, threadTotals: null, settingsVerified: true,
698
+ }
699
+ } catch (err) {
700
+ this._nativeResumeCapability = 'unknown'
701
+ ;(this._log || log).warn(`Codex native restart continuity unavailable (${err.code || 'CODEX_NATIVE_UNVERIFIED'}): ${err.message}`)
702
+ }
703
+ }
704
+
705
+ // A successful turn admits explicit choices, but it is not a settings echo.
706
+ // Observe native metadata; an unavailable echo leaves restart visibly blocked.
707
+ async _observeNativeSettings() {
708
+ if (!this._nativeLocator || !this._nativeSettingsUnverified) return
709
+ try {
710
+ const observedCounter = this._messageCounter
711
+ const response = await this._client.request('thread/read', { threadId: this._threadId, includeTurns: false })
712
+ if (observedCounter !== this._messageCounter || this._isBusy) return
713
+ const thread = response?.thread
714
+ if (thread?.id !== this._threadId || !this._readModelId(thread.model) || !Object.hasOwn(thread, 'reasoningEffort')) return
715
+ if (!(thread.reasoningEffort === null || this._readModelId(thread.reasoningEffort))) return
716
+ this.bootedModel = thread.model
717
+ this._bootedReasoningEffort = thread.reasoningEffort
718
+ this._nativeSettingsUnverified = false
719
+ this._nativeResumePersist?.()
720
+ } catch { /* retain unverified state rather than invent a settings echo */ }
721
+ }
722
+
723
+ /**
724
+ * #7729 — the injectable client seam. Production builds a real
725
+ * `CodexAppServerClient` (which spawns `codex app-server`); a test hands in a
726
+ * stub so `start()` itself — the param builders, the handshake capture, the
727
+ * model echo — is under test instead of being REPRODUCED by a test that
728
+ * cannot go red for start()'s own bugs. Mirrors the `spawnFn` (#7726) and
729
+ * `setTimer` (#6856) injectable-seam pattern already in this file.
730
+ */
731
+ _createClient(config) {
732
+ return this._clientFactory ? this._clientFactory(config) : new CodexAppServerClient(config)
733
+ }
734
+
735
+ /**
736
+ * #7729 — the `thread/start` params. Extracted VERBATIM from the inline
737
+ * object start() used to build; the keys, their order and the conditional
738
+ * `model` spread are unchanged. Extraction is what gives the effort param
739
+ * (#7730) and the resume branch (CDX-9) one place to land, and what lets a
740
+ * test assert the shape without re-typing it.
741
+ *
742
+ * @param {string} sandbox the RESOLVED sandbox mode (see start()).
743
+ */
744
+ _buildThreadParams(sandbox) {
745
+ return {
746
+ approvalPolicy: this._approvalPolicy(), // #6605 P2 — derived from permission mode
747
+ cwd: this.cwd,
748
+ sandbox,
749
+ ...((this.model || this._defaultFallbackModel) ? { model: this.model || this._defaultFallbackModel } : {}),
750
+ // #7730 — effort is seeded ASYMMETRICALLY, and this half is the one that
751
+ // is easy to get wrong. `thread/start` has NO top-level effort field:
752
+ // the value goes through the generic `config` map as
753
+ // `model_reasoning_effort`, exactly as `~/.codex/config.toml` spells it
754
+ // (verified live on codex-cli 0.154.0 — passing
755
+ // `{config: {model_reasoning_effort: 'xhigh'}}` made the response echo
756
+ // `reasoningEffort: 'xhigh'`). A top-level `effort` key here is silently
757
+ // IGNORED, which is why the omission has to be deliberate rather than
758
+ // symmetrical with `_buildTurnParams` below.
759
+ //
760
+ // Omitted entirely when the operator has chosen nothing, so codex
761
+ // resolves its own default from the config file and the echo tells us
762
+ // what it picked.
763
+ ...(this._reasoningEffortOverride ? { config: { model_reasoning_effort: this._reasoningEffortOverride } } : {}),
764
+ }
765
+ }
766
+
767
+ /**
768
+ * #7729 — the `turn/start` params, extracted verbatim from sendMessage()'s
769
+ * inline object (same keys, same order, same conditional spread).
770
+ *
771
+ * #6608 — the CURRENT model rides every turn (turn/start accepts it) so a
772
+ * mid-session set_model actually takes effect, matching the exec path's
773
+ * per-turn model. thread/start seeds the initial model; this tracks changes.
774
+ * Deliberately `this.model`, NOT `_effectiveModelId()`: echoing codex's own
775
+ * resolved model back at it on every turn would pin a thread that codex
776
+ * re-routed (`model/rerouted`) to the model it moved AWAY from.
777
+ *
778
+ * @param {Array<Object>} input the codex UserInput items (see _buildTurnInput).
779
+ */
780
+ _buildTurnParams(input) {
781
+ return {
782
+ threadId: this._threadId,
783
+ approvalPolicy: this._approvalPolicy(), // #6605 P2 — per-turn, tracks mode changes
784
+ input,
785
+ ...(this.model ? { model: this.model } : {}),
786
+ // #7730 — the OTHER half of the asymmetry: on `turn/start`, `effort` IS a
787
+ // first-class param ("this turn and subsequent turns"). It rides EVERY
788
+ // turn, not just the one after a `set_thinking_level`, for the same
789
+ // reason `model` does (#6608): a mid-session change must take effect, and
790
+ // a thread that was seeded at start must not silently drift back to the
791
+ // binary's default on some later turn. `turn/settings/update` (change the
792
+ // effort on a RUNNING turn) exists only at codex >= 0.154.0 and is
793
+ // deliberately not used — "the next turn carries the new effort" needs no
794
+ // version gate, and a capability probe here would buy a one-turn latency
795
+ // difference at the price of a gate that can be wrong.
796
+ ...(this._reasoningEffortOverride ? { effort: this._reasoningEffortOverride } : {}),
797
+ }
798
+ }
799
+
800
+ /**
801
+ * #7729 — the model id this session should be DESCRIBED by: the operator's
802
+ * explicit override when there is one, else the model codex resolved at
803
+ * `thread/start` (or re-routed to mid-turn), else null. Never a fabricated
804
+ * default — a session whose binary told us nothing still reports null, and
805
+ * the badge stays blank rather than lying.
806
+ */
807
+ _effectiveModelId() {
808
+ return this.model || this.bootedModel || null
809
+ }
810
+
811
+ /**
812
+ * #7729 — record the model codex resolved, from the `thread/start` response.
813
+ *
814
+ * BOTH reads are observed live. The UNTRIMMED codex-cli 0.154.0 capture
815
+ * (https://github.com/blamechris/chroxy/issues/7721#issuecomment-5646200933)
816
+ * carries the resolved model at the TOP LEVEL **and** on a nested `thread`
817
+ * object — `thread.model` / `thread.reasoningEffort` mirror the top-level
818
+ * `model` / `reasoningEffort` — and `thread` is in the generated
819
+ * `ThreadStartResponse.required` alongside `model`. An earlier revision of
820
+ * this docblock read the TRIMMED echo quoted in the #7721 body (only
821
+ * `{model, reasoningEffort, modelProvider, sandbox, approvalPolicy}`) and
822
+ * wrongly declared the nested object unobserved: cite the untrimmed capture,
823
+ * never the trimmed excerpt.
824
+ *
825
+ * The ordering below is deliberate and unchanged — the TOP LEVEL wins, and
826
+ * the nested read is the one `??` that still answers for a build carrying
827
+ * only the mirrored copy. That same nested object is also the SOLE source of
828
+ * `this._threadId` (`started?.thread?.id`, in `start()` above), which every
829
+ * `turn/start` and `interrupt` depends on: observed live AND schema-required,
830
+ * so it is neither speculative nor deletable defensive cruft.
831
+ *
832
+ * A response carrying NEITHER is a cannot-read, not a "codex cleared the
833
+ * model": it leaves `bootedModel` at whatever it already was — `null` for a
834
+ * brand-new session, or a value `SessionManager.createSession()` pre-seeded
835
+ * from the persisted restore snapshot before calling `start()` — and never
836
+ * blanks a known id (#7770; mirrors `_onModelRerouted`'s identical rule for
837
+ * the same field — named, deliberately, WITHOUT a line offset: the "twelve
838
+ * lines below" this docblock first carried was copied from #7770's body,
839
+ * which quoted a pre-#7729 layout, and was ~87 lines wrong on arrival. A
840
+ * method name survives a refactor; an offset does not). A session with no
841
+ * prior value stays
842
+ * `null`, never `undefined` — the badge, the usage split and the
843
+ * context-window lookup all distinguish "codex did not say" from a model
844
+ * id, and an `undefined` here would serialize away entirely rather than
845
+ * reading as a cannot-check.
846
+ *
847
+ * The three log branches split on PROVENANCE, not on the resulting
848
+ * truthiness. A carried-over value is not an echo, and saying "thread/start
849
+ * echo" over one points an operator who changed `~/.codex/config.toml` at
850
+ * codex's config resolution instead of at chroxy's restore snapshot — so the
851
+ * cannot-read still warns (naming what it kept, `_onModelRerouted`'s shape)
852
+ * rather than disappearing behind the success line.
853
+ */
854
+ _captureBootedModel(started) {
855
+ const echoed = this._readModelId(started?.model) ?? this._readModelId(started?.thread?.model)
856
+ const carried = echoed ? null : this.bootedModel || null
857
+ this.bootedModel = echoed ?? this.bootedModel ?? null
858
+ if (echoed && this.agentConnection) {
859
+ this.agentConnection.model = { ...this.agentConnection.model, resolved: echoed }
860
+ }
861
+ if (echoed) {
862
+ ;(this._log || log).info(`codex resolved model=${echoed} (native thread echo)`)
863
+ } else if (carried) {
864
+ ;(this._log || log).warn(`codex native thread carried no model echo; keeping ${carried} (restored before start)`)
865
+ } else {
866
+ ;(this._log || log).warn('codex native thread carried no model echo; the session model stays unknown rather than guessed')
867
+ }
868
+ return this.bootedModel
869
+ }
870
+
871
+ /**
872
+ * #7729 — a non-empty string model id, or null. Kept as one helper so the
873
+ * echo, the reroute and any later resume branch cannot disagree about what
874
+ * counts as "codex named a model".
875
+ */
876
+ _readModelId(value) {
877
+ return typeof value === 'string' && value.length > 0 ? value : null
878
+ }
879
+
880
+ _onModelChanged(model) {
881
+ if (this.agentConnection) {
882
+ this.agentConnection.model = {
883
+ ...this.agentConnection.model,
884
+ requested: model,
885
+ resolved: null,
886
+ }
887
+ }
888
+ ;(this._log || log).info(`codex requested model set to ${model ?? 'default'}; resolved model is unknown until the runtime reports it`)
889
+ }
890
+
891
+ /**
892
+ * #7730 — the reasoning effort this session is running at: the operator's
893
+ * explicit choice, else the effort codex reported at `thread/start`, else
894
+ * null.
895
+ *
896
+ * Overriding this getter is not cosmetic. `BaseSession.thinkingLevel` returns
897
+ * `undefined`, and `ws-history.js` skips the `thinking_level_changed` replay
898
+ * on exactly that value — so without this override the control would reset to
899
+ * whatever the client last had in memory on every reconnect and tab switch,
900
+ * which for a codex session means a level the session never entered.
901
+ *
902
+ * Null (never `undefined`) when codex named none and nobody chose one:
903
+ * "unknown" has to stay readable as itself rather than collapsing into the
904
+ * "this provider has no thinking level" case the base class expresses.
905
+ */
906
+ get thinkingLevel() {
907
+ return this._reasoningEffortOverride || this._bootedReasoningEffort || null
908
+ }
909
+
910
+ /**
911
+ * #7730 — record the operator's chosen reasoning effort.
912
+ *
913
+ * Deliberately does NOT validate the level against a roster. The
914
+ * authoritative membership check is `handlers/settings-handlers.js`, which is
915
+ * the only layer that can see the ACTIVE MODEL's catalog row (`reasoningLevels`
916
+ * from `model/list`); duplicating it here would be a second roster to drift,
917
+ * and a per-model question answered in a place that does not know the model
918
+ * can only be answered with a repo-wide literal — which is the whole defect
919
+ * #7730 removes.
920
+ *
921
+ * The effort is not pushed to codex here: it rides the NEXT `turn/start`
922
+ * (see `_buildTurnParams`). There is no separate "set the effort" RPC that
923
+ * works on an idle thread, and `turn/settings/update` only applies to a turn
924
+ * already running.
925
+ *
926
+ * #7786 — `null` CLEARS the override: `thinkingLevel` then shows codex's own
927
+ * `thread/start` echo again and `turn/start` carries no `effort`, so codex
928
+ * re-resolves its default from `~/.codex/config.toml`. A client reaches this
929
+ * with `set_thinking_level { level: null }`; the handler passes that null
930
+ * through without a roster check (a clear names no level). An empty string
931
+ * also clears, as defence in depth — the wire schema and the handler both
932
+ * refuse it before it gets here.
933
+ */
934
+ setThinkingLevel(level) {
935
+ const next = typeof level === 'string' && level.length > 0 ? level : null
936
+ this._reasoningEffortOverride = next
937
+ ;(this._log || log).info(`codex reasoning effort set to ${next ?? 'unset'} (rides the next turn/start)`)
938
+ return true
939
+ }
940
+
941
+ /**
942
+ * #7730 — record the effort codex resolved at `thread/start`.
943
+ *
944
+ * Same two reads as `_captureBootedModel`, for the same reason: the untrimmed
945
+ * codex-cli 0.154.0 capture
946
+ * (https://github.com/blamechris/chroxy/issues/7721#issuecomment-5646200933)
947
+ * carries `reasoningEffort` at the TOP LEVEL and mirrored on the nested
948
+ * `thread` object, and `ReasoningEffort` is typed there as a free non-empty
949
+ * STRING — so no value is validated against a list on the way in.
950
+ *
951
+ * This feeds the DISPLAY only (`get thinkingLevel`), never the param
952
+ * builders: it is codex's own answer, and echoing it back at codex on the
953
+ * next turn would pin a value the binary is free to resolve for itself. An
954
+ * absent echo leaves it null — the control then shows nothing rather than
955
+ * claiming the session is at a level nobody established.
956
+ */
957
+ _captureBootedReasoningEffort(started) {
958
+ const nonEmpty = (v) => (typeof v === 'string' && v.length > 0 ? v : null)
959
+ const echoed = nonEmpty(started?.reasoningEffort) ?? nonEmpty(started?.thread?.reasoningEffort)
960
+ this._bootedReasoningEffort = echoed ?? null
961
+ if (this._bootedReasoningEffort) {
962
+ ;(this._log || log).info(`codex resolved reasoning effort=${this._bootedReasoningEffort} (native thread echo)`)
963
+ }
964
+ return this._bootedReasoningEffort
965
+ }
966
+
967
+ /**
968
+ * #7729 — codex re-routed this thread to a different model server-side
969
+ * (`model/rerouted` = `{threadId, turnId, fromModel, toModel, reason}`).
970
+ * Track `toModel` so the badge follows the reroute instead of naming a model
971
+ * the thread stopped running. A notification with no usable `toModel` is a
972
+ * cannot-read and leaves the previous value ALONE — it must not blank a
973
+ * model id we already know.
974
+ */
975
+ _onModelRerouted(params) {
976
+ const to = this._readModelId(params?.toModel)
977
+ if (!to) {
978
+ ;(this._log || log).warn(`codex model/rerouted carried no toModel (${JSON.stringify(params ?? null).slice(0, 200)}); keeping ${this.bootedModel ?? 'unknown'}`)
979
+ return false
980
+ }
981
+ const from = this._readModelId(params?.fromModel) || this.bootedModel || 'unknown'
982
+ this.bootedModel = to
983
+ if (this.agentConnection) {
984
+ this.agentConnection.model = { ...this.agentConnection.model, resolved: to }
985
+ }
986
+ ;(this._log || log).info(`codex re-routed this thread ${from} → ${to}${params?.reason ? ` (${params.reason})` : ''}`)
987
+ return true
988
+ }
989
+
990
+ /**
991
+ * #7726 — refresh the codex model catalog from this live session's client.
992
+ *
993
+ * Capability-gated the #7724 way: a binary KNOWN not to serve `model/list`
994
+ * (a parsed version below the floor) is not asked, while UNKNOWN — an absent
995
+ * or unparseable userAgent — still probes, because a cannot-check must not
996
+ * read as a no. Any error from the call itself degrades identically
997
+ * (`probeMethod`), whatever JSON-RPC code it carries.
998
+ *
999
+ * #7762 — this live refresh claims the shared `'codex'` discovery slot
1000
+ * (model-discovery.js), so `scheduleProviderModelsRefresh`'s later scheduled
1001
+ * call sees an unchanged change key / hits the TTL and pushes nothing —
1002
+ * this call is the ONLY place a change made here can reach a connected
1003
+ * client. On a non-empty resolved roster, emit `models_updated` exactly the
1004
+ * `ollama-session.js` / `anthropic-compatible-session.js` shape:
1005
+ * session-manager forwards it as a provider-tagged `available_models`
1006
+ * broadcast. A `null`/empty resolution (no change, TTL-cached, or a failed
1007
+ * probe) emits nothing — pushing an empty roster would blank a picker that
1008
+ * already has one.
1009
+ *
1010
+ * The emit runs AFTER the probe's `.catch()`, with its own try/catch:
1011
+ * `EventEmitter.emit` rethrows a synchronous listener throw, and inside the
1012
+ * guarded chain that throw would be logged as `codex model catalog refresh
1013
+ * failed` and flip the resolved value to `null` — attributing a downstream
1014
+ * forwarding bug to the codex probe, which both succeeded and wrote the
1015
+ * registry. Ordering the two stages so each reports its own failure is the
1016
+ * point; do not collapse them back into one `.then().catch()`.
1017
+ *
1018
+ * @returns {Promise<Array<Object>|null>} always resolves; never throws.
1019
+ */
1020
+ _refreshModelCatalog() {
1021
+ if (!this._client) return Promise.resolve(null)
1022
+ if (this.codexCapabilities?.supportsModelList === false) {
1023
+ ;(this._log || log).debug('codex model catalog skipped: this binary is below the model/list floor')
1024
+ return Promise.resolve(null)
1025
+ }
1026
+ return Promise.resolve()
1027
+ .then(() => CodexAppServerSession.refreshModels({ client: this._client }))
1028
+ .catch((err) => {
1029
+ ;(this._log || log).debug(`codex model catalog refresh failed: ${err?.message || err}`)
1030
+ return null
1031
+ })
1032
+ .then((models) => {
1033
+ if (Array.isArray(models) && models.length > 0) {
1034
+ try {
1035
+ this.emit('models_updated', { models })
1036
+ } catch (err) {
1037
+ ;(this._log || log).debug(`codex models_updated listener threw: ${err?.message || err}`)
1038
+ }
1039
+ }
1040
+ return models
1041
+ })
1042
+ }
1043
+
1044
+ /**
1045
+ * #7724 — record what the `initialize` handshake said about the binary serving
1046
+ * this session. Feature-gating ONLY: this never throws and never refuses a
1047
+ * session, so a binary below the protocol floor (or one whose userAgent we
1048
+ * cannot parse) still starts a thread and still sends turns.
1049
+ */
1050
+ _captureHandshake(init) {
1051
+ const { version, raw } = parseCodexUserAgent(init?.userAgent)
1052
+ this.codexUserAgent = raw
1053
+ this.codexVersion = version
1054
+ this.codexCapabilities = capabilitiesForVersion(version)
1055
+ if (version) {
1056
+ ;(this._log || log).info(`codex app-server handshake (version=${version} userAgent=${String(raw).slice(0, 200)})`)
1057
+ } else {
1058
+ // Not a warning about the binary — a note that the CHEAP gate is
1059
+ // unavailable and load-bearing features must be probed at runtime.
1060
+ ;(this._log || log).warn(`codex app-server handshake carried no parseable version (userAgent=${raw === null ? 'absent' : String(raw).slice(0, 200)}); capabilities fall through to runtime probes`)
1061
+ }
1062
+ }
1063
+
1064
+ /** #8609 — the launched client's identity for the model-rejection ledger. */
1065
+ _clientKey() {
1066
+ return codexClientKey(this._spawnedBinary, this.codexVersion, this._observedAuthRoute || this._connectionAuthRoute)
1067
+ }
1068
+
1069
+ /**
1070
+ * #8609 — after the handshake, note (warn once, expose in runtime info) a
1071
+ * client bundled in a desktop app that is newer than the one we launched.
1072
+ * Advisory only: never switches binaries and never throws.
1073
+ */
1074
+ _noteNewerBundledClient() {
1075
+ try {
1076
+ const have = parseSemver(this.codexVersion)
1077
+ const bundled = this._findBundledClient()
1078
+ if (!have || !bundled || bundled.path === this._spawnedBinary) return
1079
+ const want = parseSemver(bundled.version)
1080
+ if (!want || compareSemver(want, have) <= 0) return
1081
+ this._newerBinary = { path: bundled.path, version: bundled.version }
1082
+ ;(this._log || log).warn(`a newer codex client is installed: ${bundled.version} (${bundled.path}); this session launched ${this.codexVersion} (${this._spawnedBinary}) — set CHROXY_CODEX_BIN to use it`)
1083
+ } catch (err) {
1084
+ ;(this._log || log).debug(`bundled codex client probe failed: ${err?.message || err}`)
1085
+ }
1086
+ }
1087
+
1088
+ /** #8609 — the first codex-roster model this client has not had rejected. */
1089
+ _suggestFallbackModel(rejected) {
1090
+ let roster = []
1091
+ try { roster = CodexAppServerSession.getFallbackModels().map((m) => m.id) } catch { /* no roster */ }
1092
+ return suggestFallbackModel(roster, this._clientKey(), rejected ? [rejected] : [])
1093
+ }
1094
+
1095
+ /**
1096
+ * #8609 — an earlier session on THIS client (same path and version) had its
1097
+ * default model rejected by the backend. With no explicit model, start the
1098
+ * thread on the fallback instead of walking into the same refusal.
1099
+ */
1100
+ _avoidRejectedDefaultModel() {
1101
+ if (this.model) return
1102
+ const rejected = rejectedDefaultFor(this._clientKey())
1103
+ if (!rejected) return
1104
+ const fallback = this._suggestFallbackModel(rejected)
1105
+ if (!fallback) return
1106
+ this._defaultFallbackModel = fallback
1107
+ ;(this._log || log).info(`codex model '${rejected}' was rejected for this client earlier; starting on '${fallback}' instead`)
1108
+ }
1109
+
1110
+ /**
1111
+ * #8609 — the backend refused the model: say so legibly (model, client,
1112
+ * alternative, newer client) and remember it for this client.
1113
+ */
1114
+ _modelUnsupportedPayload(rejection) {
1115
+ const ran = this._effectiveModelId()
1116
+ // Blame the client (and remember it) ONLY when the rejection text quoted a
1117
+ // model id AND that is the model this turn ran. An unquoted match ("the
1118
+ // requested model is not supported for this endpoint") says nothing about
1119
+ // the client's default, and recording it would blacklist a working model.
1120
+ const evidence = rejection.model !== null && rejection.model === ran
1121
+ const model = rejection.model || ran
1122
+ if (evidence) recordModelRejection(this._clientKey(), model, { wasDefault: !this.model })
1123
+ const version = this.codexVersion || 'unknown version'
1124
+ const path = this._spawnedBinary || 'codex'
1125
+ const parts = [evidence || rejection.model
1126
+ ? `Codex rejected model '${model}': it is not supported by the codex client this session launched (${version}, ${path}).`
1127
+ : `Codex reported that a model is not supported (session model: ${ran ? `'${ran}'` : 'unknown'}; codex client ${version}, ${path}).`]
1128
+ const fallback = this._suggestFallbackModel(model)
1129
+ if (fallback) parts.push(`Try '${fallback}'.`)
1130
+ if (this._newerBinary) {
1131
+ parts.push(`A newer codex client is installed: ${this._newerBinary.version} (${this._newerBinary.path}) — set CHROXY_CODEX_BIN to use it.`)
1132
+ }
1133
+ return { message: parts.join(' '), code: MODEL_UNSUPPORTED_CODE }
1134
+ }
1135
+
1136
+ /**
1137
+ * #8301: `sendMessage` on a session whose app-server is not up emits a
1138
+ * user-visible "not started" error. A daemon wake must not cause one.
1139
+ * @returns {string|null}
1140
+ */
1141
+ daemonTurnRefusal() {
1142
+ return (!this._processReady || !this._client) ? 'not-started' : null
1143
+ }
1144
+
1145
+ /**
1146
+ * #8281: `_activeTurn` is set when the turn is dispatched, before codex has
1147
+ * answered with a turn id (`turnId` is null until `turn/start` returns). That
1148
+ * window is still a turn in flight for a handoff.
1149
+ * @returns {boolean}
1150
+ */
1151
+ _hasTurnInFlight() {
1152
+ return !!this._activeTurn || super._hasTurnInFlight()
314
1153
  }
315
1154
 
316
1155
  async sendMessage(prompt, attachments, sendOptions = {}) {
317
1156
  if (this._isBusy) {
318
- this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
1157
+ const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
1158
+ reportInputAdmission(sendOptions, queued
1159
+ ? { status: 'queued', delivery: 'queued' }
1160
+ : {
1161
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1162
+ reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
1163
+ })
319
1164
  return
320
1165
  }
321
1166
  if (!this._processReady || !this._client) {
322
1167
  this.emit('error', { message: 'Codex app-server session is not started' })
1168
+ reportInputAdmission(sendOptions, {
1169
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1170
+ reason: 'not_runnable', message: 'The provider session is not started.',
1171
+ })
323
1172
  return
324
1173
  }
325
- this._isBusy = true
326
- this._messageCounter += 1
327
- const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
328
- this._currentMessageId = messageId
329
- this._activeTurn = { messageId, turnId: null, didStreamStart: false }
330
- // Fresh abort scope for this turn's approvals — interrupt()/destroy() abort it
331
- // so a pending permission_request resolves (deny) instead of hanging the turn.
332
- this._turnAbort = new AbortController()
333
- this._armResultTimeout()
1174
+ const messageId = this._openTurn()
334
1175
 
335
1176
  // #6606 review — mirror the exec path: prepend the combined skills prefix on
336
- // the FIRST turn so runtime skills reach codex. The flag flips only AFTER
337
- // turn/start succeeds, so a failed first turn still retries with the skills.
1177
+ // the FIRST turn so runtime skills reach codex. An acknowledgement or a
1178
+ // completed turn proves admission; a refused first turn retries the skills.
338
1179
  let text = prompt || ''
339
1180
  if (!this._skillsPrepended) {
340
1181
  const combined = typeof this._buildCombinedSkillsPrefix === 'function' ? this._buildCombinedSkillsPrefix() : ''
@@ -347,24 +1188,65 @@ export class CodexAppServerSession extends BaseSession {
347
1188
  const input = this._buildTurnInput(text, attachments, messageId)
348
1189
 
349
1190
  ;(this._log || log).info(`codex app-server turn start (msg=${messageId} thread=${this._threadId} inputItems=${input.length})`)
1191
+ const dispatchedTurn = this._activeTurn
1192
+ const turnParams = this._buildTurnParams(input)
1193
+ const previouslyUnverified = this._nativeSettingsUnverified
1194
+ // Freeze the choices actually sent, before notifications can complete this
1195
+ // turn or setters select a different choice for the next one.
1196
+ this._nativeSettingsUnverified = previouslyUnverified || !!((turnParams.model && turnParams.model !== this.bootedModel) || (turnParams.effort && turnParams.effort !== this._bootedReasoningEffort))
350
1197
  try {
351
- const res = await this._client.request('turn/start', {
352
- threadId: this._threadId,
353
- approvalPolicy: this._approvalPolicy(), // #6605 P2 — per-turn, tracks mode changes
354
- input,
355
- // #6608 — pass the CURRENT model per turn (turn/start accepts it) so a
356
- // mid-session set_model actually takes effect, matching the exec path's
357
- // per-turn model. thread/start seeds the initial model; this tracks changes.
358
- ...(this.model ? { model: this.model } : {}),
359
- })
1198
+ const res = await this._client.request('turn/start', turnParams)
360
1199
  this._skillsPrepended = true
361
- if (this._activeTurn && !this._activeTurn.turnId) this._activeTurn.turnId = res?.turn?.id || null
1200
+ reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
1201
+ if (this._activeTurn === dispatchedTurn && !dispatchedTurn.turnId) dispatchedTurn.turnId = res?.turn?.id || null
362
1202
  } catch (err) {
363
- // turn/start itself failed (dead server, bad thread) — fail this turn.
364
- this._failTurn(`Codex turn failed to start: ${err.message}`)
1203
+ const refused = typeof err?.jsonRpcCode === 'number'
1204
+ if (refused && this._activeTurn === dispatchedTurn) this._nativeSettingsUnverified = previouslyUnverified
1205
+ const admission = refused ? {
1206
+ status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
1207
+ reason: 'turn_start_failed', message: 'The provider rejected the turn before it started.',
1208
+ } : {
1209
+ status: 'uncertain', delivery: 'unknown', retrySafe: false,
1210
+ reason: 'turn_start_uncertain', message: 'The native turn acknowledgement was lost; it may have started. Check the original session before explicitly resending.',
1211
+ }
1212
+ reportInputAdmission(sendOptions, admission)
1213
+ // Only an explicit native refusal proves this turn did not start.
1214
+ // A transport loss must keep its uncertainty visible to every caller.
1215
+ this._failTurn(
1216
+ refused ? `Codex turn failed to start: ${err.message}` : admission.message,
1217
+ refused ? {} : { code: admission.reason },
1218
+ )
365
1219
  }
366
1220
  }
367
1221
 
1222
+ // Turn-start bookkeeping, shared by a turn the daemon sends and one codex is
1223
+ // running that the daemon was not tracking (#8710). Returns the messageId.
1224
+ _openTurn(turnId = null) {
1225
+ this._isBusy = true
1226
+ this._permissions.clearUserStopInFlight() // #8430: a new turn starts with no user Stop in flight
1227
+ this._messageCounter += 1
1228
+ const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
1229
+ this._currentMessageId = messageId
1230
+ this._activeTurn = { messageId, turnId, didStreamStart: false }
1231
+ // #7769 — clear the PREVIOUS turn's usage here, not at turn end. A
1232
+ // `turn/completed` that arrives with no intervening
1233
+ // `thread/tokenUsage/updated` must report `usage: null` ("codex told us
1234
+ // nothing"), never the last turn's numbers: `session-manager._trackUsage`
1235
+ // ADDS `result.usage` into `cumulativeUsage` once per turn, so re-reporting
1236
+ // is a silent double count of user-visible tokens and cost.
1237
+ // #7773 — and freeze the cumulative baseline this turn's delta is measured
1238
+ // from, in the same place, so the two can never disagree about where a turn
1239
+ // starts.
1240
+ this._lastUsage = null
1241
+ this._lastOccupancy = null
1242
+ this._turnBaselineTotals = this._threadTotals
1243
+ // Fresh abort scope for this turn's approvals — interrupt()/destroy() abort it
1244
+ // so a pending permission_request resolves (deny) instead of hanging the turn.
1245
+ this._turnAbort = new AbortController()
1246
+ this._armResultTimeout()
1247
+ return messageId
1248
+ }
1249
+
368
1250
  // #6609 — build the codex `turn/start` input array from the prompt + Chroxy
369
1251
  // attachments. codex's UserInput union natively takes file paths, so:
370
1252
  // - binary image/document → materialized to a temp file (reused helper)
@@ -385,13 +1267,32 @@ export class CodexAppServerSession extends BaseSession {
385
1267
  // + warn on an absolute or parent-traversing path.
386
1268
  const fileRefs = attachments.filter((a) => {
387
1269
  if (!a || a.type !== 'file_ref' || typeof a.path !== 'string') return false
388
- if (a.path.startsWith('/') || a.path.split(/[/\\]/).includes('..')) {
1270
+ // #7273 — `startsWith('/')` missed every Windows absolute spelling
1271
+ // (`C:\\x`, `\\\\host\\share\\x`, `\\\\?\\C:\\x`). The `..` half already split on
1272
+ // both separators; the absolute half now tests both namespaces to match.
1273
+ if (posixPath.isAbsolute(a.path) || win32Path.isAbsolute(a.path) || a.path.split(/[/\\]/).includes('..')) {
389
1274
  ;(this._log || log).warn(`codex attachment: skipping non-relative file_ref path "${a.path}"`)
390
1275
  return false
391
1276
  }
392
1277
  return true
393
1278
  })
394
- if (binary.length && !this._attachDir) this._attachDir = mkdtempSync(join(tmpdir(), 'chroxy-codex-attach-'))
1279
+ // #7373 — the attach dir lives inside a dedicated, `owner.pid`-stamped
1280
+ // per-session dir under ATTACH_BASE rather than a bare mkdtemp under
1281
+ // os.tmpdir(), so a crash leaves the boot-time sweep able to tell a
1282
+ // dead session's leftover attachment files from a live one's and
1283
+ // remove only the dead one (same shape as ClaudeTuiSession's sink
1284
+ // dirs and CliSession's permission-mode sidecar).
1285
+ if (binary.length && !this._attachDir) {
1286
+ const base = ensureOwnedBaseDir(CodexAppServerSession.ATTACH_BASE)
1287
+ const dir = join(base, `s-${randomUUID()}`)
1288
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
1289
+ // Stamp the owning pid so the boot-time sweep can tell a live
1290
+ // daemon's dir from one orphaned by a crash. Best-effort: a
1291
+ // missing pidfile just makes the dir sweep-eligible after a grace
1292
+ // window — the safe default for an orphan.
1293
+ try { writeFileSync(join(dir, OWNER_PID_FILE), String(process.pid)) } catch { /* best effort */ }
1294
+ this._attachDir = dir
1295
+ }
395
1296
  const materialized = binary.length ? materializeAttachments(binary, this._attachDir, messageId) : []
396
1297
  const refFiles = fileRefs.map((a) => ({ path: a.path, name: a.name || basename(a.path), mediaType: '', size: 0 }))
397
1298
  const all = [...materialized, ...refFiles]
@@ -427,11 +1328,66 @@ export class CodexAppServerSession extends BaseSession {
427
1328
  // ------------------------------------------------------------------
428
1329
 
429
1330
  _onNotification({ method, params }) {
430
- if (!this._activeTurn) {
431
- // Between turns: only usage/errors matter; ignore stray item churn.
432
- if (method === 'thread/tokenUsage/updated') this._lastUsage = this._mapUsage(params)
1331
+ // #8710 — a torn-down session maps nothing. The client is killed, but stdout
1332
+ // already read can still be dispatched, and with destroy()'s listeners gone
1333
+ // an `error` emitted here would throw out of the stream handler.
1334
+ if (this._destroying) return
1335
+ // #7724 — `deprecationNotice` is handled HERE, ahead of the between-turns
1336
+ // handling, NOT as a case in the switch below. It is a lifecycle notice
1337
+ // the binary can emit at any point — most plausibly right after the
1338
+ // handshake, when there is no active turn — and the switch is unreachable in
1339
+ // exactly that window. A case down there would be a handler that cannot fire
1340
+ // for its own main case.
1341
+ //
1342
+ // This early return DELIBERATELY bypasses `_resetResultTimeout()` and the
1343
+ // #6629/#6856 reconnect-backstop disarm below. Before this change a mid-turn
1344
+ // deprecationNotice reached `default: break` AFTER both, so it counted as
1345
+ // forward progress on the liveness path. It is not: the notice is emitted on
1346
+ // the binary's own schedule and says nothing about whether codex is still
1347
+ // streaming this turn, so treating it as a heartbeat would slide the result
1348
+ // timeout and the reconnect watchdog out on a payload that carries no
1349
+ // evidence of progress. A turn that has genuinely stalled must still time out.
1350
+ if (method === 'deprecationNotice') {
1351
+ this._onDeprecationNotice(params)
1352
+ return
1353
+ }
1354
+ // #8743 — a notification about a thread or a turn is codex doing something,
1355
+ // so the idle-only auto-deploy must not restart the daemon under it. That
1356
+ // includes the ones dropped below without an event: a sub-agent's thread, a
1357
+ // straggler from a turn codex already ended, anything for a turn the daemon
1358
+ // is not tracking. The emit() override only sees the ones that become events.
1359
+ // One that names neither (account rate limits, MCP or skills status) is
1360
+ // about the environment, may arrive on the binary's own schedule, and must
1361
+ // not hold a deploy off.
1362
+ if (this._notificationTurnId(params) || (typeof params?.threadId === 'string' && params.threadId !== '')) {
1363
+ this.noteProviderActivity()
1364
+ }
1365
+ if (this._isOtherThread(params)) {
1366
+ // #8710 — a sub-agent's thread. Its activity is evidence this turn's work
1367
+ // is still running (the parent is often blocked waiting on it), so it holds
1368
+ // off the result timeout — unless a pending permission has paused that
1369
+ // timer. Nothing else: it is not this thread's stream, so it neither
1370
+ // disarms the reconnect backstops below nor maps onto this turn's events.
1371
+ if (this._activeTurn && this._resultTimeout) this._armResultTimeout()
1372
+ return
1373
+ }
1374
+ const turnId = this._notificationTurnId(params)
1375
+ const sessionHandler = SESSION_SCOPED_HANDLERS.get(method)
1376
+ if (turnId && !sessionHandler && this._endedNativeTurnIds.has(turnId)) {
1377
+ // #8710 — codex already ended this turn: a straggler (a background exec
1378
+ // reporting after its turn, or the `turn/completed` that follows a terminal
1379
+ // `error`), not a live turn, and never the turn that is open now.
1380
+ ;(this._log || log).debug(`codex app-server ${method} for ended turn ${turnId} — ignored`)
433
1381
  return
434
1382
  }
1383
+ if (!this._activeTurn) {
1384
+ // #7729 — a reroute and a usage update both describe the SESSION, not the
1385
+ // turn, so they are consumed here.
1386
+ if (sessionHandler) { sessionHandler(this, params); return }
1387
+ // #8710 — anything else is about a turn the daemon is not tracking. An
1388
+ // error is surfaced, and codex still reporting work opens a turn for it.
1389
+ if (!this._onUntrackedTurnNotification(method, params, turnId)) return
1390
+ }
435
1391
  this._resetResultTimeout()
436
1392
  // #6629/#6856 — any notification that is NOT another `error` tick is genuine
437
1393
  // forward progress: codex's response stream is live again, so disarm BOTH the
@@ -440,6 +1396,7 @@ export class CodexAppServerSession extends BaseSession {
440
1396
  // `error` clears both below on its way to _failTurn; a transient reconnect
441
1397
  // `error` re-arms the watchdog but leaves the deadline untouched.)
442
1398
  if (method !== 'error') { this._clearReconnectWatchdog(); this._clearReconnectDeadline() }
1399
+ if (sessionHandler) { sessionHandler(this, params); return }
443
1400
  const t = this._activeTurn
444
1401
  switch (method) {
445
1402
  case 'turn/started':
@@ -458,11 +1415,8 @@ export class CodexAppServerSession extends BaseSession {
458
1415
  case 'item/completed':
459
1416
  this._onItemCompleted(params?.item)
460
1417
  break
461
- case 'thread/tokenUsage/updated':
462
- this._lastUsage = this._mapUsage(params)
463
- break
464
1418
  case 'turn/completed':
465
- this._finishTurn(params?.turn)
1419
+ this._finishTurn(params?.turn, turnId)
466
1420
  break
467
1421
  case 'error': {
468
1422
  // #6623 — codex emits transient `error` notifications WHILE its OWN retry
@@ -475,9 +1429,10 @@ export class CodexAppServerSession extends BaseSession {
475
1429
  // notification — the result timeout (re-armed by _resetResultTimeout above)
476
1430
  // is the backstop if codex never recovers, and codex's terminal give-up
477
1431
  // (a disconnect WITHOUT a reconnecting message) still falls through to fail.
1432
+ // #8754 — codex says whether it retries (`willRetry`); see _codexWillRetry.
478
1433
  const err = this._errorPayload(params)
479
- if (this._isTransientReconnect(err)) {
480
- ;(this._log || log).warn(`codex app-server response stream reconnecting (turn kept open): ${err.message || 'responseStreamDisconnected'}`)
1434
+ if (this._codexWillRetry(params, err)) {
1435
+ ;(this._log || log).warn(`codex app-server retrying (turn kept open): ${err.message || 'stream error'}`)
481
1436
  // #6629 — arm the bounded watchdog so a reconnect that NEVER recovers
482
1437
  // (nor emits codex's terminal give-up) still reconciles the stale
483
1438
  // working state, even when a pending permission has paused the result
@@ -494,7 +1449,11 @@ export class CodexAppServerSession extends BaseSession {
494
1449
  }
495
1450
  this._clearReconnectWatchdog() // terminal error → about to fail; drop the backstops
496
1451
  this._clearReconnectDeadline() // #6856
497
- this._failTurn(`Codex error: ${JSON.stringify(params).slice(0, 200)}`)
1452
+ // #8710 — codex has ended this turn: its `turn/completed` follows.
1453
+ this._noteNativeTurnEnded(turnId ?? t.turnId)
1454
+ const { message, code } = this._terminalErrorPayload(err, params)
1455
+ this._logRawTerminalError(params)
1456
+ this._failTurn(message, { code })
498
1457
  break
499
1458
  }
500
1459
  default:
@@ -502,6 +1461,147 @@ export class CodexAppServerSession extends BaseSession {
502
1461
  }
503
1462
  }
504
1463
 
1464
+ /**
1465
+ * #8710 — every thread-scoped notification names its thread in `threadId`
1466
+ * (required in the v2 schema, codex-cli 0.163.0), and the app-server relays a
1467
+ * sub-agent's thread on its parent's connection. Trial run B2b ended its turn
1468
+ * on a worker's `turn/completed` 11 minutes into a turn codex ran for two
1469
+ * hours. An absent id is read as this thread, as every notification without
1470
+ * one always has been.
1471
+ */
1472
+ _isOtherThread(params) {
1473
+ const id = params?.threadId
1474
+ return typeof id === 'string' && id !== '' && this._threadId != null && id !== this._threadId
1475
+ }
1476
+
1477
+ // #8710 — the codex turn a notification is about: `turnId` on item, error and
1478
+ // usage notifications, `turn.id` on turn/started and turn/completed.
1479
+ _notificationTurnId(params) {
1480
+ const id = params?.turnId ?? params?.turn?.id
1481
+ return typeof id === 'string' && id !== '' ? id : null
1482
+ }
1483
+
1484
+ // #8710 — remember a turn codex itself ended, so a straggler for it is not
1485
+ // taken for a live turn. Bounded: only recent turns still have any in flight.
1486
+ _noteNativeTurnEnded(turnId) {
1487
+ if (typeof turnId !== 'string' || turnId === '') return
1488
+ this._endedNativeTurnIds.delete(turnId)
1489
+ this._endedNativeTurnIds.add(turnId)
1490
+ if (this._endedNativeTurnIds.size > MAX_ENDED_NATIVE_TURN_IDS) {
1491
+ this._endedNativeTurnIds.delete(this._endedNativeTurnIds.values().next().value)
1492
+ }
1493
+ }
1494
+
1495
+ /**
1496
+ * #8710 — a notification for this thread arrived with no daemon turn open.
1497
+ * It is about a turn the daemon is not tracking: one it gave up on itself (the
1498
+ * result timeout, the reconnect backstops, a lost `turn/start`
1499
+ * acknowledgement) or one codex runs without being asked. Before #8710 all of
1500
+ * it was discarded, which is how trial run B2b's last 1 h 50 min of work and
1501
+ * the usage-limit stop that ended it never reached a client.
1502
+ *
1503
+ * Returns true when it opened a turn, which the caller then maps as usual.
1504
+ */
1505
+ _onUntrackedTurnNotification(method, params, turnId) {
1506
+ const tlog = this._log || log
1507
+ if (method === 'error') {
1508
+ const err = this._errorPayload(params)
1509
+ // `willRetry` (required in 0.163.0) marks codex's own retry of a turn it is
1510
+ // still running: not an end, and that turn's later notifications are live.
1511
+ // #8754: the same rule as an active turn (_codexWillRetry), so an explicit
1512
+ // `willRetry: false` is an end here too.
1513
+ if (this._codexWillRetry(params, err)) {
1514
+ tlog.debug(`codex app-server retrying with no turn open: ${err.message || 'stream error'}`)
1515
+ return false
1516
+ }
1517
+ this._noteNativeTurnEnded(turnId)
1518
+ const payload = this._terminalErrorPayload(err, params)
1519
+ this._logRawTerminalError(params)
1520
+ tlog.warn(`codex app-server error with no turn open (turn=${turnId}): ${payload.message}`)
1521
+ this.emit('error', payload)
1522
+ return false
1523
+ }
1524
+ if (method === 'turn/completed') {
1525
+ this._noteNativeTurnEnded(turnId)
1526
+ const turn = params?.turn
1527
+ if (turn?.status === 'failed') {
1528
+ const payload = this._terminalErrorPayload(turn.error, turn.error)
1529
+ this._logRawTerminalError(turn.error)
1530
+ tlog.warn(`codex app-server turn ${turnId} failed with no turn open: ${payload.message}`)
1531
+ this.emit('error', payload)
1532
+ } else {
1533
+ tlog.info(`codex app-server turn ${turnId} ended (${turn?.status || 'completed'}) with no turn open`)
1534
+ }
1535
+ return false
1536
+ }
1537
+ // Only a turn/started, or a notification naming its turn, says a turn is live.
1538
+ if (method !== 'turn/started' && !turnId) {
1539
+ tlog.debug(`codex app-server ${method} with no turn open — ignored`)
1540
+ return false
1541
+ }
1542
+ this._openTurn(turnId)
1543
+ tlog.warn(`codex app-server ${method} for turn ${turnId} with no turn open — following codex's turn`)
1544
+ // stream_start is what tells clients the session is busy again.
1545
+ this._ensureStreamStart()
1546
+ return true
1547
+ }
1548
+
1549
+ /**
1550
+ * #8710 — what a turn-ending codex error tells the client. A usage limit
1551
+ * carries codex's own sentence (it names when the limit resets) and the
1552
+ * `usage_limit` code claude-tui sessions use for the same stop (#8400); a
1553
+ * failed turn that names no error says only that it failed.
1554
+ * `usageLimitExceeded` is the v2 `CodexErrorInfo` spelling (codex-cli 0.163.0
1555
+ * `generate-json-schema`).
1556
+ *
1557
+ * #8610 — any other error shows its readable message, decoding nested
1558
+ * JSON-encoded errors within fixed bounds (codex-error-text.js), with HTTP
1559
+ * status and error type as secondary detail. When nothing readable is found it
1560
+ * says so; the raw payload is never shown. The usage-limit and model-rejection
1561
+ * branches above keep their precedence, and nothing here changes whether the
1562
+ * turn ends.
1563
+ */
1564
+ _terminalErrorPayload(err, raw) {
1565
+ if (err?.codexErrorInfo === 'usageLimitExceeded' && typeof err.message === 'string' && err.message) {
1566
+ return { message: err.message, code: USAGE_LIMIT_CODE }
1567
+ }
1568
+ const rejection = detectModelRejection(err, raw)
1569
+ if (rejection) return this._modelUnsupportedPayload(rejection)
1570
+ if (raw == null) return { message: 'Codex turn failed' }
1571
+ const readable = describeCodexError(err ?? raw)
1572
+ return { message: readable ? formatCodexError(readable) : UNREADABLE_CODEX_ERROR }
1573
+ }
1574
+
1575
+ /**
1576
+ * #8610 — the chat card shows only the readable message, so the full raw payload
1577
+ * goes to the server log: one line, redacted, cut at a fixed length (codex-error-text.js).
1578
+ */
1579
+ _logRawTerminalError(raw) {
1580
+ ;(this._log || log).warn(`codex app-server terminal error payload: ${rawCodexErrorForLog(raw)}`)
1581
+ }
1582
+
1583
+ /**
1584
+ * #7724 — surface the app-server's own deprecation notice. Logged, not
1585
+ * emitted: it is operator-facing information about the codex binary, not a
1586
+ * turn event, and the switch's default arm used to swallow it entirely.
1587
+ *
1588
+ * The params shape is `{ summary: string (required), details: string|null }`,
1589
+ * verified against the live codex-cli 0.154.0 binary with
1590
+ * `codex app-server generate-json-schema --out <dir>` →
1591
+ * `ServerNotification.json` → `definitions.DeprecationNoticeNotification`.
1592
+ * There is no `message` field. The JSON.stringify fallback is kept for a
1593
+ * payload that carries neither field (a fork, or a future rename), so a
1594
+ * notice is never swallowed — but it is the FALLBACK, not the main path.
1595
+ */
1596
+ _onDeprecationNotice(params) {
1597
+ const summary = typeof params?.summary === 'string' && params.summary ? params.summary : null
1598
+ const details = typeof params?.details === 'string' && params.details ? params.details : null
1599
+ let detail
1600
+ if (summary) detail = details ? `${summary} — ${details}` : summary
1601
+ else detail = JSON.stringify(params ?? null)
1602
+ ;(this._log || log).warn(`codex app-server deprecation notice: ${String(detail).slice(0, 500)}`)
1603
+ }
1604
+
505
1605
  _onItemStarted(item) {
506
1606
  if (!item) return
507
1607
  // commandExecution / fileChange / mcpToolCall map to Chroxy tools. The
@@ -575,6 +1675,7 @@ export class CodexAppServerSession extends BaseSession {
575
1675
  this.emit('tool_result', { toolUseId: item.id, result, truncated, isError })
576
1676
  this._trackToolResult(item.id)
577
1677
  } else if (item.type === 'agentMessage') {
1678
+ this.emit('assistant_response', { responseId: item.id, text: assistantResponseText(item.text) })
578
1679
  // Fallback: if the final text never arrived as deltas (short replies can
579
1680
  // skip the delta stream), emit it once so the message isn't lost.
580
1681
  if (!this._activeTurn.didStreamStart && item.text) {
@@ -633,8 +1734,221 @@ export class CodexAppServerSession extends BaseSession {
633
1734
  this.emit('stream_start', { messageId: this._activeTurn.messageId })
634
1735
  }
635
1736
 
1737
+ /**
1738
+ * #7729 — the one consumer of `thread/tokenUsage/updated`. It carries THREE
1739
+ * independent facts and they are handled separately:
1740
+ *
1741
+ * - the token breakdown, mapped onto chroxy's accounting keys — a DELTA of
1742
+ * the cumulative `total` since turn start (#7773);
1743
+ * - the context-window OCCUPANCY snapshot the meter reads (#7794);
1744
+ * - `tokenUsage.modelContextWindow`, which is the model's REAL window as
1745
+ * reported by the binary running it — authoritative, and the only source
1746
+ * that exists: `model/list` does not carry a window at all.
1747
+ *
1748
+ * #7773 — `_threadTotals` is advanced LAST, and deliberately after
1749
+ * `_mapUsage` has read it: the delta is always measured from the baseline
1750
+ * frozen at turn start, never from the previous notification, so N
1751
+ * notifications in one turn each report that turn's running sum rather than
1752
+ * one response's slice.
1753
+ */
1754
+ _onTokenUsage(params) {
1755
+ this._lastUsage = this._mapUsage(params)
1756
+ this._lastOccupancy = this._buildOccupancy(params)
1757
+ this._applyContextWindow(params)
1758
+ const total = params?.tokenUsage?.total
1759
+ if (total && typeof total === 'object') this._threadTotals = total
1760
+ }
1761
+
1762
+ /**
1763
+ * #7794 — the context-window OCCUPANCY snapshot (wire field
1764
+ * `contextOccupancy`, NOT the billing `usage` aggregate beside it) built from
1765
+ * codex's own numbers, so a codex session's context meter renders instead of
1766
+ * staying dashed forever.
1767
+ *
1768
+ * **The series is `tokenUsage.last`, NOT `tokenUsage.total`** — #7794's body
1769
+ * specifies `total.total_tokens` and that is WRONG, falsified by a live
1770
+ * two-turn probe against codex-cli 0.154.0 (gpt-5.5, thread
1771
+ * 01a09778-0c52-7c41-8d24-e4f4ff68b708):
1772
+ *
1773
+ * turn 1: total.totalTokens=14962 last.totalTokens=14962
1774
+ * turn 2: total.totalTokens=31920 last.totalTokens=16958 (14962+16958)
1775
+ *
1776
+ * `total` is the thread-CUMULATIVE sum of every response's usage. Metered as
1777
+ * occupancy it grows without bound, reads 100% of a 258400 window after ~15
1778
+ * turns of a real session, and can never step down after a compaction — the
1779
+ * exact failure #7794's own second acceptance criterion forbids. `last` is
1780
+ * the most recent response: `inputTokens` is the conversation as codex last
1781
+ * sent it and `totalTokens` is that prompt plus the reply
1782
+ * (14935+27=14962, 16937+21=16958), i.e. the size the NEXT turn starts from.
1783
+ * That follows a compaction down, which is the #6769 semantics.
1784
+ *
1785
+ * No `source` field: the protocol enum has values for the SDK control API and
1786
+ * byok's final-round estimate, and this is neither. Absent parses to
1787
+ * `source: null` client-side, which renders the value un-flagged rather than
1788
+ * labelled an estimate — correct, since these are the binary's own figures.
1789
+ *
1790
+ * Returns null (field omitted, clients keep their previous snapshot / dash)
1791
+ * for the flat legacy shape, a missing/malformed `last`, or a zero total —
1792
+ * never a fabricated number (#5444).
1793
+ */
1794
+ _buildOccupancy(params) {
1795
+ const last = params?.tokenUsage?.last
1796
+ if (!last || typeof last !== 'object') return null
1797
+ const totalTokens = nonNegInt(last.totalTokens)
1798
+ if (totalTokens <= 0) return null
1799
+ const win = params?.tokenUsage?.modelContextWindow
1800
+ return {
1801
+ totalTokens,
1802
+ // Omitted rather than null when codex reported no window: the client's
1803
+ // ceiling resolution then falls back to the registry window, which the
1804
+ // ratchet may still have. `maxTokens: null` would mean the same thing to
1805
+ // `contextMeterCeiling`, but omitting keeps "codex said nothing" and
1806
+ // "codex said null" from being spelled differently on the wire.
1807
+ ...(Number.isFinite(win) && win > 0 ? { maxTokens: win } : {}),
1808
+ }
1809
+ }
1810
+
1811
+ /**
1812
+ * #7729 — write codex's own `modelContextWindow` to the codex registry as
1813
+ * authoritative, falling back to the observed-tokens ratchet when the binary
1814
+ * did not report one.
1815
+ *
1816
+ * Three properties are deliberate:
1817
+ *
1818
+ * - **No `models_updated` emit from either path.** The reason is #7729's
1819
+ * AC, which rules the global broadcast out — NOT per-turn cost. The cost
1820
+ * argument would in fact be wrong: `if (!changed) return false` below
1821
+ * sits ahead of where any emit would go, so an emit would fire at most
1822
+ * once per model per WINDOW CHANGE, not on every token update. What it
1823
+ * would still be is a GLOBAL broadcast (`ws-forwarding.js` →
1824
+ * `available_models` to EVERY client) originated by one session's turn,
1825
+ * and that shape is what the AC forbids. #7728 fixed the client-side
1826
+ * slot, so such a broadcast is harmless — harmless is not the same as
1827
+ * wanted. The registry write persists via `saveCache()` and reaches
1828
+ * clients on the next roster refresh; closing that last hop with a
1829
+ * SESSION-scoped push is #7774.
1830
+ * - **A missing/unusable window is a cannot-check, not a zero.** 0,
1831
+ * negative, NaN and null all leave the registry entry exactly as it was
1832
+ * and fall through to the ratchet — they never write, and they never
1833
+ * substitute a default. A brand-new session that has not completed a turn
1834
+ * therefore has NO window and its meter stays dashed; fabricating one
1835
+ * would be worse than none (#5444).
1836
+ * - **`Number.isFinite` guards the call.** `registry.updateContextWindow`
1837
+ * tests `typeof === 'number' && > 0`, which NaN passes (`NaN <= 0` is
1838
+ * false) — it would then write NaN, since `x !== NaN` is always true.
1839
+ *
1840
+ * @returns {boolean} true when the registry entry changed.
1841
+ */
1842
+ _applyContextWindow(params) {
1843
+ const modelId = this._effectiveModelId()
1844
+ // Unknown model → nothing to key the window on. The ratchet is equally
1845
+ // inert here (it no-ops on an id the registry does not carry), so this is
1846
+ // an early return, not a behaviour difference.
1847
+ if (!modelId) return false
1848
+
1849
+ const reported = params?.tokenUsage?.modelContextWindow
1850
+ if (!Number.isFinite(reported) || reported <= 0) {
1851
+ // Codex did not report a window on this update — fall back to the shared
1852
+ // learn-loop, which can only ratchet UP off an observed prompt size.
1853
+ // Deliberately no emit callback: see above.
1854
+ //
1855
+ // The ratchet is fed the WHOLE prompt (codex's `inputTokens`, of which
1856
+ // `cachedInputTokens` is a subset), NOT `_lastUsage.input_tokens` — that
1857
+ // is the DISJOINT uncached half _mapUsage emits for accounting, and a
1858
+ // cache-heavy turn still occupies the full prompt in the context window.
1859
+ // codex-session.js:760 warns against conflating exactly these two.
1860
+ const u = this._usageBreakdown(params)
1861
+ const promptTokens = nonNegInt(u.inputTokens ?? u.input_tokens)
1862
+ if (promptTokens <= 0) return false
1863
+ return maybeRatchetContextWindow('codex', modelId, promptTokens)
1864
+ }
1865
+
1866
+ const registry = getRegistryForProvider('codex')
1867
+ if (!registry || typeof registry.updateContextWindow !== 'function') return false
1868
+ const changed = registry.updateContextWindow(modelId, reported)
1869
+ if (!changed) return false
1870
+ // #4413 — persist so a restart keeps the authoritative window. Idempotent
1871
+ // and warn-on-failure, like the ratchet's own save.
1872
+ if (typeof registry.saveCache === 'function') registry.saveCache()
1873
+ ;(this._log || log).info(`codex reported context window ${reported} for ${modelId} (authoritative)`)
1874
+ return true
1875
+ }
1876
+
1877
+ /**
1878
+ * #7729 — the LAST RESPONSE's token breakdown inside a
1879
+ * `thread/tokenUsage/updated` payload, for every shape this session has to
1880
+ * read.
1881
+ *
1882
+ * The LIVE shape is `{threadId, turnId, tokenUsage: {total, last,
1883
+ * modelContextWindow}}` (verified against codex-cli 0.154.0), so the
1884
+ * pre-existing `params.usage` read found nothing there and every token count
1885
+ * mapped to zero. `params.usage` keeps its precedence for any caller/build
1886
+ * still using the flat shape.
1887
+ *
1888
+ * #7773 — the docstring here USED to call this "the per-turn token
1889
+ * breakdown", which is more than `last` delivers: `last` is one model
1890
+ * RESPONSE, and a coding turn with N tool round-trips emits N notifications.
1891
+ * The per-turn figure is `_turnUsageBreakdown` below. This one keeps
1892
+ * one-response semantics on purpose, because the context-window RATCHET in
1893
+ * `_applyContextWindow` wants a single response's prompt size — summing a
1894
+ * turn's responses there would ratchet the learned window far above the real
1895
+ * one.
1896
+ */
1897
+ _usageBreakdown(params) {
1898
+ return params?.usage || params?.tokenUsage?.last || params || {}
1899
+ }
1900
+
1901
+ /**
1902
+ * #7773 — THIS TURN's token breakdown: `tokenUsage.total` minus the
1903
+ * cumulative baseline frozen at turn start.
1904
+ *
1905
+ * `total` is CUMULATIVE over the thread. Proven live on codex-cli 0.154.0
1906
+ * (two turns, one thread — full capture in `_buildOccupancy`): turn 2
1907
+ * reported `total.totalTokens = 31920` for `last.totalTokens = 16958`,
1908
+ * exactly turn 1's 14962 plus turn 2's 16958. So neither raw field is the
1909
+ * turn:
1910
+ *
1911
+ * - `total` compounds — session-manager's `_trackUsage` ADDS `result.usage`
1912
+ * into `cumulativeUsage` once per turn, so reporting a running total
1913
+ * re-counts the whole thread every turn (the #7767 rationale, correct);
1914
+ * - `last` DROPS — every response but the final one of the turn is thrown
1915
+ * away, a systematic undercount concentrated on exactly the tool-heavy
1916
+ * turns that dominate a coding session (#7773).
1917
+ *
1918
+ * The delta does neither, and it is what every other chroxy provider reports
1919
+ * (an Anthropic turn sums all of its requests).
1920
+ *
1921
+ * Measured from the TURN BASELINE rather than the previous notification, so
1922
+ * the value is the turn's running sum on each of N notifications and the
1923
+ * final one — the only one `_finishTurn` reports — is the whole turn.
1924
+ *
1925
+ * Every field is clamped at 0 by `nonNegInt`, so a `total` that moved
1926
+ * BACKWARDS (a resumed thread, or a future build that resets its counters
1927
+ * after compacting) undercounts rather than emitting a negative into an
1928
+ * accumulator.
1929
+ *
1930
+ * Falls through to `_usageBreakdown` when there is no `total` to difference:
1931
+ * the flat `params.usage` shape, and any build that stops sending `total`.
1932
+ */
1933
+ _turnUsageBreakdown(params) {
1934
+ if (params?.usage) return params.usage
1935
+ const total = params?.tokenUsage?.total
1936
+ if (!total || typeof total !== 'object') return this._usageBreakdown(params)
1937
+ const base = this._turnBaselineTotals
1938
+ if (!base || typeof base !== 'object') return this._nativeUsageBaselineUnknown ? this._usageBreakdown(params) : total
1939
+ const delta = (key) => nonNegInt(nonNegInt(total[key]) - nonNegInt(base[key]))
1940
+ return {
1941
+ totalTokens: delta('totalTokens'),
1942
+ inputTokens: delta('inputTokens'),
1943
+ cachedInputTokens: delta('cachedInputTokens'),
1944
+ cacheWriteInputTokens: delta('cacheWriteInputTokens'),
1945
+ outputTokens: delta('outputTokens'),
1946
+ reasoningOutputTokens: delta('reasoningOutputTokens'),
1947
+ }
1948
+ }
1949
+
636
1950
  _mapUsage(params) {
637
- const u = params?.usage || params || {}
1951
+ const u = this._turnUsageBreakdown(params)
638
1952
  const rawInput = nonNegInt(u.inputTokens ?? u.input_tokens)
639
1953
  const cached = nonNegInt(u.cachedInputTokens ?? u.cached_input_tokens)
640
1954
  return {
@@ -654,23 +1968,75 @@ export class CodexAppServerSession extends BaseSession {
654
1968
  // Deprecated duplicate of cache_read_input_tokens — kept one release
655
1969
  // for any external reader of the raw result payload (#6692).
656
1970
  cached_input_tokens: cached,
1971
+ // #7773 — `TokenUsageBreakdown` has six fields and this maps three;
1972
+ // the other two are UNREAD ON PURPOSE, and a test pins each.
1973
+ //
1974
+ // - `reasoningOutputTokens` is a SUBSET of `outputTokens`, proven by
1975
+ // the live capture's own arithmetic: totalTokens 14962 =
1976
+ // inputTokens 14935 + outputTokens 27, while reasoningOutputTokens
1977
+ // was 20. Were it additive, totalTokens would have been 14982. So
1978
+ // `output_tokens` above already contains it and adding it anywhere
1979
+ // would double count. Surfacing it SEPARATELY for display is
1980
+ // #7730/#6942, not an accounting key.
1981
+ // - `cacheWriteInputTokens` maps to NOTHING, so
1982
+ // `cache_creation_input_tokens` stays absent (and `_trackUsage`
1983
+ // accumulates 0) for every codex session. Read 0 in every capture so
1984
+ // far, which means its relationship to `inputTokens` is UNPROVEN —
1985
+ // and under the OpenAI convention the rest of this function is built
1986
+ // on it is plausibly another subset, where an additive map would
1987
+ // double count real tokens. Absent is the fail-safe reading: it
1988
+ // under-reports a cost line rather than inflating one. Map it the day
1989
+ // a capture shows it non-zero AND shows whether totalTokens counts it
1990
+ // twice.
657
1991
  }
658
1992
  }
659
1993
 
660
- _finishTurn(turn) {
1994
+ // #7072 / #9241: a turn the operator stopped arrives HERE. `interrupt()` sends
1995
+ // `turn/interrupt`, and codex documents the answer as `turn/completed` with
1996
+ // `status: 'interrupted'` (app-server docs, "Interrupt a turn"), not an `error`
1997
+ // notification. It is reported as a `stopped` result (BaseSession marks it
1998
+ // `interrupted`, so an orchestration TurnDriver no longer settles it as a success),
1999
+ // and the requested-Stop handling there applies: no chip, the quiet `stopped`, and
2000
+ // the stop-before-reply marker when nothing had been produced. CAVEAT: this shape is
2001
+ // documented by OpenAI but NOT pinned by a live probe in this repo's tests (#6606's C1
2002
+ // test only models turn/completed-after-interrupt); a binary that answers differently
2003
+ // gets the old behaviour, a normal result.
2004
+ _finishTurn(turn, turnId = null) {
661
2005
  if (!this._activeTurn) return
662
2006
  const t = this._activeTurn
2007
+ // #8710 — codex ended this turn: a straggler naming it is never taken for a
2008
+ // live turn, or for the next one.
2009
+ this._noteNativeTurnEnded(turnId ?? t.turnId)
2010
+ // Completion can precede the RPC acknowledgement. Persist first-turn skills
2011
+ // admission before result listeners save the now-completed native session.
2012
+ this._skillsPrepended = true
663
2013
  this._clearResultTimeout()
664
- if (t.didStreamStart) this.emit('stream_end', { messageId: t.messageId })
2014
+ if (t.didStreamStart) this.emit('stream_end', { messageId: t.messageId, ...(turn?.status && turn.status !== 'completed' ? { interrupted: true } : {}) })
665
2015
  this._emitResult(
666
2016
  {
667
2017
  cost: null,
668
2018
  duration: turn?.durationMs ?? null,
2019
+ declarationEligible: turn?.status === 'completed' && !turn?.error,
669
2020
  usage: this._lastUsage,
670
2021
  // #6692: single-model split (codex runs one model per session; cost
671
2022
  // is unknown at the source — pricing happens downstream).
672
- modelUsage: synthesizeModelUsage(this.model, this._lastUsage),
2023
+ // #7729: key on the EFFECTIVE model. `this.model` is null whenever the
2024
+ // operator left codex to pick, and synthesizeModelUsage returns null
2025
+ // for a null id — so before the thread/start echo was captured, every
2026
+ // default codex session's per-model usage split was silently dropped.
2027
+ modelUsage: synthesizeModelUsage(this._effectiveModelId(), this._lastUsage),
673
2028
  sessionId: this._threadId,
2029
+ // #9241: codex answers `turn/interrupt` with `turn/completed {status:'interrupted'}`
2030
+ // (TurnStatus), not an error. That is a cancelled turn, which BaseSession then treats
2031
+ // like every other provider's Stop (no chip for a requested one, the marker when
2032
+ // nothing had been produced).
2033
+ ...(turn?.status === 'interrupted' ? { turnOutcome: 'stopped', stopRequested: true } : {}),
2034
+ // #7794 — occupancy snapshot, or the field omitted entirely when codex
2035
+ // sent no usable one (clients then keep their previous snapshot / the
2036
+ // honest dash). Wire name is contextOccupancy, NOT contextUsage: the
2037
+ // `usage` field above is the billing aggregate and must never be
2038
+ // metered against the window (#6769).
2039
+ ...(this._lastOccupancy ? { contextOccupancy: this._lastOccupancy } : {}),
674
2040
  },
675
2041
  'turn_ended_with_orphan_tool_start',
676
2042
  )
@@ -682,6 +2048,18 @@ export class CodexAppServerSession extends BaseSession {
682
2048
  // would mis-report a LATER genuine error as a clean `stopped` (#4881 race).
683
2049
  this._clearIntentionalStop()
684
2050
  this._clearMessageState()
2051
+ // #8710 — codex reports a turn its error ended (a usage limit, among others)
2052
+ // as `failed`, with the error beside it. The result above keeps the turn's
2053
+ // usage accounted; this says the work did not finish. Normally the `error`
2054
+ // notification ahead of it has already failed the turn, and this
2055
+ // `turn/completed` never gets here.
2056
+ if (turn?.status === 'failed') {
2057
+ const payload = this._terminalErrorPayload(turn.error, turn.error)
2058
+ this._logRawTerminalError(turn.error)
2059
+ ;(this._log || log).warn(`codex app-server turn failed: ${payload.message}`)
2060
+ this.emit('error', payload)
2061
+ }
2062
+ this._observeNativeSettings()
685
2063
  this._maybeDequeue()
686
2064
  }
687
2065
 
@@ -724,10 +2102,33 @@ export class CodexAppServerSession extends BaseSession {
724
2102
  return /reconnect/i.test(typeof err?.message === 'string' ? err.message : '')
725
2103
  }
726
2104
 
2105
+ // #8754 — is this `error` notification codex retrying on its own (the turn goes on)
2106
+ // or a turn-ending error? Since codex-cli 0.163.0 the app-server says so:
2107
+ // `ErrorNotification.willRetry` is required, `true` for an EventMsg::StreamError that
2108
+ // codex retries itself and `false` for a turn-ending EventMsg::Error. When the field
2109
+ // is PRESENT it decides, both ways: only `true` keeps the turn open, even when the
2110
+ // message does not look like a reconnect (e.g. responseStreamConnectionFailed), and
2111
+ // anything else ends it, even when the message does. That includes a malformed value
2112
+ // (`null`, `'true'`, `1`): a codex that sends the field has stopped promising the
2113
+ // #6623 shape, so its message is no evidence of a retry, and ending the turn is the
2114
+ // conservative reading. Only a payload WITHOUT the field (an older codex) falls back
2115
+ // to the #6623 heuristic above. Keeping the turn open never removes the hard bounds:
2116
+ // the #6629 watchdog and the #6856 one-shot deadline are armed exactly as for a
2117
+ // #6623 reconnect.
2118
+ _codexWillRetry(params, err) {
2119
+ if (params && typeof params === 'object' && Object.hasOwn(params, 'willRetry')) {
2120
+ return params.willRetry === true
2121
+ }
2122
+ return this._isTransientReconnect(err)
2123
+ }
2124
+
727
2125
  // #6638: also release cached fileChange diffs when per-turn state is cleared
728
2126
  // (turn end / fail / destroy), so a diff can't outlive its turn.
729
- _clearMessageState() {
730
- super._clearMessageState()
2127
+ // #7340: forward the opts to super. `turnEndedCleanly` decides whether a
2128
+ // confirmed-backgrounded subagent survives BaseSession's turn-end sweep;
2129
+ // an override that drops it silently disables the exemption.
2130
+ _clearMessageState(opts) {
2131
+ super._clearMessageState(opts)
731
2132
  this._pendingFileChanges.clear()
732
2133
  this._clearReconnectWatchdog() // #6629 — drop the reconnect backstop on any turn teardown
733
2134
  this._clearReconnectDeadline() // #6856 — drop the suppression deadline on any turn teardown
@@ -1074,21 +2475,27 @@ export class CodexAppServerSession extends BaseSession {
1074
2475
  : `Codex connector "${server}": is requesting your input${url}`
1075
2476
  }
1076
2477
 
1077
- // 'auto' (skip all prompts) → codex runs without asking. Every other mode →
1078
- // 'on-request': codex asks per action and the PermissionManager applies the
1079
- // mode/rules (auto-allow for acceptEdits/rules, prompt for 'approve').
2478
+ // #8619: `on-request` in EVERY mode, Auto included. codex's own `never`
2479
+ // policy would emit no approval RPC, which is exactly the seam Chroxy's
2480
+ // protected-path / secret-read floor needs (#7825) — so Auto never maps to
2481
+ // it. Under Auto the PermissionManager's auto-mode path answers each request
2482
+ // without a prompt unless the floor reserves it for a human, which is the
2483
+ // same floor coverage Approve and Accept Edits have. What no mode covers is
2484
+ // an action the native sandbox already authorizes: codex runs those without
2485
+ // any RPC, in Auto as in Approve.
1080
2486
  _approvalPolicy() {
1081
- return this.permissionMode === 'auto' ? 'never' : 'on-request'
2487
+ return 'on-request'
1082
2488
  }
1083
2489
 
1084
2490
  // In-process permission responses (capabilities.inProcessPermissions) — thin
1085
2491
  // delegators to the PermissionManager, mirroring SdkSession.
1086
- respondToPermission(requestId, decision, editedInput, reason) {
1087
- return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
2492
+ respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy) {
2493
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope, resolvedBy)
1088
2494
  }
1089
2495
 
1090
- respondToQuestion(text, answers) {
1091
- return this._permissions.respondToQuestion(text, answers)
2496
+ respondToQuestion(text, answers, toolUseId) {
2497
+ // #8460: same shared manager, same id check as SDK/BYOK.
2498
+ return this._permissions.respondToQuestion(text, answers, toolUseId)
1092
2499
  }
1093
2500
 
1094
2501
  // #6829 — permission-rule accessors, mirroring SdkSession/ByokSession. Codex's
@@ -1164,6 +2571,7 @@ export class CodexAppServerSession extends BaseSession {
1164
2571
  async interrupt() {
1165
2572
  this.clearOutgoingQueue()
1166
2573
  this.markIntentionalStop()
2574
+ this._noteTurnStopRequested() // #9241: so a `turn/completed{interrupted}` takes the Stop path
1167
2575
  // Stop must not wait on a prompt: abort this turn's approval scope so a
1168
2576
  // pending permission_request resolves (deny → decline) immediately, instead
1169
2577
  // of leaving the turn wedged until the 5-min timeout (#6611 review).
@@ -1174,14 +2582,42 @@ export class CodexAppServerSession extends BaseSession {
1174
2582
  }
1175
2583
  }
1176
2584
 
1177
- // Panic-button parity with SdkSession (#3729): switching TO auto drains any
1178
- // already-emitted approval prompts (they resolve as allow → we answer codex
1179
- // accept), so the user isn't left staring at a prompt after choosing "approve
1180
- // everything". approvalPolicy for the NEXT turn is derived from the new mode.
2585
+ // #3729 panic button: a switch to Auto drains the prompts already pending
2586
+ // as allow. `autoAllowPending` leaves a floored prompt and a sandbox-scope
2587
+ // escalation (`request_permissions`, NOT_DELEGABLE_TOOLS — #7975) pending for
2588
+ // a human, and `approvalPolicy` stays `on-request` after the switch (#8619).
1181
2589
  _onPermissionModeChanged(mode) {
1182
2590
  if (mode === 'auto') this._permissions.autoAllowPending()
1183
2591
  }
1184
2592
 
2593
+ /**
2594
+ * Base dir the per-session materialized-attachment dirs live under
2595
+ * (#7373). Named once so `_buildTurnInput()`'s lazy creation and the boot
2596
+ * sweep cannot drift onto two different paths. Mirrors
2597
+ * `CliSession.PERMISSION_MODE_SIDECAR_BASE` and `ClaudeTuiSession.SINK_BASE`.
2598
+ */
2599
+ static get ATTACH_BASE() { return join(tmpdir(), 'chroxy-codex-attach') }
2600
+
2601
+ /**
2602
+ * #7373 — boot-time sweep of materialized-attachment dirs orphaned by a
2603
+ * crash. destroy() removes a session's own dir, but a SIGKILL leaks it, so
2604
+ * a long-lived host accumulates one per crashed session that ever
2605
+ * materialized a binary attachment. Same ownership rule and implementation
2606
+ * as the claude-tui sink sweep and the claude-cli sidecar sweep — only
2607
+ * dirs whose `owner.pid` is DEAD are removed, so a live daemon's dirs
2608
+ * (including this one's) are kept and the sweep is safe to run
2609
+ * unconditionally at boot.
2610
+ *
2611
+ * @param {object} [logger] - logger with info/warn (defaults to module log)
2612
+ * @returns {{swept:number, kept:number}}
2613
+ */
2614
+ static sweepStaleAttachDirs(logger = log) {
2615
+ return sweepStaleOwnedDirs(CodexAppServerSession.ATTACH_BASE, {
2616
+ logger,
2617
+ label: 'codex attach',
2618
+ })
2619
+ }
2620
+
1185
2621
  async destroy() {
1186
2622
  this._destroying = true
1187
2623
  this.clearOutgoingQueue({ emit: false })