@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,604 @@
1
+ import { JsonlSubprocessSession } from './jsonl-subprocess-session.js'
2
+ import { buildBaseSessionOpts } from './base-session.js'
3
+ import { homedir } from 'os'
4
+ import { join } from 'path'
5
+ import { resolveBinary } from './utils/resolve-binary.js'
6
+ import { buildSpawnEnv } from './utils/spawn-env.js'
7
+ import {
8
+ CONTEXT_WINDOW_HEADROOM,
9
+ getRatchetCap,
10
+ maybeRatchetContextWindow,
11
+ } from './utils/context-window-learn.js'
12
+ import { BILLING_CLASSES } from './billing-class.js'
13
+ import { hasCodexOAuthCreds } from './auth-probes.js'
14
+
15
+ /**
16
+ * Manages a Codex CLI session using `codex exec --json`.
17
+ *
18
+ * Implements the same EventEmitter interface as SdkSession/CliSession so
19
+ * SessionManager and WsServer work identically regardless of provider.
20
+ *
21
+ * Codex CLI outputs JSONL events via --json flag:
22
+ * thread.started { thread_id }
23
+ * turn.started {}
24
+ * item.completed { item: { id, type, text, ... } }
25
+ * turn.completed { usage: { input_tokens, output_tokens, cached_input_tokens } }
26
+ *
27
+ * Events emitted (standard provider contract):
28
+ * ready { model }
29
+ * stream_start { messageId }
30
+ * stream_delta { messageId, delta }
31
+ * stream_end { messageId }
32
+ * tool_start { messageId, toolUseId, tool, input }
33
+ * tool_result { toolUseId, result }
34
+ * result { cost, duration, usage, sessionId }
35
+ * error { message }
36
+ */
37
+
38
+ /**
39
+ * No default model is hard-coded here.
40
+ *
41
+ * Previously this module shipped `DEFAULT_MODEL = 'gpt-5.4'`, which pinned
42
+ * the server to a specific Codex release and caused `codex exec -c model=...`
43
+ * to fail whenever that version wasn't available on the host. Instead we now
44
+ * pass `null` through to `BaseSession` when no model is supplied, and
45
+ * `buildCodexArgs()` below omits the `-c model=...` override so Codex CLI
46
+ * falls back to whatever default is configured in `~/.codex/config.toml`.
47
+ */
48
+ const DEFAULT_MODEL = null
49
+
50
+ // Resolve the codex binary once at module load. Under a GUI launch
51
+ // (e.g. Tauri on macOS) PATH is minimal and may exclude the user's
52
+ // install dir — fall through to known locations so `spawn()` succeeds.
53
+ // Covers curl|sh installers (~/.local/bin) and `npm install -g` without
54
+ // sudo (~/.npm-global/bin).
55
+ const BINARY_CANDIDATES = [
56
+ join(homedir(), '.local/bin/codex'),
57
+ '/opt/homebrew/bin/codex',
58
+ '/usr/local/bin/codex',
59
+ '/usr/bin/codex',
60
+ join(homedir(), '.npm-global/bin/codex'),
61
+ ]
62
+
63
+ const CODEX = resolveBinary('codex', BINARY_CANDIDATES)
64
+
65
+ /**
66
+ * Codex CLI sandbox modes. Source: `codex exec --sandbox <MODE>` accepts
67
+ * exactly these three values (verified against codex-cli 0.128.0). Exported
68
+ * so tests and consumers can pin the canonical list without re-declaring it.
69
+ */
70
+ export const CODEX_SANDBOX_MODES = Object.freeze([
71
+ 'read-only',
72
+ 'workspace-write',
73
+ 'danger-full-access',
74
+ ])
75
+
76
+ /**
77
+ * Default sandbox mode when nothing overrides it. Matches the #3846 stopgap
78
+ * — Codex would otherwise fall back to read-only in any non-trusted dir and
79
+ * be unable to edit files in fresh chroxy sessions.
80
+ */
81
+ export const CODEX_DEFAULT_SANDBOX = 'workspace-write'
82
+
83
+ /**
84
+ * Module-level cache of invalid `CHROXY_CODEX_SANDBOX` values we have
85
+ * already warned about (#3981). Because `resolveCodexSandbox()` runs on
86
+ * every `sendMessage()`, a single typo in an operator's environment would
87
+ * otherwise spam `console.warn` for every turn of every session for the
88
+ * lifetime of the server. We still want loud-on-first-call so the typo is
89
+ * discoverable, but bounded volume after that — one log line per distinct
90
+ * bad value per process.
91
+ *
92
+ * Keyed by the trimmed raw string so a later typo-correction to a *different*
93
+ * invalid value still surfaces. Never cleared; the set is bounded by the
94
+ * number of distinct invalid values an operator types, which in practice is
95
+ * 1 or 2.
96
+ */
97
+ const _warnedSandboxValues = new Set()
98
+
99
+ /**
100
+ * Resolve the Codex sandbox mode from the environment (#3847).
101
+ *
102
+ * Operators may pin a non-default sandbox without source edits by setting
103
+ * `CHROXY_CODEX_SANDBOX` to one of {@link CODEX_SANDBOX_MODES}. Unknown values
104
+ * log a warning (once per distinct value per process — see #3981) and fall
105
+ * back to {@link CODEX_DEFAULT_SANDBOX} — refusing to start the whole server
106
+ * would be the wrong failure mode for a stopgap env knob, and a silent
107
+ * fall-through would hide typos.
108
+ *
109
+ * Read at call time (not module-load time) so the override responds to test
110
+ * harnesses, hot reload, and in-process env changes.
111
+ *
112
+ * @returns {'read-only'|'workspace-write'|'danger-full-access'}
113
+ */
114
+ export function resolveCodexSandbox() {
115
+ const raw = process.env.CHROXY_CODEX_SANDBOX
116
+ if (typeof raw !== 'string' || raw.length === 0) return CODEX_DEFAULT_SANDBOX
117
+ const trimmed = raw.trim()
118
+ if (trimmed.length === 0) return CODEX_DEFAULT_SANDBOX
119
+ if (CODEX_SANDBOX_MODES.includes(trimmed)) return trimmed
120
+ // Case-sensitive match — Codex CLI is case-sensitive on these values, so
121
+ // silently coercing `Read-Only` would mask a typo that would have failed
122
+ // loudly downstream.
123
+ if (!_warnedSandboxValues.has(trimmed)) {
124
+ _warnedSandboxValues.add(trimmed)
125
+ console.warn(
126
+ `[codex] CHROXY_CODEX_SANDBOX="${trimmed}" is not a valid sandbox mode `
127
+ + `(expected one of: ${CODEX_SANDBOX_MODES.join(', ')}); `
128
+ + `falling back to ${CODEX_DEFAULT_SANDBOX}`,
129
+ )
130
+ }
131
+ return CODEX_DEFAULT_SANDBOX
132
+ }
133
+
134
+ /**
135
+ * Build the argv passed to `codex exec`. Exported for unit testing.
136
+ *
137
+ * `--skip-git-repo-check` is always passed: chroxy owns its own session-trust
138
+ * gate, and Codex's git-repo heuristic refuses non-git directories outright
139
+ * with a bare `exit 1`, which surfaced as an undiagnosable error in the UI
140
+ * (#3834).
141
+ *
142
+ * REVISIT (#3840): if chroxy ever grows a directory-trust prompt (i.e. a
143
+ * per-cwd "you've never opened this directory before, allow?" confirmation
144
+ * driven by chroxy's UX, distinct from the skills-content `trustStore` in
145
+ * `base-session.js`), gate this flag on that confirmation — pass it for
146
+ * trusted cwds, omit it for untrusted ones so Codex's own git-repo heuristic
147
+ * adds a second line of defense. Until that UX lands, always-on is correct
148
+ * because the user picking a cwd in chroxy IS today's trust signal.
149
+ *
150
+ * `--sandbox <mode>` is always passed (#3837 stopgap): without it Codex
151
+ * falls back to `read-only` in any directory that isn't explicitly listed
152
+ * under `[projects."…"]` with `trust_level = "trusted"` in
153
+ * `~/.codex/config.toml`, which makes Codex unable to write files in
154
+ * fresh chroxy sessions and looks like a chroxy bug. The user picking
155
+ * a directory in chroxy IS the trust signal, so `workspace-write` is the
156
+ * right default. Operators may override the default via the
157
+ * `CHROXY_CODEX_SANDBOX` env var (#3847) — e.g. on a multi-tenant host
158
+ * where Codex should start `read-only` until the user opts in. A
159
+ * per-session sandbox selector is tracked separately under #3837.
160
+ *
161
+ * SECURITY INVARIANT (#3843, #3869): `text`, `model`, and `threadId` are
162
+ * interpolated into argv passed directly to `spawn()` — no shell, so shell
163
+ * metacharacters can't escape.
164
+ *
165
+ * - `model` is interpolated into `-c model="${model}"` *without* re-validation
166
+ * here. **Callers MUST pre-validate the model ID against
167
+ * `CodexSession.getAllowedModels()` before calling.** The production gate is
168
+ * `handleSetModel` in `handlers/settings-handlers.js`, which rejects any
169
+ * value not in the per-provider allowlist before `session.setModel()`
170
+ * writes to `this.model`.
171
+ *
172
+ * - `threadId` (#3865) is **trusted because it comes from Codex CLI's own
173
+ * `thread.started` JSONL stdout** — captured in `_processJsonlLine`, never
174
+ * from user input. If a future caller wires this to a different source
175
+ * (e.g. a user-supplied resume input from the dashboard), validate it as a
176
+ * UUID first. Note that `codex exec resume <id>` silently falls back to a
177
+ * *new* thread when the id is malformed or unknown rather than erroring —
178
+ * so a "resume isn't resuming" bug report likely means the threadId path
179
+ * is wrong, not that the CLI rejected the value.
180
+ *
181
+ * If a future refactor exposes `buildCodexArgs` to a new caller (e.g. an
182
+ * alternate spawn path), preserve these invariants or add validation here.
183
+ *
184
+ * @param {string} text User prompt
185
+ * @param {string|null} model Optional model ID. Caller must validate against
186
+ * `CodexSession.getAllowedModels()`. If falsy,
187
+ * no `-c model=` flag is appended — Codex CLI
188
+ * uses its own default.
189
+ * @param {string|null} threadId Optional Codex thread_id captured from a
190
+ * previous turn's `thread.started` event.
191
+ * When set, switches to `exec resume <id>`
192
+ * form so the CLI replays prior conversation
193
+ * state instead of treating each message as
194
+ * a fresh thread (#3865).
195
+ * @returns {string[]}
196
+ */
197
+ export function buildCodexArgs(text, model, threadId = null) {
198
+ // INVARIANT: --sandbox must be passed to the parent `exec`, not to the
199
+ // `resume` subcommand. `codex exec resume --sandbox ...` errors out with
200
+ // `unexpected argument '--sandbox' found` (verified against codex-cli
201
+ // 0.128.0) because --sandbox is only declared on the parent `exec` command.
202
+ // Keep --sandbox BEFORE the `resume` subcommand on the resume path.
203
+ const sandbox = resolveCodexSandbox()
204
+ const args = threadId
205
+ ? ['exec', '--sandbox', sandbox, 'resume', threadId, text, '--json', '--skip-git-repo-check']
206
+ : ['exec', text, '--json', '--skip-git-repo-check', '--sandbox', sandbox]
207
+ if (model) {
208
+ args.push('-c', `model="${model}"`)
209
+ }
210
+ return args
211
+ }
212
+
213
+ // Per-provider model metadata — #2956.
214
+ // Source of truth for `set_model` validation, fallback model list, and
215
+ // per-model context window/label surfaced in the dashboard dropdown. Keep
216
+ // this list small and explicit until Codex CLI grows a native
217
+ // `supportedModels()` equivalent.
218
+ //
219
+ // Context-window values come from the OpenAI model docs; `contextWindow` is
220
+ // used both in the token-usage HUD and as the Codex-side override for the
221
+ // generic 200k default shipped by `models.js`.
222
+ //
223
+ // #3857: gpt-5 / gpt-5-codex bumped from 272k → 400k. The 272k value was an
224
+ // internal pre-launch limit that was never updated when OpenAI shipped the
225
+ // public 400k Codex window — surfaced as a permanent 100% footer meter at
226
+ // ~321k tokens even though Codex kept responding coherently (issue #3857,
227
+ // also captured upstream in openai/codex#19319 + community.openai.com:
228
+ // "Input tokens exceed the configured limit of 272,000 tokens"). The runtime
229
+ // learn-loop in `_processJsonlLine` ratchets these upward when the SDK
230
+ // reports an `input_tokens` value larger than the static entry, so a future
231
+ // upstream bump (1M variants on certain plans) self-corrects without
232
+ // requiring another source-code change.
233
+ const CODEX_MODEL_METADATA = Object.freeze({
234
+ 'gpt-5-codex': { label: 'GPT-5 Codex', contextWindow: 400_000 },
235
+ 'gpt-5': { label: 'GPT-5', contextWindow: 400_000 },
236
+ 'gpt-4.1': { label: 'GPT-4.1', contextWindow: 1_000_000 },
237
+ 'gpt-4o': { label: 'GPT-4o', contextWindow: 128_000 },
238
+ 'o1': { label: 'o1', contextWindow: 200_000 },
239
+ 'o3': { label: 'o3', contextWindow: 200_000 },
240
+ })
241
+
242
+ const CODEX_ALLOWED_MODELS = Object.freeze(Object.keys(CODEX_MODEL_METADATA))
243
+
244
+ const CODEX_FALLBACK_MODELS = Object.freeze(CODEX_ALLOWED_MODELS.map(id => {
245
+ const meta = CODEX_MODEL_METADATA[id]
246
+ return Object.freeze({
247
+ id,
248
+ label: meta.label,
249
+ fullId: id,
250
+ contextWindow: meta.contextWindow,
251
+ })
252
+ }))
253
+
254
+ /**
255
+ * Headroom multiplier for the learn-loop. Re-exported from the shared
256
+ * `CONTEXT_WINDOW_HEADROOM` constant in `utils/context-window-learn.js`
257
+ * (#4414) so the value lives in one place and any future provider that
258
+ * adopts the learn-loop picks up the same headroom.
259
+ *
260
+ * Kept exported under the legacy `CODEX_*` name so existing tests and any
261
+ * consumers continue to compile unchanged.
262
+ */
263
+ export const CODEX_CONTEXT_WINDOW_HEADROOM = CONTEXT_WINDOW_HEADROOM
264
+
265
+ /**
266
+ * Sanity cap on the learn-loop ratchet target for the Codex provider —
267
+ * a single `turn.completed` event with a corrupt or malicious
268
+ * `input_tokens` value (overflow, JSONL parse glitch, future Codex CLI
269
+ * bug) must not be able to balloon the registered window to an absurd
270
+ * number. 2,000,000 tokens is well above today's largest published Codex
271
+ * window (1M for gpt-4.1 / certain 1M GPT-5 variants on plan tiers).
272
+ *
273
+ * Sourced from the per-provider cap table in `utils/context-window-learn.js`
274
+ * (#4414) — bump it there if a legit future Codex model exceeds 2M.
275
+ */
276
+ export const CODEX_CONTEXT_WINDOW_RATCHET_CAP = getRatchetCap('codex')
277
+
278
+ /**
279
+ * #3857 learn-loop helper. Thin Codex-specific wrapper around the shared
280
+ * `maybeRatchetContextWindow` (#4414) so the existing test suite and any
281
+ * direct callers continue to compile unchanged.
282
+ *
283
+ * @param {import('events').EventEmitter} session The CodexSession instance
284
+ * @param {string} modelId Short id or fullId of the active Codex model
285
+ * @param {number} inputTokens `usage.input_tokens` from `turn.completed`
286
+ * @returns {boolean} true when the registry was updated, false when no-op
287
+ */
288
+ export function _maybeRatchetContextWindow(session, modelId, inputTokens) {
289
+ // #4413 persistence behavior is preserved by the shared helper, which
290
+ // calls `registry.saveCache()` after a successful update. Both Codex
291
+ // and Gemini providers route through the same path now.
292
+ return maybeRatchetContextWindow('codex', modelId, inputTokens, session.emit.bind(session))
293
+ }
294
+
295
+ export class CodexSession extends JsonlSubprocessSession {
296
+ // ------------------------------------------------------------------
297
+ // Static provider identity — required by JsonlSubprocessSession
298
+ // ------------------------------------------------------------------
299
+
300
+ static get binaryCandidates() {
301
+ return BINARY_CANDIDATES
302
+ }
303
+
304
+ static get resolvedBinary() {
305
+ return CODEX
306
+ }
307
+
308
+ static get apiKeyEnv() {
309
+ return 'OPENAI_API_KEY'
310
+ }
311
+
312
+ /**
313
+ * #6563 — Codex authenticates via OPENAI_API_KEY OR OAuth tokens cached in
314
+ * ~/.codex/auth.json by `codex login`. Reuse the SAME probe resolveAuth() and
315
+ * the preflight use so all three layers (display, runtime, preflight) agree
316
+ * that a `codex login`-only user is authenticated — start() must not throw for
317
+ * them just because the env key is unset.
318
+ */
319
+ static hasAlternativeCredentials() {
320
+ return hasCodexOAuthCreds()
321
+ }
322
+
323
+ static get providerName() {
324
+ return 'codex'
325
+ }
326
+
327
+ /**
328
+ * Human-readable label shown in the startup banner and anywhere else the
329
+ * server needs to name this provider (#2953). Each provider owns its own
330
+ * display name so `server-cli.js` no longer has to maintain a hardcoded
331
+ * `PROVIDER_LABELS` map that drifts every time a new provider lands.
332
+ */
333
+ static get displayLabel() {
334
+ return 'OpenAI Codex'
335
+ }
336
+
337
+ /**
338
+ * Root data directory for this provider (#2965).
339
+ * Consumers (conversation-scanner, ws-file-ops) use this to locate
340
+ * provider-specific subdirs (projects/, agents/, commands/) without
341
+ * hardcoding the path.
342
+ */
343
+ static get dataDir() {
344
+ return join(homedir(), '.codex')
345
+ }
346
+
347
+ static get messageIdPrefix() {
348
+ return 'codex'
349
+ }
350
+
351
+ static get capabilities() {
352
+ return {
353
+ permissions: false,
354
+ inProcessPermissions: false,
355
+ modelSwitch: true,
356
+ permissionModeSwitch: false,
357
+ planMode: false,
358
+ resume: false,
359
+ terminal: false,
360
+ thinkingLevel: false,
361
+ // #3932: declared explicitly so the capability matrix matches across
362
+ // providers — claude-tui is the only one that sets this to false.
363
+ streaming: true,
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Model IDs this provider accepts in `set_model`. Returns a plain array so
369
+ * the settings handler can surface it to the client on rejection.
370
+ * @returns {string[]}
371
+ */
372
+ static getAllowedModels() {
373
+ return CODEX_ALLOWED_MODELS
374
+ }
375
+
376
+ /**
377
+ * Minimal model list shown in the dashboard when the SDK has not pushed
378
+ * a dynamic update for this provider. Mirrors the shape returned by
379
+ * `createModelsRegistry().getModels()` so it can be dropped straight
380
+ * into the per-provider registry (#2956).
381
+ *
382
+ * @returns {ReadonlyArray<{id:string,label:string,fullId:string,contextWindow:number}>}
383
+ */
384
+ static getFallbackModels() {
385
+ return CODEX_FALLBACK_MODELS
386
+ }
387
+
388
+ /**
389
+ * Lookup metadata for a known Codex model. Returns null for unknown
390
+ * ids so the registry can fall through to its generic heuristic
391
+ * (useful when Codex adds a new model before the server is updated).
392
+ *
393
+ * @param {string} modelId
394
+ * @returns {{id:string,label:string,fullId:string,contextWindow:number,description?:string}|null}
395
+ */
396
+ static getModelMetadata(modelId) {
397
+ const meta = CODEX_MODEL_METADATA[modelId]
398
+ if (!meta) return null
399
+ return {
400
+ id: modelId,
401
+ label: meta.label,
402
+ fullId: modelId,
403
+ contextWindow: meta.contextWindow,
404
+ description: meta.description || '',
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Preflight dependency spec used by `chroxy doctor`.
410
+ */
411
+ static get preflight() {
412
+ return {
413
+ label: 'Codex',
414
+ binary: {
415
+ name: 'codex',
416
+ args: ['--version'],
417
+ candidates: BINARY_CANDIDATES,
418
+ installHint: 'install Codex CLI',
419
+ },
420
+ credentials: {
421
+ envVars: ['OPENAI_API_KEY'],
422
+ hint: 'set OPENAI_API_KEY',
423
+ // #6563: the env var is OPTIONAL when OAuth creds exist (`codex login`),
424
+ // so `chroxy doctor` downgrades the missing env var from fail→warn instead
425
+ // of a hard credentials failure — doctor can't read the OAuth token, but it
426
+ // must not report a false failure when resolveAuth() is ready on OAuth. Same
427
+ // probe as resolveAuth() + hasAlternativeCredentials() → one definition of
428
+ // "has a usable credential".
429
+ optional: hasCodexOAuthCreds(),
430
+ },
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Resolve runtime auth state for the dashboard (#4769).
436
+ *
437
+ * Codex authenticates via OPENAI_API_KEY env OR the OAuth tokens cached
438
+ * under `~/.codex/auth.json` by `codex login`. The CLI works fine even
439
+ * when the file's OPENAI_API_KEY field is null because the tokens block
440
+ * carries the round-trip (#4301). Env wins; OAuth file fallback covers
441
+ * users who logged in via the CLI instead of exporting a key.
442
+ *
443
+ * @param {NodeJS.ProcessEnv} env
444
+ * @param {{ hasCodexOAuthCreds: () => boolean }} helpers
445
+ * @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string}}
446
+ */
447
+ static resolveAuth(env, helpers) {
448
+ const credSpec = this.preflight.credentials
449
+ const envVars = credSpec.envVars
450
+ const hint = credSpec.hint || `set ${envVars.join(' or ')}`
451
+
452
+ const matched = envVars.find(v => env[v])
453
+ if (matched) {
454
+ return {
455
+ ready: true,
456
+ source: 'env',
457
+ envVar: matched,
458
+ envVars,
459
+ hint: '',
460
+ detail: `OpenAI API (${matched} set)`,
461
+ billingClass: BILLING_CLASSES.API_KEY,
462
+ }
463
+ }
464
+ if (helpers.hasCodexOAuthCreds()) {
465
+ return {
466
+ ready: true,
467
+ source: 'oauth',
468
+ envVar: null,
469
+ envVars,
470
+ hint,
471
+ detail: 'OpenAI API (OAuth from `codex login`)',
472
+ billingClass: BILLING_CLASSES.API_KEY,
473
+ }
474
+ }
475
+ const resolvedHint = hint
476
+ ? `${hint} or run \`codex login\``
477
+ : 'run `codex login` or set OPENAI_API_KEY'
478
+ return {
479
+ ready: false,
480
+ source: 'none',
481
+ envVar: null,
482
+ envVars,
483
+ hint: resolvedHint,
484
+ detail: envVars.length ? `Not configured — ${resolvedHint}` : 'Not configured',
485
+ // Non-Claude provider — always per-token api-key billing, era-independent.
486
+ billingClass: BILLING_CLASSES.API_KEY,
487
+ }
488
+ }
489
+
490
+ constructor(opts = {}) {
491
+ // `model` may be null/undefined — BaseSession coerces to null and
492
+ // _buildArgs() omits the `-c model=...` flag so Codex CLI defers
493
+ // to its own default from ~/.codex/config.toml.
494
+ // #5367: forward every BaseSession opt via the canonical picker (which
495
+ // preserves the #3899 hardTimeoutMs / #4790 streamStallTimeoutMs plumbing
496
+ // that used to be hand-maintained here). Overrides: provider default,
497
+ // `model || DEFAULT_MODEL`, and `resumeSessionId` — the last is a
498
+ // JsonlSubprocessSession-local opt (not a BaseSession key) so it must ride
499
+ // through the overrides bag to reach the middle layer.
500
+ super(buildBaseSessionOpts(opts, {
501
+ provider: opts.provider || 'codex',
502
+ model: opts.model || DEFAULT_MODEL,
503
+ resumeSessionId: opts.resumeSessionId,
504
+ }))
505
+ }
506
+
507
+ // ------------------------------------------------------------------
508
+ // JsonlSubprocessSession overrides
509
+ // ------------------------------------------------------------------
510
+
511
+ _buildArgs(text) {
512
+ return buildCodexArgs(text, this.model, this.resumeSessionId)
513
+ }
514
+
515
+ _buildChildEnv() {
516
+ return buildSpawnEnv('codex')
517
+ }
518
+
519
+ _processJsonlLine(event, ctx) {
520
+ if (!event.type) return
521
+
522
+ switch (event.type) {
523
+ case 'thread.started': {
524
+ // Codex CLI emits this as the first JSONL line of every `codex exec`
525
+ // invocation. Capturing thread_id is what lets subsequent turns
526
+ // resume the conversation (#3865) — without it, every sendMessage
527
+ // spawns `codex exec "<prompt>"` with no prior context.
528
+ if (event.thread_id) {
529
+ this.resumeSessionId = event.thread_id
530
+ }
531
+ break
532
+ }
533
+
534
+ case 'item.completed': {
535
+ const item = event.item
536
+ if (!item) break
537
+
538
+ if (item.type === 'agent_message' && item.text) {
539
+ if (!ctx.didStreamStart) {
540
+ this.emit('stream_start', { messageId: ctx.messageId })
541
+ ctx.didStreamStart = true
542
+ }
543
+ this.emit('stream_delta', { messageId: ctx.messageId, delta: item.text })
544
+ } else if (item.type === 'tool_call') {
545
+ const toolMessageId = `codex-tool-${++this._messageCounter}`
546
+ this.emit('tool_start', {
547
+ messageId: toolMessageId,
548
+ toolUseId: item.id || toolMessageId,
549
+ tool: item.name || 'unknown',
550
+ input: item.arguments || item.input || {},
551
+ })
552
+ } else if (item.type === 'tool_output') {
553
+ this.emit('tool_result', {
554
+ toolUseId: item.call_id || item.id || `codex-tool-${this._messageCounter}`,
555
+ result: item.output || item.text || '',
556
+ })
557
+ }
558
+ break
559
+ }
560
+
561
+ case 'turn.completed': {
562
+ ctx.didEmitResult = true
563
+ // End stream before result (standard provider contract)
564
+ if (ctx.didStreamStart) {
565
+ this.emit('stream_end', { messageId: ctx.messageId })
566
+ ctx.didStreamStart = false
567
+ }
568
+ const usage = event.usage || {}
569
+ const inputTokens = usage.input_tokens || 0
570
+ const outputTokens = usage.output_tokens || 0
571
+ // #3857 learn-loop: when Codex reports an `input_tokens` value that
572
+ // exceeds the registered context window for the active model, the
573
+ // static window is stale (this is exactly how we found the original
574
+ // 272k drift — 321k turns kept succeeding past 100%). Ratchet the
575
+ // registry upward to at least `input_tokens * 1.1` so the next turn's
576
+ // meter reflects reality, and emit `models_updated` so connected
577
+ // dashboards pick up the corrected value without waiting for a
578
+ // refresh. Mirrors the Claude path in sdk-session.js:741 — except
579
+ // the SDK there has an explicit `contextWindow` field; here we infer
580
+ // it from the observed token count.
581
+ //
582
+ // Only ratchets *up* — a single small turn must never shrink the
583
+ // registered window (the model didn't change, only the prompt size
584
+ // for this one turn did).
585
+ if (this.model && inputTokens > 0) {
586
+ _maybeRatchetContextWindow(this, this.model, inputTokens)
587
+ }
588
+ this.emit('result', {
589
+ cost: null,
590
+ duration: null,
591
+ usage: {
592
+ input_tokens: inputTokens,
593
+ output_tokens: outputTokens,
594
+ },
595
+ sessionId: this.resumeSessionId,
596
+ })
597
+ break
598
+ }
599
+
600
+ default:
601
+ break
602
+ }
603
+ }
604
+ }