@chroxy/server 0.10.0 → 0.11.0

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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -1,17 +1,110 @@
1
1
  import { mkdtempSync, rmSync } from 'fs'
2
2
  import { tmpdir } from 'os'
3
3
  import { join, basename, extname } from 'path'
4
- import { BaseSession, buildBaseSessionOpts } from './base-session.js'
4
+ import { BaseSession, buildBaseSessionOpts, DEFAULT_RESULT_TIMEOUT_MS } from './base-session.js'
5
+ import { isOperatorTimeoutInRange } from './duration.js'
6
+ import { nonNegInt, synthesizeModelUsage } from './usage-normalize.js'
5
7
  import { CodexSession, resolveCodexSandbox } from './codex-session.js'
6
8
  import { CodexAppServerClient } from './codex-app-server-client.js'
7
9
  import { PermissionManager, wirePermissionManager } from './permission-manager.js'
8
10
  import { materializeAttachments, buildAttachmentsPromptSuffix } from './claude-tui-attachments.js'
9
11
  import { buildSpawnEnv } from './utils/spawn-env.js'
12
+ import { labelBinarySpawnFailure } from './utils/verify-binary.js'
10
13
  import { createLogger, loggerForSession } from './logger.js'
11
14
 
12
15
  // Image extensions codex can attach for VISION via a `localImage` input item.
13
16
  const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg'])
14
17
 
18
+ // #6638: cap on cached fileChange diffs (itemId → changes). A turn deletes each on
19
+ // completion and clears the map at turn end, so this only bites a pathological
20
+ // flood of un-completed fileChange items.
21
+ const MAX_PENDING_FILE_CHANGES = 500
22
+
23
+ // #6684: cap the rendered mcpToolCall result text. A connector tool can return an
24
+ // arbitrarily large content array / structuredContent blob; bound it so a single
25
+ // tool_result can't balloon the transcript or the persisted history ring.
26
+ const MAX_MCP_RESULT_CHARS = 10_000
27
+
28
+ // #6629: bounded backstop for codex's OWN response-stream reconnect loop. #6623
29
+ // keeps the turn OPEN on a transient `Reconnecting... N/M` error so codex can
30
+ // recover, and the only pre-existing backstop was the 30-min result timeout.
31
+ // But a pending permission prompt CLEARS that timer outright
32
+ // (`_pauseResultTimeoutForPermission` → `_clearResultTimeout`), and it is only
33
+ // re-armed when the NEXT notification arrives (`_resetResultTimeout`, run at the
34
+ // top of `_onNotification`). A codex approval is a server→client REQUEST, not a
35
+ // notification, so it never re-arms anything. So the exact #6629 situation — a
36
+ // shell-escalation prompt pending, then the response stream wedges mid-reconnect
37
+ // with no further notifications — leaves NO active result timeout at all, and the
38
+ // session hangs in "Working..." indefinitely. This watchdog is the independent
39
+ // backstop for that gap: armed on a transient reconnect notification, NOT touched
40
+ // by the permission pause, disarmed the moment codex makes any real forward
41
+ // progress, and — if codex neither recovers nor emits its terminal give-up —
42
+ // fails the turn cleanly (clears busy + sweeps orphan tool_starts) with
43
+ // `error{code:'stream_stall'}` so the client shows its existing retry affordance
44
+ // instead of a stale spinner. 2 min comfortably clears codex's bounded N/5 retry
45
+ // cycle while bounding the worst-case stale state far below the 30-min default.
46
+ const RECONNECT_WATCHDOG_MS = 2 * 60 * 1000
47
+
48
+ // #6856: dedicated HARD CAP on how long a codex turn may stay in the transient-
49
+ // reconnect-SUPPRESSED state opened by #6854. The #6629 watchdog above is a
50
+ // SILENCE detector — it is RE-ARMED on every `Reconnecting...` tick, so it only
51
+ // fires after codex goes QUIET for a full window. That leaves one path still
52
+ // unbounded-but-slow: a codex that emits reconnect notifications FOREVER (never
53
+ // recovering, never silent, never emitting a terminal give-up). Each tick runs
54
+ // `_resetResultTimeout` (pushing the 30-min result timeout out) AND re-arms the
55
+ // silence watchdog — so BOTH backstops keep sliding forward and the turn stays
56
+ // "Working..." far longer than it should. This deadline is armed ONCE the moment
57
+ // the turn first enters suppression and is deliberately NOT re-armed on later
58
+ // reconnect ticks, so a never-ending reconnect storm fails on a fixed bound. It
59
+ // is cleared the instant codex makes genuine forward progress (any non-`error`
60
+ // notification) or the turn ends. 5 min sits above codex's bounded N/5 retry
61
+ // burst AND above the 2-min silence watchdog (so the faster silence path still
62
+ // wins its own case), while capping the worst case 6x below the 30-min result
63
+ // timeout. Override via `reconnectDeadlineMs` opt / CHROXY_CODEX_RECONNECT_DEADLINE_MS,
64
+ // clamped to the window below (#6967) so an override can't break either invariant.
65
+ const RECONNECT_DEADLINE_MS = 5 * 60 * 1000
66
+
67
+ // #6967: the operator override is CLAMPED to the window the #6856 design depends
68
+ // on, not merely checked for finite/positive. Two invariants define that window:
69
+ //
70
+ // FLOOR (exclusive) — the deadline must sit ABOVE the #6629 silence watchdog.
71
+ // Below it, the deadline would beat the silence path to every wedge and the
72
+ // watchdog's "codex went quiet" case could never win on its own; and above
73
+ // codex's bounded N/5 retry burst, a sub-watchdog deadline would kill turns
74
+ // codex was about to recover on its own. `CHROXY_CODEX_RECONNECT_DEADLINE_MS=1000`
75
+ // used to be accepted verbatim and fired near-instantly.
76
+ // CEILING (exclusive) — the deadline must sit BELOW the default result timeout.
77
+ // Its entire purpose is being a strictly-shorter bound than that timeout; at
78
+ // or past it the deadline is dead code (the result timeout fires first).
79
+ //
80
+ // `isOperatorTimeoutInRange` runs first so this shares the finite/positive/<=24h
81
+ // guard rail (and its typo warning) with `resultTimeoutMs` & friends; the window
82
+ // check then narrows it to this timer's own bounds.
83
+ const RECONNECT_DEADLINE_FLOOR_MS = RECONNECT_WATCHDOG_MS
84
+ const RECONNECT_DEADLINE_CEILING_MS = DEFAULT_RESULT_TIMEOUT_MS
85
+
86
+ // #6856/#6967: resolve the reconnect-suppression deadline. The opt wins over the
87
+ // env var, but only when it is itself VALID — an out-of-range opt falls through
88
+ // to the env candidate rather than shadowing it. Anything outside the window
89
+ // above (including a non-finite value: unset env → NaN, garbage → NaN, and
90
+ // 0/negative) falls back to the default. Returns ms.
91
+ function resolveReconnectDeadlineMs(optValue, logger = log) {
92
+ for (const candidate of [optValue, Number(process.env.CHROXY_CODEX_RECONNECT_DEADLINE_MS)]) {
93
+ if (!isOperatorTimeoutInRange(candidate, { name: 'reconnectDeadlineMs', log: logger })) continue
94
+ if (candidate > RECONNECT_DEADLINE_FLOOR_MS && candidate < RECONNECT_DEADLINE_CEILING_MS) return candidate
95
+ // Same defensive shape as isOperatorTimeoutInRange's own warn — a stubbed
96
+ // logger without .warn must not turn a rejected override into a throw.
97
+ if (logger && typeof logger.warn === 'function') {
98
+ logger.warn(
99
+ `reconnectDeadlineMs ${candidate} is outside the supported window ` +
100
+ `(${RECONNECT_DEADLINE_FLOOR_MS}ms < value < ${RECONNECT_DEADLINE_CEILING_MS}ms); ` +
101
+ `falling back to the ${RECONNECT_DEADLINE_MS}ms default`,
102
+ )
103
+ }
104
+ }
105
+ return RECONNECT_DEADLINE_MS
106
+ }
107
+
15
108
  const log = createLogger('codex-app-server')
