@chroxy/server 0.11.0 → 0.11.10

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