16
109
 
17
110
  /**
@@ -72,6 +165,15 @@ export class CodexAppServerSession extends BaseSession {
72
165
  terminal: false,
73
166
  thinkingLevel: false,
74
167
  streaming: true,
168
+ // #6888: despite inProcessPermissions:true (this session's
169
+ // respondToPermission delegates to the shared PermissionManager, which DOES
170
+ // compute a deny message via buildDenyMessage(reason)), _routeApproval only
171
+ // reads `result.behavior` when building the RPC response back to codex —
172
+ // `result.message` is never forwarded, so the operator's deny reason is
173
+ // silently dropped. Explicit false (not just omitted) so this doesn't read
174
+ // as an oversight: tracked by #6885 ("Codex deny reason either reaches the
175
+ // model or is documented as unsupported"). Flip to true once that lands.
176
+ denyReason: false,
75
177
  }
76
178
  }
77
179
 
@@ -88,19 +190,66 @@ export class CodexAppServerSession extends BaseSession {
88
190
  this._lastUsage = null
89
191
  this._skillsPrepended = false // #6606 — inject the skills prefix once, on turn 1
90
192
  this._turnAbort = null // per-turn AbortController — cancels pending approvals
193
+ this._reconnectWatchdog = null // #6629 — bounded backstop for a wedged reconnect
194
+ this._reconnectDeadline = null // #6856 — one-shot hard cap on total reconnect-suppression time
195
+ // #6856/#6967 — configurable reconnect-suppression deadline (opt / env /
196
+ // default), clamped to the window between the #6629 silence watchdog and the
197
+ // default result timeout. The out-of-range warning goes to the MODULE logger,
198
+ // not the usual `this._log || log`: `this._log` is the thread-scoped logger
199
+ // built in start() (it needs a thread id, which does not exist yet), so at
200
+ // construction that expression is unconditionally `log` and writing it would
201
+ // only imply a session scoping this warn can never have.
202
+ this._reconnectDeadlineMs = resolveReconnectDeadlineMs(opts.reconnectDeadlineMs)
203
+ // #6856 — injectable timer seam (defaults to node globals) so the reconnect
204
+ // deadline is unit-testable without wall-clock waits, mirroring the #6908/#6911
205
+ // byok-mcp-config `setTimer`/`clearTimer` pattern. Only the deadline routes
206
+ // through this; the #6629 silence watchdog keeps using the globals directly.
207
+ this._setTimer = typeof opts.setTimer === 'function' ? opts.setTimer : setTimeout
208
+ this._clearTimer = typeof opts.clearTimer === 'function' ? opts.clearTimer : clearTimeout
209
+ // #6638: per-session sandbox override (create_session `codexSandbox`) — wins
210
+ // over CHROXY_CODEX_SANDBOX / the default. Applied at thread start.
211
+ this._codexSandbox = opts.codexSandbox || null
212
+ // #6929 review — the sandbox actually resolved+applied to `thread/start`
213
+ // (set in start(), see below). null until then; getCodexSandbox() falls
214
+ // back to a live resolve for that (normally unreachable) pre-start window.
215
+ this._resolvedCodexSandbox = null
216
+ // #6638: fileChange item.changes cached by itemId, so a fileChange approval
217
+ // (whose params carry NO diff) can surface WHAT will change. Cleared per turn.
218
+ this._pendingFileChanges = new Map()
91
219
  this._attachDir = null // #6609 — lazily-created temp dir for materialized attachments
92
220
 
93
221
  // #6605 Phase 2 — surface codex approvals through the same PermissionManager
94
222
  // bridge SdkSession uses. wirePermissionManager re-emits permission_request /
95
223
  // permission_resolved / user_question on THIS session and back-links
96
224
  // _pendingPermissions/_lastPermissionData for ws-permissions.js.
97
- this._permissions = new PermissionManager({ log })
225
+ // #6794 — pass cwd so the protected-path floor can resolve relative tool
226
+ // targets (.git/.claude/.env…) against this session's working directory.
227
+ // #6771 — pass the durable rule store (persistent per-project allow-always).
228
+ this._permissions = new PermissionManager({ log, cwd: this.cwd, ruleStore: this._permissionRuleStore })
98
229
  wirePermissionManager(this, this._permissions, {
99
230
  onRequest: () => this._pauseResultTimeoutForPermission(),
100
231
  onResolved: () => this._resumeResultTimeoutForPermission(),
101
232
  })
102
233
  }
103
234
 
235
+ /**
236
+ * #6901: the ACTIVE/resolved sandbox mode this thread runs under — the exact
237
+ * value passed to `thread/start` (see start()), which STORES the resolved
238
+ * value on `this._resolvedCodexSandbox` at that moment. #6929 review: this
239
+ * returns the stored value instead of re-resolving `CHROXY_CODEX_SANDBOX` on
240
+ * every call, so a later env change can't make the display drift from what
241
+ * this already-running thread actually got (Codex applies the sandbox once
242
+ * at thread start; it cannot change mid-thread). Falls back to a live
243
+ * resolve only in the window before start() has run (session constructed but
244
+ * not yet started). Surfaced by `SessionManager.listSessions()` as
245
+ * `SessionInfo.codexSandbox` so a client can DISPLAY the current sandbox for
246
+ * a running codex session. Display-only: changing it needs a new session.
247
+ * @returns {string} one of CODEX_SANDBOX_MODES
248
+ */
249
+ getCodexSandbox() {
250
+ return this._resolvedCodexSandbox || resolveCodexSandbox(this._codexSandbox)
251
+ }
252
+
104
253
  _buildChildEnv() { return buildSpawnEnv('codex') }
105
254
 
106
255
  // ------------------------------------------------------------------
@@ -108,9 +257,18 @@ export class CodexAppServerSession extends BaseSession {
108
257
  // ------------------------------------------------------------------
109
258
 
110
259
  async start() {
111
- const sandbox = resolveCodexSandbox()
260
+ // #6929 review — resolve AND STORE here, the actual `thread/start` apply
261
+ // site, so getCodexSandbox() can report what this thread really got instead
262
+ // of re-resolving the env (and potentially drifting from it) on every call.
263
+ this._resolvedCodexSandbox = resolveCodexSandbox(this._codexSandbox)
264
+ const sandbox = this._resolvedCodexSandbox
265
+ // Capture the EXACT binary the client will spawn so the spawn-time backstop
266
+ // (#6708) verifies that path — in start()'s catch AND later in
267
+ // _onClientExit — rather than a fresh re-resolve.
268
+ const attemptedBinary = CodexAppServerSession.resolvedBinary
269
+ this._spawnedBinary = attemptedBinary
112
270
  this._client = new CodexAppServerClient({
113
- bin: CodexAppServerSession.resolvedBinary,
271
+ bin: attemptedBinary,
114
272
  cwd: this.cwd,
115
273
  env: this._buildChildEnv(),
116
274
  logger: log,
@@ -119,13 +277,30 @@ export class CodexAppServerSession extends BaseSession {
119
277
  this._client.on('serverRequest', (r) => this._onServerRequest(r))
120
278
  this._client.on('exit', (e) => this._onClientExit(e))
121
279
 
122
- await this._client.initialize({ name: 'chroxy', version: '1' })
123
- const started = await this._client.request('thread/start', {
124
- approvalPolicy: this._approvalPolicy(), // #6605 P2 — derived from permission mode
125
- cwd: this.cwd,
126
- sandbox,
127
- ...(this.model ? { model: this.model } : {}),
128
- })
280
+ let started
281
+ 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
+ })
289
+ } catch (err) {
290
+ // #6708 — the app-server child is spawned inside initialize(); a missing/
291
+ // quarantined codex binary surfaces here as an initialize rejection (the
292
+ // child errors and _onError rejects the pending request). Re-verify so the
293
+ // session_create_failed names the quarantine + fix rather than an opaque
294
+ // "codex app-server exited". Only relabels when the binary is actually
295
+ // unhealthy; otherwise the original protocol error rethrows unchanged.
296
+ const labeled = labelBinarySpawnFailure({
297
+ attemptedPath: err?.path || this._spawnedBinary,
298
+ binary: 'codex',
299
+ prefix: 'Failed to start codex app-server',
300
+ })
301
+ if (labeled) throw new Error(labeled)
302
+ throw err
303
+ }
129
304
  this._threadId = started?.thread?.id || null
130
305
  // #6608 — do NOT set this.resumeSessionId in Phase 1: capabilities.resume is
131
306
  // false, and SessionManager persists resumeSessionId as the conversationId to
@@ -258,6 +433,13 @@ export class CodexAppServerSession extends BaseSession {
258
433
  return
259
434
  }
260
435
  this._resetResultTimeout()
436
+ // #6629/#6856 — any notification that is NOT another `error` tick is genuine
437
+ // forward progress: codex's response stream is live again, so disarm BOTH the
438
+ // reconnect backstops that #6623's suppression path may have armed — the #6629
439
+ // silence watchdog and the #6856 one-shot suppression deadline. (A terminal
440
+ // `error` clears both below on its way to _failTurn; a transient reconnect
441
+ // `error` re-arms the watchdog but leaves the deadline untouched.)
442
+ if (method !== 'error') { this._clearReconnectWatchdog(); this._clearReconnectDeadline() }
261
443
  const t = this._activeTurn
262
444
  switch (method) {
263
445
  case 'turn/started':
@@ -282,9 +464,39 @@ export class CodexAppServerSession extends BaseSession {
282
464
  case 'turn/completed':
283
465
  this._finishTurn(params?.turn)
284
466
  break
285
- case 'error':
467
+ case 'error': {
468
+ // #6623 — codex emits transient `error` notifications WHILE its OWN retry
469
+ // loop re-establishes a dropped response stream (a `Reconnecting... N/M`
470
+ // message + `codexErrorInfo.responseStreamDisconnected`). This commonly
471
+ // fires right after a permission / escalation round-trip stalls a shell
472
+ // turn. These are NOT terminal: failing here surfaces a red provider error
473
+ // and orphans the in-flight turn even though codex is still recovering and
474
+ // may yet emit turn/completed. Keep the turn OPEN on a reconnect-in-progress
475
+ // notification — the result timeout (re-armed by _resetResultTimeout above)
476
+ // is the backstop if codex never recovers, and codex's terminal give-up
477
+ // (a disconnect WITHOUT a reconnecting message) still falls through to fail.
478
+ const err = this._errorPayload(params)
479
+ if (this._isTransientReconnect(err)) {
480
+ ;(this._log || log).warn(`codex app-server response stream reconnecting (turn kept open): ${err.message || 'responseStreamDisconnected'}`)
481
+ // #6629 — arm the bounded watchdog so a reconnect that NEVER recovers
482
+ // (nor emits codex's terminal give-up) still reconciles the stale
483
+ // working state, even when a pending permission has paused the result
484
+ // timeout. Re-arms on each reconnect tick so codex's legit N/5 retry
485
+ // burst doesn't trip it mid-recovery.
486
+ this._armReconnectWatchdog()
487
+ // #6856 — arm the one-shot suppression deadline the FIRST time this turn
488
+ // enters the reconnect-suppressed state. Unlike the watchdog it is NOT
489
+ // re-armed here on subsequent ticks (the guard in _armReconnectDeadline
490
+ // makes a later call a no-op), so a reconnect storm that keeps ticking
491
+ // forever still fails on a fixed bound instead of sliding both backstops out.
492
+ this._armReconnectDeadline()
493
+ break
494
+ }
495
+ this._clearReconnectWatchdog() // terminal error → about to fail; drop the backstops
496
+ this._clearReconnectDeadline() // #6856
286
497
  this._failTurn(`Codex error: ${JSON.stringify(params).slice(0, 200)}`)
287
498
  break
499
+ }
288
500
  default:
289
501
  break // reasoning/plan/other items are ignored in Phase 1
290
502
  }
@@ -292,7 +504,12 @@ export class CodexAppServerSession extends BaseSession {
292
504
 
293
505
  _onItemStarted(item) {
294
506
  if (!item) return
295
- // commandExecution / fileChange / mcpToolCall map to Chroxy tools.
507
+ // commandExecution / fileChange / mcpToolCall map to Chroxy tools. The
508
+ // mcpToolCall EXECUTION is surfaced as a tool_start/tool_result so connector
509
+ // tool calls are visible in the transcript (#6684 part 4). Note this is
510
+ // transcript visibility only — a connector tool execution does not itself go
511
+ // through the approval pipeline (that is the separate mcpServer/elicitation
512
+ // request, #6635); see docs/design/codex-permission-model.md §8.
296
513
  if (item.type === 'commandExecution') {
297
514
  const toolUseId = item.id
298
515
  this.emit('tool_start', {
@@ -304,13 +521,38 @@ export class CodexAppServerSession extends BaseSession {
304
521
  this._trackToolStart(toolUseId, 'shell')
305
522
  } else if (item.type === 'fileChange') {
306
523
  const toolUseId = item.id
524
+ const changes = item.changes ?? item.patch ?? null
307
525
  this.emit('tool_start', {
308
526
  messageId: this._activeTurn.messageId,
309
527
  toolUseId,
310
528
  tool: 'apply_patch',
311
- input: { changes: item.changes ?? item.patch ?? null },
529
+ input: { changes },
312
530
  })
313
531
  this._trackToolStart(toolUseId, 'apply_patch')
532
+ // #6638: remember the changes so a later fileChange approval (keyed by the
533
+ // same itemId, but carrying no diff) can show what will change. Only cache a
534
+ // non-null diff — a null-change item would just waste a slot and evict a real
535
+ // diff earlier. Bounded: deleted on item completion / cleared per turn; evict
536
+ // oldest at the cap.
537
+ if (toolUseId != null && changes != null) {
538
+ if (this._pendingFileChanges.size >= MAX_PENDING_FILE_CHANGES) {
539
+ this._pendingFileChanges.delete(this._pendingFileChanges.keys().next().value)
540
+ }
541
+ this._pendingFileChanges.set(toolUseId, changes)
542
+ }
543
+ } else if (item.type === 'mcpToolCall') {
544
+ // #6684: surface a connector tool EXECUTION in the transcript, labelled
545
+ // `server/tool` (e.g. `github/create_issue`) so the source connector is
546
+ // clear, with the call arguments as the input.
547
+ const toolUseId = item.id
548
+ const tool = this._mcpToolLabel(item)
549
+ this.emit('tool_start', {
550
+ messageId: this._activeTurn.messageId,
551
+ toolUseId,
552
+ tool,
553
+ input: { server: item.server, tool: item.tool, arguments: item.arguments },
554
+ })
555
+ this._trackToolStart(toolUseId, tool)
314
556
  }
315
557
  }
316
558
 
@@ -322,6 +564,16 @@ export class CodexAppServerSession extends BaseSession {
322
564
  } else if (item.type === 'fileChange') {
323
565
  this.emit('tool_result', { toolUseId: item.id, result: item.status ?? '' })
324
566
  this._trackToolResult(item.id)
567
+ if (item.id != null) this._pendingFileChanges.delete(item.id) // #6638: done — release the cached diff
568
+ } else if (item.type === 'mcpToolCall') {
569
+ // #6684/#6712: emit the connector tool's output as a tool_result. A failed
570
+ // call surfaces error.message as the result text AND flags `isError` (which
571
+ // now round-trips the wire → clients style the error). Large output is
572
+ // capped and flagged `truncated`.
573
+ const { result, truncated } = this._summarizeMcpResult(item)
574
+ const isError = item.status === 'failed' || item.error != null
575
+ this.emit('tool_result', { toolUseId: item.id, result, truncated, isError })
576
+ this._trackToolResult(item.id)
325
577
  } else if (item.type === 'agentMessage') {
326
578
  // Fallback: if the final text never arrived as deltas (short replies can
327
579
  // skip the delta stream), emit it once so the message isn't lost.
@@ -332,6 +584,49 @@ export class CodexAppServerSession extends BaseSession {
332
584
  }
333
585
  }
334
586
 
587
+ // #6684: `server/tool` label for an mcpToolCall (e.g. `github/create_issue`),
588
+ // degrading to whichever of the two is present, else a generic `mcp`.
589
+ _mcpToolLabel(item) {
590
+ const server = typeof item?.server === 'string' ? item.server.trim() : ''
591
+ const tool = typeof item?.tool === 'string' ? item.tool.trim() : ''
592
+ if (server && tool) return `${server}/${tool}`
593
+ return tool || server || 'mcp'
594
+ }
595
+
596
+ // #6684: reduce an mcpToolCall completion to a { result, truncated } tool_result
597
+ // (the caller adds `isError` from the item status). Prefers the connector's
598
+ // error message, then the MCP content array (text parts inline, non-text parts
599
+ // as a `[type]` marker), then structuredContent, then the bare status so the
600
+ // card is never blank. Text is bounded by MAX_MCP_RESULT_CHARS.
601
+ _summarizeMcpResult(item) {
602
+ if (item?.error && typeof item.error.message === 'string' && item.error.message) {
603
+ return this._capMcpResult(item.error.message)
604
+ }
605
+ const content = item?.result?.content
606
+ if (Array.isArray(content) && content.length > 0) {
607
+ const text = content
608
+ .map((c) => (c && typeof c.text === 'string' ? c.text : c && typeof c.type === 'string' ? `[${c.type}]` : null))
609
+ .filter(Boolean)
610
+ .join('\n')
611
+ if (text) return this._capMcpResult(text)
612
+ }
613
+ if (item?.result?.structuredContent != null) {
614
+ return this._capMcpResult(JSON.stringify(item.result.structuredContent))
615
+ }
616
+ return { result: item?.status ?? '', truncated: false }
617
+ }
618
+
619
+ // Cap the rendered text at MAX_MCP_RESULT_CHARS, signalling an over-cap slice via
620
+ // the wire `truncated` flag (ServerToolResultSchema.truncated → store-core's
621
+ // toolResultTruncated) rather than an in-band marker.
622
+ _capMcpResult(text) {
623
+ const s = String(text)
624
+ if (s.length > MAX_MCP_RESULT_CHARS) {
625
+ return { result: s.slice(0, MAX_MCP_RESULT_CHARS), truncated: true }
626
+ }
627
+ return { result: s, truncated: false }
628
+ }
629
+
335
630
  _ensureStreamStart() {
336
631
  if (this._activeTurn.didStreamStart) return
337
632
  this._activeTurn.didStreamStart = true
@@ -340,10 +635,25 @@ export class CodexAppServerSession extends BaseSession {
340
635
 
341
636
  _mapUsage(params) {
342
637
  const u = params?.usage || params || {}
638
+ const rawInput = nonNegInt(u.inputTokens ?? u.input_tokens)
639
+ const cached = nonNegInt(u.cachedInputTokens ?? u.cached_input_tokens)
343
640
  return {
344
- input_tokens: u.inputTokens ?? u.input_tokens ?? 0,
345
- output_tokens: u.outputTokens ?? u.output_tokens ?? 0,
346
- cached_input_tokens: u.cachedInputTokens ?? u.cached_input_tokens ?? 0,
641
+ // #6692: codex reports cached tokens as a SUBSET of input (OpenAI's
642
+ // prompt_tokens_details convention; corroborated in-repo by the exec
643
+ // path's context ratchet treating input_tokens as the full prompt —
644
+ // codex-session.js). Chroxy's accounting keys are ADDITIVE (Anthropic
645
+ // shape: input excludes cache reads), so split into uncached input +
646
+ // cache_read. The subtraction is clamped, so a future codex build that
647
+ // switched to additive reporting would undercount input rather than
648
+ // go negative. Before this fix the cache count was emitted only under
649
+ // `cached_input_tokens`, a key `_trackUsage` never reads — codex cache
650
+ // tokens were silently dropped from cumulativeUsage.
651
+ input_tokens: nonNegInt(rawInput - cached),
652
+ output_tokens: nonNegInt(u.outputTokens ?? u.output_tokens),
653
+ cache_read_input_tokens: cached,
654
+ // Deprecated duplicate of cache_read_input_tokens — kept one release
655
+ // for any external reader of the raw result payload (#6692).
656
+ cached_input_tokens: cached,
347
657
  }
348
658
  }
349
659
 
@@ -353,7 +663,15 @@ export class CodexAppServerSession extends BaseSession {
353
663
  this._clearResultTimeout()
354
664
  if (t.didStreamStart) this.emit('stream_end', { messageId: t.messageId })
355
665
  this._emitResult(
356
- { cost: null, duration: turn?.durationMs ?? null, usage: this._lastUsage, sessionId: this._threadId },
666
+ {
667
+ cost: null,
668
+ duration: turn?.durationMs ?? null,
669
+ usage: this._lastUsage,
670
+ // #6692: single-model split (codex runs one model per session; cost
671
+ // is unknown at the source — pricing happens downstream).
672
+ modelUsage: synthesizeModelUsage(this.model, this._lastUsage),
673
+ sessionId: this._threadId,
674
+ },
357
675
  'turn_ended_with_orphan_tool_start',
358
676
  )
359
677
  this._activeTurn = null
@@ -367,19 +685,54 @@ export class CodexAppServerSession extends BaseSession {
367
685
  this._maybeDequeue()
368
686
  }
369
687
 
370
- _failTurn(message) {
688
+ // #6629 — `code` lets the reconnect-watchdog surface its failure as
689
+ // `error{code:'stream_stall'}` so clients reuse the existing recoverable-stall
690
+ // retry chip (parity with SdkSession's stall recovery) instead of rendering a
691
+ // bare, non-actionable error. An intentional stop still wins and reports `stopped`.
692
+ _failTurn(message, { code } = {}) {
371
693
  this._clearResultTimeout()
372
694
  const t = this._activeTurn
373
695
  if (t?.didStreamStart) this.emit('stream_end', { messageId: t.messageId })
374
696
  const wasIntentional = this._consumeIntentionalStop()
375
697
  if (wasIntentional) this.emit('stopped', {})
376
- else this.emit('error', { message })
698
+ else this.emit('error', code ? { message, code } : { message })
377
699
  this._activeTurn = null
378
700
  this._endTurnAbort()
379
701
  this._clearMessageState()
380
702
  this._maybeDequeue()
381
703
  }
382
704
 
705
+ // #6623 — codex's `error` notification carries the error under an `error` wrapper
706
+ // in the wild ({ error: { message, codexErrorInfo, ... } }) but a bare shape
707
+ // ({ message, ... }) elsewhere. Normalize to the inner error object either way so
708
+ // the callers read one shape.
709
+ _errorPayload(params) {
710
+ return params?.error && typeof params.error === 'object' ? params.error : (params || {})
711
+ }
712
+
713
+ // #6623 — true iff this error is codex's OWN transient response-stream reconnect
714
+ // (its retry loop is still running) rather than a terminal failure. Codex tags the
715
+ // retry with BOTH `codexErrorInfo.responseStreamDisconnected` AND a
716
+ // `Reconnecting... N/M` message; the terminal give-up drops the reconnecting
717
+ // message (or is a different error entirely), so it still fails the turn. Gating
718
+ // on both keeps the suppression conservative — anything not clearly a retry falls
719
+ // through to _failTurn.
720
+ _isTransientReconnect(err) {
721
+ const info = err?.codexErrorInfo
722
+ const disconnected = info && typeof info === 'object' && info.responseStreamDisconnected != null
723
+ if (!disconnected) return false
724
+ return /reconnect/i.test(typeof err?.message === 'string' ? err.message : '')
725
+ }
726
+
727
+ // #6638: also release cached fileChange diffs when per-turn state is cleared
728
+ // (turn end / fail / destroy), so a diff can't outlive its turn.
729
+ _clearMessageState() {
730
+ super._clearMessageState()
731
+ this._pendingFileChanges.clear()
732
+ this._clearReconnectWatchdog() // #6629 — drop the reconnect backstop on any turn teardown
733
+ this._clearReconnectDeadline() // #6856 — drop the suppression deadline on any turn teardown
734
+ }
735
+
383
736
  // Abort this turn's approval scope (any pending permission_request resolves as
384
737
  // a deny) and drop the controller. Safe to call with no active turn.
385
738
  _endTurnAbort() {
@@ -412,31 +765,91 @@ export class CodexAppServerSession extends BaseSession {
412
765
  if (this._resultTimeout) { clearTimeout(this._resultTimeout); this._resultTimeout = null }
413
766
  }
414
767
 
768
+ // #6629 — bounded reconnect watchdog. Armed when #6623 keeps a turn open on a
769
+ // transient response-stream reconnect; unlike the result timeout it is NOT
770
+ // paused by a pending permission, so a codex that wedges mid-reconnect (never
771
+ // recovers, never emits its terminal give-up) still reconciles the stale
772
+ // working state promptly. Re-armed (clear + set) on each reconnect tick so
773
+ // codex's legit multi-attempt retry burst doesn't trip it — it only fires
774
+ // after a full window of silence following the last thing codex said. Disarmed
775
+ // by any genuine forward-progress notification (recovery) and on turn teardown.
776
+ _armReconnectWatchdog() {
777
+ this._clearReconnectWatchdog()
778
+ this._reconnectWatchdog = setTimeout(() => {
779
+ this._reconnectWatchdog = null
780
+ if (!this._activeTurn) return
781
+ // #6629 — INTENTIONAL that this fires even while a permission prompt is
782
+ // pending. The watchdog only arms on a genuine disconnect and is disarmed by
783
+ // ANY forward-progress notification, so reaching this callback means codex
784
+ // emitted no ticks and made no progress for the full window — the response
785
+ // stream is genuinely wedged and the turn cannot complete regardless of the
786
+ // pending approval. Failing cleanly (deny the pending approval via
787
+ // _endTurnAbort + surface a recoverable stall) is the actionable outcome;
788
+ // deliberately NOT firing during a pending permission would just restore the
789
+ // #6629 indefinite-stale-state bug (the paused result timeout is exactly what
790
+ // this watchdog exists to backstop). The user can retry to continue.
791
+ ;(this._log || log).warn(`codex app-server response stream did not recover within ${RECONNECT_WATCHDOG_MS}ms — reconciling stale working state (#6629)`)
792
+ this._failTurn('Codex response stream disconnected and did not recover — the turn was stopped. Retry to continue.', { code: 'stream_stall' })
793
+ }, RECONNECT_WATCHDOG_MS)
794
+ if (typeof this._reconnectWatchdog.unref === 'function') this._reconnectWatchdog.unref()
795
+ }
796
+
797
+ _clearReconnectWatchdog() {
798
+ if (this._reconnectWatchdog) { clearTimeout(this._reconnectWatchdog); this._reconnectWatchdog = null }
799
+ }
800
+
801
+ // #6856 — one-shot HARD CAP on the transient-reconnect-suppressed state. Armed
802
+ // ONCE on entering suppression; the `if (this._reconnectDeadline) return` guard
803
+ // is load-bearing — a subsequent reconnect tick must NOT push the deadline out
804
+ // (that re-arming is exactly the #6854 gap this closes). It is a strictly-shorter
805
+ // bound than the 30-min result timeout and independent of the #6629 silence
806
+ // watchdog (which keeps sliding forward on every tick). Cleared on genuine
807
+ // forward progress or turn teardown. Routes through the injectable timer seam so
808
+ // it is hermetically testable, and unref's the handle so a bare test/CI run
809
+ // self-exits with no leaked timer (#6933).
810
+ _armReconnectDeadline() {
811
+ if (this._reconnectDeadline) return // already suppressed — do NOT extend the deadline
812
+ this._reconnectDeadline = this._setTimer(() => {
813
+ this._reconnectDeadline = null
814
+ if (!this._activeTurn) return
815
+ const secs = Math.round(this._reconnectDeadlineMs / 1000)
816
+ ;(this._log || log).warn(`codex app-server reconnect exceeded ${secs}s without recovery — failing the turn (#6856)`)
817
+ this._failTurn(`Codex reconnect exceeded ${secs}s without recovery — the turn was stopped. Retry to continue.`, { code: 'stream_stall' })
818
+ }, this._reconnectDeadlineMs)
819
+ if (this._reconnectDeadline && typeof this._reconnectDeadline.unref === 'function') this._reconnectDeadline.unref()
820
+ }
821
+
822
+ _clearReconnectDeadline() {
823
+ if (this._reconnectDeadline) { this._clearTimer(this._reconnectDeadline); this._reconnectDeadline = null }
824
+ }
825
+
415
826
  // ------------------------------------------------------------------
416
827
  // Server → client requests (approvals) — routed into the permission pipeline
417
828
  // ------------------------------------------------------------------
418
829
 
419
830
  // Codex asks before running a command / editing a file (approvalPolicy
420
- // 'on-request'). Route the two clean approval families through the
421
- // PermissionManager; safe-decline the scope-escalation variant (#6610).
831
+ // 'on-request'). All three approval families route through the PermissionManager:
832
+ // command/file as decision enums, and the scope-escalation variant as a
833
+ // permission-grant prompt (#6610). See docs/design/codex-permission-model.md.
422
834
  _onServerRequest({ id, method, params }) {
423
835
  if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval') {
424
836
  this._routeApproval(id, method, params)
425
837
  return
426
838
  }
427
839
  if (method === 'item/permissions/requestApproval') {
428
- // Scope-escalation (codex wants BROADER permissions than its sandbox). The
429
- // response is a permission-grant object, not a simple decision — safe-deny
430
- // (grant nothing) so the turn proceeds without escalating. Full surfacing
431
- // is tracked in #6610.
432
- //
433
- // Send ONLY an empty `permissions` object and OMIT `scope`: per the
434
- // app-server schema PermissionGrantScope accepts only 'turn'/'session', so
435
- // an explicit 'none' is an invalid enum value that errors on deserialize
436
- // (the field's serde default only applies when it's ABSENT) — which would
437
- // wedge the turn, the opposite of a safe-deny (#6612).
438
- ;(this._log || log).info('codex app-server: declining permissions-escalation request (grant nothing) — #6610')
439
- this._client?.respond(id, { permissions: {} })
840
+ // Scope-escalation: codex wants BROADER permissions than its sandbox. Surface
841
+ // it through the permission pipeline as a distinctly-worded prompt (#6610).
842
+ this._routePermissionsApproval(id, params)
843
+ return
844
+ }
845
+ if (method === 'mcpServer/elicitation/request') {
846
+ // A codex MCP server (connector, e.g. GitHub) is eliciting the user — most
847
+ // commonly a write/action confirmation. Previously this fell through to the
848
+ // -32601 decline below, so the connector approval was silently rejected and
849
+ // "missed" (#6635). Surface it as an accept/decline prompt. NOTE: structured
850
+ // form-content collection and interactive url-mode flows are a follow-up —
851
+ // accept currently answers with the action only, no `content`.
852
+ this._routeMcpElicitation(id, params)
440
853
  return
441
854
  }
442
855
  ;(this._log || log).warn(`codex app-server: unsupported serverRequest ${method} — declining`)
@@ -470,9 +883,18 @@ export class CodexAppServerSession extends BaseSession {
470
883
  // renders. `description`/`command`/`file_path` drive the human-facing prompt.
471
884
  _describeApproval(method, params) {
472
885
  if (method === 'item/fileChange/requestApproval') {
886
+ // #6638: the approval params carry no diff, so correlate to the fileChange
887
+ // item's cached changes (same itemId) and surface WHAT changes — a paths
888
+ // summary in the description (visible with no client change) + the raw
889
+ // changes for a client that renders a diff.
890
+ const changes = params?.itemId != null ? this._pendingFileChanges.get(params.itemId) ?? null : null
891
+ const summary = this._summarizeFileChanges(changes)
892
+ const description = summary
893
+ ? (params?.reason ? `${params.reason} — ${summary}` : `Apply changes: ${summary}`)
894
+ : (params?.reason || 'Apply file changes')
473
895
  return {
474
896
  tool: 'apply_patch',
475
- input: { description: params?.reason || 'Apply file changes', file_path: params?.grantRoot },
897
+ input: { description, file_path: params?.grantRoot, changes },
476
898
  }
477
899
  }
478
900
  // item/commandExecution/requestApproval
@@ -484,6 +906,21 @@ export class CodexAppServerSession extends BaseSession {
484
906
  }
485
907
  }
486
908
 
909
+ // #6638: summarize a fileChange `changes` array (FileUpdateChange[] =
910
+ // { path, kind, diff }) into a paths line for the approval prompt, e.g.
911
+ // "2 files: src/a.js, src/b.js". Caps the list (+N more) so it stays bounded
912
+ // for the ≤200-char prompt. Returns null when there's nothing to summarize.
913
+ _summarizeFileChanges(changes) {
914
+ if (!Array.isArray(changes) || changes.length === 0) return null
915
+ const MAX = 3
916
+ const paths = changes.map((c) => (c && typeof c.path === 'string' ? c.path : null)).filter(Boolean)
917
+ if (paths.length === 0) return `${changes.length} file change(s)`
918
+ const shown = paths.slice(0, MAX)
919
+ const extra = paths.length - shown.length
920
+ const list = shown.join(', ') + (extra > 0 ? `, +${extra} more` : '')
921
+ return `${paths.length} file${paths.length === 1 ? '' : 's'}: ${list}`
922
+ }
923
+
487
924
  // The two approval families use DIFFERENT decision vocabularies (from the
488
925
  // app-server JSON schema): fileChange → ReviewDecision, commandExecution →
489
926
  // CommandExecutionApprovalDecision.
@@ -496,6 +933,147 @@ export class CodexAppServerSession extends BaseSession {
496
933
  return { decision: session ? 'acceptForSession' : 'accept' }
497
934
  }
498
935
 
936
+ // #6610: codex's THIRD approval family — item/permissions/requestApproval — is a
937
+ // scope-escalation (it wants broader filesystem/network access than its sandbox).
938
+ // Unlike the command/file families the response is a permission-GRANT object
939
+ // (PermissionsRequestApprovalResponse: { permissions, scope?, strictAutoReview? }),
940
+ // not a decision enum, so it needs its own routing + response mapping. It still
941
+ // flows through the same PermissionManager prompt (a distinctly-worded request),
942
+ // so existing clients render + answer it with the normal allow/deny UI.
943
+ async _routePermissionsApproval(rpcId, params) {
944
+ let result
945
+ try {
946
+ const input = {
947
+ description: this._describePermissionsRequest(params),
948
+ // Structured detail for any client that wants to render the exact scope.
949
+ requestedPermissions: params?.permissions ?? null,
950
+ }
951
+ // Sentinel suggestion → respondToPermission echoes updatedPermissions on an
952
+ // "always allow", which we read as a SESSION-scoped grant (mirrors _routeApproval).
953
+ const suggestions = [{ codexApproval: 'item/permissions/requestApproval' }]
954
+ result = await this._permissions.handlePermission('request_permissions', input, this._turnAbort?.signal, this.permissionMode, suggestions)
955
+ } catch (err) {
956
+ result = { behavior: 'deny', message: err?.message || 'permission error' }
957
+ }
958
+ const allow = result?.behavior === 'allow'
959
+ const session = allow && !!result?.updatedPermissions
960
+ this._client?.respond(rpcId, this._codexPermissionsGrant(allow, session, params?.permissions))
961
+ }
962
+
963
+ // Build the PermissionsRequestApprovalResponse. Approve → grant EXACTLY what codex
964
+ // requested. RequestPermissionProfile and GrantedPermissionProfile share the same
965
+ // {fileSystem?, network?} shape (the request is even additionalProperties:false), so
966
+ // we reconstruct the grant from those two known fields rather than echoing the raw
967
+ // request object: that grants precisely the requested scope while making a malformed
968
+ // frame (an array — typeof [] === 'object' — or any unexpected key) structurally
969
+ // unable to reach the wire and wedge the turn (#6612). Scope 'session' for an
970
+ // "always allow" else 'turn'. Deny → an empty `permissions` object with `scope`
971
+ // OMITTED (an explicit 'none' is an invalid PermissionGrantScope enum and wedges
972
+ // the turn — #6612).
973
+ _codexPermissionsGrant(allow, session, requestedPermissions) {
974
+ if (!allow) return { permissions: {} }
975
+ const src = requestedPermissions && typeof requestedPermissions === 'object' && !Array.isArray(requestedPermissions)
976
+ ? requestedPermissions
977
+ : {}
978
+ const permissions = {}
979
+ if (src.fileSystem !== undefined) permissions.fileSystem = src.fileSystem
980
+ if (src.network !== undefined) permissions.network = src.network
981
+ return { permissions, scope: session ? 'session' : 'turn' }
982
+ }
983
+
984
+ // Human-readable summary of the requested scope for the approval prompt, so the
985
+ // operator sees WHAT codex wants to broaden before granting it. The prompt is
986
+ // truncated to 200 chars downstream, so cap each list to a few entries + a
987
+ // "+N more" tail (keeps the most-load-bearing detail — including the trailing
988
+ // "network access" — from being sliced off) and stringify every path defensively.
989
+ _describePermissionsRequest(params) {
990
+ const MAX_ENTRIES = 3
991
+ const summarize = (arr, render) => {
992
+ const shown = arr.slice(0, MAX_ENTRIES).map(render)
993
+ const extra = arr.length - shown.length
994
+ return extra > 0 ? [...shown, `+${extra} more`] : shown
995
+ }
996
+ const parts = []
997
+ const fs = params?.permissions?.fileSystem
998
+ if (fs && typeof fs === 'object') {
999
+ const entries = Array.isArray(fs.entries) ? fs.entries : []
1000
+ for (const p of summarize(entries, (e) => {
1001
+ const path = e?.path?.path ?? e?.path?.pattern ?? e?.path?.value?.kind ?? 'a path'
1002
+ return `filesystem ${e?.access ?? 'access'} → ${String(path)}`
1003
+ })) parts.push(p)
1004
+ if (Array.isArray(fs.read) && fs.read.length) parts.push(`filesystem read: ${summarize(fs.read, String).join(', ')}`)
1005
+ if (Array.isArray(fs.write) && fs.write.length) parts.push(`filesystem write: ${summarize(fs.write, String).join(', ')}`)
1006
+ }
1007
+ if (params?.permissions?.network?.enabled) parts.push('network access')
1008
+ const scope = parts.length ? parts.join('; ') : 'broader permissions'
1009
+ const reason = typeof params?.reason === 'string' && params.reason.trim()
1010
+ ? ` — ${params.reason.trim()}`
1011
+ : ''
1012
+ return `Codex is requesting to broaden its sandbox permissions${reason}: ${scope}`
1013
+ }
1014
+
1015
+ // #6635: an MCP server (connector) is eliciting the user. Surface it as an
1016
+ // accept/decline prompt through the permission pipeline (was silently declined
1017
+ // with -32601, so a GitHub-connector write approval was "missed" and the tool
1018
+ // call rejected). The elicitation response is { action: accept|decline|cancel,
1019
+ // content? }; we answer with the action only — structured `content` collection
1020
+ // (form / openai/form modes) and interactive url-mode flows are a follow-up.
1021
+ async _routeMcpElicitation(rpcId, params) {
1022
+ let result
1023
+ try {
1024
+ const input = {
1025
+ description: this._describeMcpElicitation(params),
1026
+ serverName: params?.serverName ?? null,
1027
+ mode: params?.mode ?? null,
1028
+ // Surfaced so the client can show a url-mode elicitation's link.
1029
+ url: typeof params?.url === 'string' ? params.url : null,
1030
+ message: typeof params?.message === 'string' ? params.message : null,
1031
+ }
1032
+ // The sentinel is inert for this tool (unlike command/file/escalation, we
1033
+ // don't read updatedPermissions): an elicitation "allow" is a one-shot
1034
+ // accept, never a persisted rule — kept only for handlePermission symmetry.
1035
+ const suggestions = [{ codexApproval: 'mcpServer/elicitation/request' }]
1036
+ result = await this._permissions.handlePermission('mcp_elicitation', input, this._turnAbort?.signal, this.permissionMode, suggestions)
1037
+ } catch (err) {
1038
+ result = { behavior: 'deny', message: err?.message || 'permission error' }
1039
+ }
1040
+ const allow = result?.behavior === 'allow'
1041
+ // #6635: we can't collect structured `content` yet (#6684), so a form-mode
1042
+ // elicitation that REQUIRES fields is DECLINED even on allow — an action-only
1043
+ // accept could make the connector act on empty/default params the user never
1044
+ // saw. Confirmation-style (no required fields) + url-mode accept normally; a
1045
+ // decline is always the safe status quo (matches the pre-#6635 -32601 outcome).
1046
+ const action = allow && !this._elicitationRequiresContent(params) ? 'accept' : 'decline'
1047
+ this._client?.respond(rpcId, { action })
1048
+ }
1049
+
1050
+ // True when accepting would need structured `content` we can't yet collect:
1051
+ // `openai/form` (freeform content) or a `form` whose schema declares required
1052
+ // properties. `url`-mode and content-less confirmation forms return false.
1053
+ _elicitationRequiresContent(params) {
1054
+ const mode = params?.mode
1055
+ if (mode === 'openai/form') return true
1056
+ if (mode !== 'form') return false
1057
+ const required = params?.requestedSchema?.required
1058
+ return Array.isArray(required) && required.length > 0
1059
+ }
1060
+
1061
+ // Human-readable elicitation prompt: which connector is asking, and what for.
1062
+ _describeMcpElicitation(params) {
1063
+ const server = typeof params?.serverName === 'string' && params.serverName.trim()
1064
+ ? params.serverName.trim()
1065
+ : 'an MCP connector'
1066
+ const msg = typeof params?.message === 'string' && params.message.trim() ? params.message.trim() : ''
1067
+ const url = params?.mode === 'url' && typeof params?.url === 'string' && params.url.trim()
1068
+ ? ` (opens ${params.url.trim()})`
1069
+ : ''
1070
+ // Build the two shapes explicitly rather than post-cleaning whitespace: with a
1071
+ // message → `connector "x" asks: <msg>`, without → `connector "x": is requesting…`.
1072
+ return msg
1073
+ ? `Codex connector "${server}" asks: ${msg}${url}`
1074
+ : `Codex connector "${server}": is requesting your input${url}`
1075
+ }
1076
+
499
1077
  // 'auto' (skip all prompts) → codex runs without asking. Every other mode →
500
1078
  // 'on-request': codex asks per action and the PermissionManager applies the
501
1079
  // mode/rules (auto-allow for acceptEdits/rules, prompt for 'approve').
@@ -505,14 +1083,56 @@ export class CodexAppServerSession extends BaseSession {
505
1083
 
506
1084
  // In-process permission responses (capabilities.inProcessPermissions) — thin
507
1085
  // delegators to the PermissionManager, mirroring SdkSession.
508
- respondToPermission(requestId, decision, editedInput) {
509
- return this._permissions.respondToPermission(requestId, decision, editedInput)
1086
+ respondToPermission(requestId, decision, editedInput, reason) {
1087
+ return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
510
1088
  }
511
1089
 
512
1090
  respondToQuestion(text, answers) {
513
1091
  return this._permissions.respondToQuestion(text, answers)
514
1092
  }
515
1093
 
1094
+ // #6829 — permission-rule accessors, mirroring SdkSession/ByokSession. Codex's
1095
+ // PermissionManager already owns a rule store (seeded per-cwd in the ctor), but
1096
+ // without these thin wrappers a codex session's rules were invisible on the
1097
+ // wire: the `permission_rules_updated` broadcast (settings-handlers.js) and the
1098
+ // ws-history reconnect replay (ws-history.js) both gate on `getPermissionRules`
1099
+ // / `getPersistentPermissionRules`, and the projectRules re-seed calls
1100
+ // `setPersistentPermissionRules` — so on codex an allowAlways persisted at the
1101
+ // enforcement layer but never broadcast, replayed, or re-seeded. Session-rule
1102
+ // MUTATION (`setPermissionRules`) is intentionally NOT exposed so codex keeps
1103
+ // advertising `sessionRules:false` in the provider picker (providers.js derives
1104
+ // the capability from `setPermissionRules` presence); only the durable
1105
+ // project-rule read/replay surface is wired.
1106
+
1107
+ /** Current session-scoped permission rules. Delegates to PermissionManager. */
1108
+ getPermissionRules() {
1109
+ if (typeof this._permissions.getRules === 'function') {
1110
+ return this._permissions.getRules()
1111
+ }
1112
+ return []
1113
+ }
1114
+
1115
+ /**
1116
+ * #6771/#6829 — durable (project-scoped) permission rules applied to this
1117
+ * session, tagged `persist:'project'`. Delegates to PermissionManager.
1118
+ */
1119
+ getPersistentPermissionRules() {
1120
+ if (typeof this._permissions.getPersistentRules === 'function') {
1121
+ return this._permissions.getPersistentRules()
1122
+ }
1123
+ return []
1124
+ }
1125
+
1126
+ /**
1127
+ * #6771/#6829 — re-seed this session's in-memory durable rule set (no persist;
1128
+ * the caller owns the store write). Delegates to PermissionManager.
1129
+ */
1130
+ setPersistentPermissionRules(rules) {
1131
+ if (typeof this._permissions.setPersistentRules === 'function') {
1132
+ this._permissions.setPersistentRules(rules)
1133
+ }
1134
+ }
1135
+
516
1136
  // A permission prompt can outlast the result timeout while it waits on a human;
517
1137
  // pause the timer on request, re-arm it once the decision lands (#3920 pattern).
518
1138
  _pauseResultTimeoutForPermission() { this._clearResultTimeout() }
@@ -523,8 +1143,18 @@ export class CodexAppServerSession extends BaseSession {
523
1143
  const detail = error ? error.message : `code=${code}${signal ? ` signal=${signal}` : ''}`
524
1144
  ;(this._log || log).warn(`codex app-server exited unexpectedly (${detail})`)
525
1145
  this._processReady = false
526
- if (this._activeTurn) this._failTurn(`Codex app-server exited (${detail})`)
527
- else this.emit('error', { message: `Codex app-server exited (${detail})`, recoverable: true })
1146
+ // #6708 — app-server has no respawn, so an unexpected exit IS the terminal
1147
+ // signal. If the child died because its binary was quarantined/removed out
1148
+ // from under the running daemon, name the cause + fix instead of a bare
1149
+ // "exited (spawn … ENOENT)". Only relabels when the binary is unhealthy.
1150
+ const labeled = labelBinarySpawnFailure({
1151
+ attemptedPath: error?.path || this._spawnedBinary,
1152
+ binary: 'codex',
1153
+ prefix: 'Codex app-server exited',
1154
+ })
1155
+ const message = labeled || `Codex app-server exited (${detail})`
1156
+ if (this._activeTurn) this._failTurn(message)
1157
+ else this.emit('error', { message, recoverable: true })
528
1158
  }
529
1159
 
530
1160
  // ------------------------------------------------------------------
@@ -557,6 +1187,8 @@ export class CodexAppServerSession extends BaseSession {
557
1187
  this.clearOutgoingQueue({ emit: false })
558
1188
  this._clearIntentionalStop()
559
1189
  this._clearResultTimeout()
1190
+ this._clearReconnectWatchdog() // #6629 — never leave the reconnect timer armed past teardown
1191
+ this._clearReconnectDeadline() // #6856 — never leave the suppression deadline armed past teardown
560
1192
  this._endTurnAbort() // resolve any in-flight approval as a deny before teardown
561
1193
  try { this._permissions?.destroy() } catch { /* noop */ }
562
1194
  // #6609 — drop the materialized-attachment temp dir.