@jbkjr/relay 0.0.0-stage → 1.2.1

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 (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +386 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1525 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +320 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +637 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +329 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +629 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1502 -0
  186. package/docs/pinned-codex.md +321 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
@@ -0,0 +1,479 @@
1
+ // The stub's Codex CLI: `codex app-server` (JSON-RPC, with approval requests sent to the client),
2
+ // `codex exec --json` (no approval channel: the action is simply denied), and `codex mcp list`.
3
+ import { emit, loadSession, record, runSteps, SEEN_ENV, stubborn } from "../stub-agent.mjs";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+
7
+ const archiveFile = (id) => path.join(process.env.STUB_DIR, "sessions", `codex-${id}.archived`);
8
+ const sessionFile = (id) => path.join(process.env.STUB_DIR, "sessions", `codex-${id}.json`);
9
+ /** The model a thread is started on when it names none: Codex's default at the time (STUB_CODEX_NEW_THREAD_MODEL), else the stub's own. */
10
+ const newThreadModel = () => process.env.STUB_CODEX_NEW_THREAD_MODEL ?? "gpt-stub";
11
+
12
+ /**
13
+ * Codex's fast_mode feature as this server has it, or undefined where nothing sets it (on, as in
14
+ * Codex 0.163.0): a layer above relay's flags (STUB_CODEX_EFFECTIVE features) first, then relay's
15
+ * -c features.fast_mode, then the person's own config (STUB_CODEX_FEATURES), which relay's flags
16
+ * outrank. With it off, Codex 0.163.0 drops every service tier, "default" included.
17
+ */
18
+ function fastMode(c) {
19
+ const above = JSON.parse(process.env.STUB_CODEX_EFFECTIVE ?? "{}").features?.fast_mode;
20
+ if (typeof above === "boolean") return above;
21
+ if (Object.prototype.hasOwnProperty.call(c, "features.fast_mode")) return c["features.fast_mode"] === true;
22
+ const own = JSON.parse(process.env.STUB_CODEX_FEATURES ?? "{}").fast_mode;
23
+ return typeof own === "boolean" ? own : undefined;
24
+ }
25
+
26
+ /**
27
+ * A -c value as Codex parses it (TOML; the raw text where it is not), for the TOML relay writes:
28
+ * strings, booleans, numbers, arrays and inline tables whose keys are quoted.
29
+ */
30
+ function tomlValue(raw) {
31
+ let json = "";
32
+ let inString = false;
33
+ for (let i = 0; i < raw.length; i++) {
34
+ const ch = raw[i];
35
+ if (inString) {
36
+ json += ch;
37
+ if (ch === "\\") json += raw[++i];
38
+ else if (ch === '"') inString = false;
39
+ } else if (ch === '"') { inString = true; json += ch; }
40
+ else json += ch === "=" ? ":" : ch;
41
+ }
42
+ try { return JSON.parse(json); } catch { return raw; }
43
+ }
44
+
45
+ /** The permission profile a server started with these -c values selects, as Codex 0.163.0 reads it, or null for a built-in one. */
46
+ function profileOf(cfg) {
47
+ const id = cfg.default_permissions;
48
+ if (typeof id !== "string" || id.startsWith(":")) return null;
49
+ const at = `permissions.${id}.`;
50
+ const profile = {};
51
+ for (const [k, v] of Object.entries(cfg)) if (k.startsWith(at)) {
52
+ const keys = k.slice(at.length).split(".");
53
+ let o = profile;
54
+ for (const key of keys.slice(0, -1)) o = o[key] ??= {};
55
+ o[keys.at(-1)] = v;
56
+ }
57
+ return profile;
58
+ }
59
+
60
+ /** What a profile allows: read, write or danger (no sandbox), as the stub's steps use it. */
61
+ function accessOf(id, profile) {
62
+ if (id === ":danger-full-access") return "danger";
63
+ if (id === ":read-only") return "read";
64
+ if (!profile) return "unknown";
65
+ return profile.filesystem?.[":workspace_roots"]?.["."] === "write" ? "write" : "read";
66
+ }
67
+
68
+ /** The legacy description of a thread's sandbox (SandboxPolicy) the real server reports for a profile. */
69
+ function sandboxOf(id, profile, extraRoots = []) {
70
+ const access = accessOf(id, profile);
71
+ if (access === "danger") return { type: "dangerFullAccess" };
72
+ const networkAccess = profile?.network?.enabled === true;
73
+ if (access === "read") return { type: "readOnly", networkAccess };
74
+ // Writable: the profile's own roots and every workspace root of the thread but its directory (`:workspace_roots` "." = write).
75
+ return { type: "workspaceWrite", writableRoots: [...new Set([...Object.keys(profile?.workspace_roots ?? {}), ...extraRoots])], networkAccess, excludeTmpdirEnvVar: profile?.filesystem?.[":tmpdir"] !== "write", excludeSlashTmp: profile?.filesystem?.[":slash_tmp"] !== "write" };
76
+ }
77
+
78
+ /** A profile as config/read reports it: every key Codex knows and nothing set to it null. */
79
+ function reportedProfile(profile) {
80
+ if (!profile) return null;
81
+ const { glob_scan_max_depth = null, ...entries } = profile.filesystem ?? {};
82
+ return {
83
+ description: profile.description ?? null, extends: profile.extends ?? null, workspace_roots: profile.workspace_roots ?? null,
84
+ filesystem: profile.filesystem ? { glob_scan_max_depth, ...entries } : null,
85
+ network: profile.network ? { enabled: null, proxy_url: null, mode: null, domains: null, ...profile.network } : null,
86
+ };
87
+ }
88
+
89
+ function parseCodex(argv) {
90
+ const cfg = {};
91
+ for (let i = 0; i < argv.length; i++) {
92
+ if (argv[i] !== "-c") continue;
93
+ const eq = argv[i + 1].indexOf("=");
94
+ const key = argv[i + 1].slice(0, eq);
95
+ const raw = argv[i + 1].slice(eq + 1);
96
+ // Inline tables only where relay writes them for a profile; other keys as before (skills.config stays its text).
97
+ let value = raw;
98
+ if (key.startsWith("permissions.")) value = tomlValue(raw);
99
+ else try { value = JSON.parse(raw); } catch {}
100
+ cfg[key] = value;
101
+ }
102
+ const resumed = argv[1] === "resume";
103
+ if (resumed && fs.existsSync(archiveFile(argv[argv.length - 2]))) throw new Error("cannot resume an archived thread");
104
+ const env = {};
105
+ for (const [k, v] of Object.entries(cfg)) if (k.startsWith("mcp_servers.relay.env.")) env[k.slice("mcp_servers.relay.env.".length)] = v;
106
+ const relay = cfg["mcp_servers.relay.command"] && cfg["mcp_servers.relay.enabled"] !== false
107
+ ? { command: cfg["mcp_servers.relay.command"], args: cfg["mcp_servers.relay.args"] ?? [], env, env_vars: cfg["mcp_servers.relay.env_vars"] ?? [] }
108
+ : undefined;
109
+ const profile = profileOf(cfg);
110
+ return {
111
+ sessionId: resumed ? argv[argv.length - 2] : undefined, resumed, relay, cfg, profile,
112
+ access: accessOf(cfg.default_permissions, profile),
113
+ };
114
+ }
115
+
116
+ /** Emulates `codex app-server`: JSON-RPC over stdio, with approval requests sent to the client. */
117
+ async function appServer(argv) {
118
+ const parsed = parseCodex(argv);
119
+ const out = (m) => process.stdout.write(JSON.stringify(m) + "\n");
120
+ const answers = new Map();
121
+ let nextId = 1000;
122
+ let session = null;
123
+ let threadParams = null;
124
+ /** Skill roots added to this server (skills/extraRoots/set). */
125
+ let extraRoots = [];
126
+ /** Whether the client turned on the experimental API (initialize), which thread/start's `permissions` needs. */
127
+ let experimental = false;
128
+ const rl = (await import("node:readline")).createInterface({ input: process.stdin });
129
+ // STUB_CODEX_RPC_DELAY_MS: every request from relay is answered that much later (the benchmark's
130
+ // diagnostic, scripts/bench: it exposes how many requests are on a turn's critical path). Off by default.
131
+ const rpcDelay = Number(process.env.STUB_CODEX_RPC_DELAY_MS ?? 0);
132
+ for await (const line of rl) {
133
+ let m; try { m = JSON.parse(line); } catch { continue; }
134
+ if (m.id !== undefined && m.method === undefined) { answers.get(m.id)?.(m.result ?? { error: m.error }); continue; }
135
+ if (rpcDelay > 0 && m.id !== undefined) await new Promise((r) => setTimeout(r, rpcDelay));
136
+ if (m.method === "initialize") { experimental = m.params?.capabilities?.experimentalApi === true; record({ event: "codex-initialize", capabilities: m.params?.capabilities ?? null }); out({ id: m.id, result: { userAgent: "stub" } }); continue; }
137
+ // An administrator's requirements, as the real server reports them (ConfigRequirementsReadResponse): none, unless a test sets some.
138
+ if (m.method === "configRequirements/read") {
139
+ if (process.env.STUB_CODEX_REQUIREMENTS_ERROR) { out({ id: m.id, error: { code: -32000, message: process.env.STUB_CODEX_REQUIREMENTS_ERROR } }); continue; }
140
+ out({ id: m.id, result: { supportsIndependentSpeedModes: true, requirements: JSON.parse(process.env.STUB_CODEX_REQUIREMENTS ?? "null") } });
141
+ continue;
142
+ }
143
+ if (m.method === "config/read") {
144
+ // What reached the server, for a test of the environment a preflight gets (STUB_RECORD_CONFIG_READ),
145
+ // and a server that never answers, for a test of a preflight that hangs (STUB_CODEX_HANG_CONFIG).
146
+ if (process.env.STUB_RECORD_CONFIG_READ) record({ event: "config-read", target: "codex", env: SEEN_ENV, node: process.env.RELAY_NODE_ID ?? null });
147
+ if (process.env.STUB_CODEX_HANG_CONFIG) continue;
148
+ // The effective configuration, built from the flags this server was started with. A test can
149
+ // overlay values to stand in for a layer that outranks relay's flags.
150
+ const c = parsed.cfg;
151
+ const servers = {};
152
+ for (const [k, v] of Object.entries(c)) {
153
+ const mm = /^mcp_servers\.("?)(.+?)\1\.(enabled|command|args)$/.exec(k);
154
+ if (mm) (servers[mm[2]] ??= {})[mm[3]] = v;
155
+ const me = /^mcp_servers\.relay\.env\.(.+)$/.exec(k);
156
+ if (me) ((servers.relay ??= {}).env ??= {})[me[1]] = v;
157
+ }
158
+ const has = (k) => Object.prototype.hasOwnProperty.call(c, k);
159
+ // shell_environment_policy as Codex 0.163.0 reports it: as configured, every unset field null
160
+ // (Codex's defaults). STUB_CODEX_SHELL_POLICY replaces it with a test's own (JSON), or leaves
161
+ // it out ("omit"), as a server that does not report it.
162
+ const shellPolicy = process.env.STUB_CODEX_SHELL_POLICY === undefined
163
+ ? { inherit: null, ignore_default_excludes: null, exclude: null, set: null, include_only: null, filters: null, experimental_use_profile: null }
164
+ : JSON.parse(process.env.STUB_CODEX_SHELL_POLICY);
165
+ const config = {
166
+ ...(shellPolicy === "omit" ? {} : { shell_environment_policy: shellPolicy }),
167
+ ...(has("daybreak") ? { daybreak: c.daybreak } : {}),
168
+ sandbox_mode: c.sandbox_mode ?? null, approvals_reviewer: c.approvals_reviewer, service_tier: c.service_tier ?? null, web_search: c.web_search ?? "indexed",
169
+ default_permissions: c.default_permissions ?? null,
170
+ permissions: parsed.profile ? { [c.default_permissions]: reportedProfile(parsed.profile) } : null,
171
+ sandbox_workspace_write: null,
172
+ mcp_servers: servers,
173
+ // Every --disable and --enable the server was started with, as the real one reports features set.
174
+ features: {
175
+ plugins: true, hooks: true, ...Object.fromEntries(argv.flatMap((a, i) => (a === "--disable" || a === "--enable" ? [[argv[i + 1], a === "--enable"]] : []))),
176
+ // Every -c features.<key> as given, as the real server echoes them, known or not.
177
+ ...Object.fromEntries(Object.entries(c).filter(([k]) => k.startsWith("features.") && k !== "features.fast_mode").map(([k, v]) => [k.slice("features.".length), v])),
178
+ ...(fastMode(c) === undefined ? {} : { fast_mode: fastMode(c) }),
179
+ },
180
+ ...(has("skills.config") ? { skills: { config: c["skills.config"] } } : {}),
181
+ ...JSON.parse(process.env.STUB_CODEX_EFFECTIVE ?? "{}"),
182
+ };
183
+ out({ id: m.id, result: { config, origins: {} } });
184
+ continue;
185
+ }
186
+ if (m.method === "initialized") continue;
187
+ // The features this server runs with, as the real one lists them (ExperimentalFeatureListResponse,
188
+ // Codex 0.164.0): only keys it knows, network_proxy and request_permissions_tool among them, on as
189
+ // the -c flags set them. STUB_CODEX_FEATURE_LIST replaces the list (JSON), or makes the call fail ("error").
190
+ if (m.method === "experimentalFeature/list") {
191
+ record({ event: "feature-list", target: "codex" });
192
+ if (process.env.STUB_CODEX_FEATURE_LIST === "error") { out({ id: m.id, error: { code: -32601, message: "method not found" } }); continue; }
193
+ const on = (k) => parsed.cfg[`features.${k}`] === true;
194
+ const data = JSON.parse(process.env.STUB_CODEX_FEATURE_LIST ?? "null") ?? [
195
+ { name: "exec_permission_approvals", stage: "underDevelopment", enabled: on("exec_permission_approvals"), defaultEnabled: false },
196
+ { name: "request_permissions_tool", stage: "underDevelopment", enabled: on("request_permissions_tool"), defaultEnabled: false },
197
+ { name: "network_proxy", stage: "beta", enabled: on("network_proxy"), defaultEnabled: false },
198
+ ];
199
+ out({ id: m.id, result: { data, nextCursor: null } });
200
+ continue;
201
+ }
202
+ // A command Codex runs in a sandbox of this server's profile (command/exec): relay's network check.
203
+ // What the real server's sandbox would make of it (codex-network.ts CANARY_SCRIPT), from the
204
+ // profile and the proxy feature; STUB_CODEX_CANARY replaces the output (JSON), or fails the call ("error").
205
+ if (m.method === "command/exec") {
206
+ record({ event: "command-exec", target: "codex", params: m.params, cwd: m.params?.cwd ?? null });
207
+ if (process.env.STUB_CODEX_CANARY === "error") { out({ id: m.id, error: { code: -32000, message: "failed to start managed network proxy" } }); continue; }
208
+ const net = parsed.profile?.network ?? {};
209
+ const proxied = net.enabled === true && parsed.cfg["features.network_proxy"] === true;
210
+ const local = net.allow_local_binding === true;
211
+ // STUB_CODEX_CANARY_LATER: the output from the second command/exec of the job on (a file in STUB_DIR counts them).
212
+ const counter = path.join(process.env.STUB_DIR, "codex-command-exec-count");
213
+ const seen = fs.existsSync(counter) ? Number(fs.readFileSync(counter, "utf8")) : 0;
214
+ fs.writeFileSync(counter, String(seen + 1));
215
+ const later = seen >= 1 && process.env.STUB_CODEX_CANARY_LATER ? process.env.STUB_CODEX_CANARY_LATER : null;
216
+ const result = later ? JSON.parse(later) : process.env.STUB_CODEX_CANARY ? JSON.parse(process.env.STUB_CODEX_CANARY)
217
+ : !net.enabled ? { proxy: null, loop: "EPERM", unix: "EPERM", viaProxy: "no proxy" }
218
+ : !proxied ? { proxy: null, loop: "connected", unix: "connected", viaProxy: "no proxy" }
219
+ : { proxy: "http://127.0.0.1:61000", loop: local ? "connected" : "EPERM", unix: "EPERM", viaProxy: local ? "HTTP/1.1 200 OK" : "HTTP/1.1 403 Forbidden" };
220
+ out({ id: m.id, result: { exitCode: 0, stdout: JSON.stringify(result) + "\n", stderr: "" } });
221
+ continue;
222
+ }
223
+ // Skills as codex-cli 0.163.0 finds them (observed under a scratch CODEX_HOME and HOME): the
224
+ // person's ($CODEX_HOME/skills without .system, ~/.agents/skills), the repository's (.agents/skills
225
+ // and .codex/skills in the turn's directory and each one above it up to the repository's top),
226
+ // every directory up to six levels below one of those that holds a file named exactly SKILL.md
227
+ // (inside another skill's directory too, never in a dot-directory), Codex's own system skill,
228
+ // extra roots set on this server (left out under STUB_CODEX_DROP_ROOTS, as if Codex did not take
229
+ // them; a root whose parent holds .claude-plugin/plugin.json has its skills named
230
+ // <plugin>:<name>, as 0.163.0 names them), and any a test adds (STUB_CODEX_SKILLS, or
231
+ // STUB_CODEX_IN_ROOT under the first extra root), each switched off by a skills.config entry
232
+ // naming its SKILL.md.
233
+ if (m.method === "skills/extraRoots/set") { extraRoots = m.params.extraRoots ?? []; out({ id: m.id, result: {} }); continue; }
234
+ if (m.method === "skills/list") {
235
+ const cwd = m.params?.cwds?.[0] ?? process.cwd();
236
+ const codexHome = process.env.CODEX_HOME || path.join(process.env.HOME ?? "", ".codex");
237
+ const off = new Set([...String(parsed.cfg["skills.config"] ?? "").matchAll(/path="((?:[^"\\]|\\.)*)",enabled=false/g)].map((x) => JSON.parse(`"${x[1]}"`)));
238
+ const found = [];
239
+ const scan = (dir, scope, depth = 0, prefix = "") => {
240
+ if (!fs.existsSync(dir)) return;
241
+ for (const n of fs.readdirSync(dir).sort()) {
242
+ const sub = path.join(dir, n);
243
+ if (n.startsWith(".") || !fs.statSync(sub).isDirectory()) continue;
244
+ if (fs.readdirSync(sub).includes("SKILL.md")) found.push({ name: `${prefix}${n}`, path: path.join(sub, "SKILL.md"), scope });
245
+ if (depth + 1 < 6) scan(sub, scope, depth + 1, prefix);
246
+ }
247
+ };
248
+ const pluginOf = (root) => {
249
+ try {
250
+ return JSON.parse(fs.readFileSync(path.join(path.dirname(root), ".claude-plugin", "plugin.json"), "utf8")).name;
251
+ } catch {
252
+ return null;
253
+ }
254
+ };
255
+ scan(path.join(codexHome, "skills"), "user");
256
+ scan(path.join(process.env.HOME ?? "", ".agents", "skills"), "user");
257
+ for (let d = path.resolve(cwd); ; d = path.dirname(d)) {
258
+ scan(path.join(d, ".agents", "skills"), "repo");
259
+ scan(path.join(d, ".codex", "skills"), "repo");
260
+ if (fs.existsSync(path.join(d, ".git")) || path.dirname(d) === d) break;
261
+ }
262
+ if (!process.env.STUB_CODEX_DROP_ROOTS) for (const r of extraRoots) scan(r, "user", 0, pluginOf(r) ? `${pluginOf(r)}:` : "");
263
+ found.push({ name: "openai-docs", path: path.join(codexHome, "skills", ".system", "openai-docs", "SKILL.md"), scope: "system" });
264
+ found.push(...JSON.parse(process.env.STUB_CODEX_SKILLS ?? "[]"));
265
+ if (extraRoots.length) found.push(...JSON.parse(process.env.STUB_CODEX_IN_ROOT ?? "[]").map((x) => ({ name: x.name, path: path.join(extraRoots[0], x.rel), scope: "user" })));
266
+ const real = (p) => { try { return fs.realpathSync(p); } catch { return p; } };
267
+ const skills = found.map((f) => ({ name: f.name, description: "", path: f.path, scope: f.scope, enabled: !off.has(f.path) && !off.has(real(f.path)), pluginId: null }));
268
+ const read = (p) => { try { return fs.readFileSync(p, "utf8"); } catch { return null; } };
269
+ const copies = Object.fromEntries(skills.filter((sk) => extraRoots.some((r) => sk.path.startsWith(r))).map((sk) => [sk.name, read(sk.path)]));
270
+ record({ event: "skills-list", target: "codex", cwd, found: skills.map((sk) => sk.name), enabled: skills.filter((sk) => sk.enabled).map((sk) => sk.name), roots: extraRoots, plugins: extraRoots.map(pluginOf), copies });
271
+ out({ id: m.id, result: { data: [{ cwd, skills, errors: [] }] } });
272
+ continue;
273
+ }
274
+ if (m.method === "account/read") {
275
+ const type = process.env.STUB_ACCOUNT ?? "chatgpt";
276
+ out({ id: m.id, result: { account: process.env.STUB_ACCOUNT === "none" ? null : { type, ...(type === "chatgpt" ? { planType: process.env.STUB_CODEX_PLAN ?? "prolite" } : {}) }, requiresOpenaiAuth: true } });
277
+ continue;
278
+ }
279
+ // The account's model catalog, as the real server lists it (ModelListResponse, Codex 0.163.0): each model's
280
+ // service tiers by catalog id. By default one model, the stub's own, offering fast (priority) only; a test can replace it.
281
+ // STUB_CODEX_MODEL_PAGES, a list of such lists, is the catalog in pages, as the real server pages it (cursor, nextCursor).
282
+ if (m.method === "model/list") {
283
+ record({ event: "model-list", target: "codex", params: m.params });
284
+ // A server or account whose catalog cannot be read (STUB_CODEX_MODEL_LIST_ERROR, the error's message).
285
+ if (process.env.STUB_CODEX_MODEL_LIST_ERROR) { out({ id: m.id, error: { code: -32000, message: process.env.STUB_CODEX_MODEL_LIST_ERROR } }); continue; }
286
+ let cached = null;
287
+ try {
288
+ cached = JSON.parse(fs.readFileSync(path.join(process.env.CODEX_HOME || path.join(process.env.HOME, ".codex"), "models_cache.json"), "utf8")).models?.map((m) => ({
289
+ id: m.slug, model: m.slug, availableAccessPrograms: { cyber: m.available_access_programs?.cyber?.map((p) => p === "daybreak_blue" ? "daybreakBlue" : p) ?? [] },
290
+ }));
291
+ } catch { /* Ordinary tests use the stub's default catalog. */ }
292
+ const pages = JSON.parse(process.env.STUB_CODEX_MODEL_PAGES ?? "null") ?? [JSON.parse(process.env.STUB_CODEX_MODELS ?? "null") ?? cached ?? [
293
+ { id: "gpt-stub", model: "gpt-stub", displayName: "GPT-Stub", hidden: false, isDefault: true, serviceTiers: [{ id: "priority", name: "Fast", description: "2x speed, increased usage" }], defaultServiceTier: null },
294
+ ]];
295
+ const page = m.params?.cursor ? Number(m.params.cursor) : 0;
296
+ // A hidden model is listed only when asked for (includeHidden), as the real server does.
297
+ const data = (pages[page] ?? []).filter((model) => m.params?.includeHidden === true || !model.hidden);
298
+ out({ id: m.id, result: { data, nextCursor: page + 1 < pages.length ? String(page + 1) : null } });
299
+ continue;
300
+ }
301
+ // A thread's stored metadata, as the real server reads it (ThreadReadParams, ThreadReadResponse; Codex 0.163.0): its model among them.
302
+ if (m.method === "thread/read") {
303
+ record({ event: "thread-read", target: "codex", params: m.params });
304
+ const file = sessionFile(m.params.threadId);
305
+ if (!fs.existsSync(file)) { out({ id: m.id, error: { code: -32600, message: `no rollout found for thread id ${m.params.threadId}` } }); continue; }
306
+ const sess = JSON.parse(fs.readFileSync(file, "utf8"));
307
+ out({ id: m.id, result: { thread: { id: m.params.threadId, model: sess.model ?? newThreadModel(), modelProvider: "openai" } } });
308
+ continue;
309
+ }
310
+ if (m.method === "thread/archive" || m.method === "thread/unarchive") {
311
+ const id = m.params.threadId;
312
+ const archived = archiveFile(id);
313
+ if (m.method === "thread/archive" && process.env.STUB_CODEX_ARCHIVE_ERROR) {
314
+ const error = process.env.STUB_CODEX_ARCHIVE_ERROR;
315
+ out({ id: m.id, error: { code: -32000, message: error === "ENOSPC" ? "disk full" : error } }); continue;
316
+ }
317
+ if (m.method === "thread/unarchive" && !fs.existsSync(archived)) {
318
+ out({ id: m.id, error: { code: -32600, message: `no archived rollout found for thread id ${id}` } }); continue;
319
+ }
320
+ if (m.method === "thread/archive") fs.writeFileSync(archived, "");
321
+ else fs.unlinkSync(archived);
322
+ record({ event: m.method, target: "codex", sessionId: id });
323
+ out({ id: m.id, result: {} }); continue;
324
+ }
325
+ if (m.method === "thread/start" || m.method === "thread/resume") {
326
+ // As the real server checks them (0.163.0): a profile named on the thread needs the experimental API, and excludes `sandbox`.
327
+ if (m.params.permissions !== undefined && !experimental) { out({ id: m.id, error: { code: -32600, message: `${m.method}.permissions requires experimentalApi capability` } }); continue; }
328
+ if (m.params.permissions !== undefined && m.params.sandbox !== undefined) { out({ id: m.id, error: { code: -32600, message: "`permissions` cannot be combined with `sandbox`" } }); continue; }
329
+ threadParams = m.params;
330
+ const resumed = m.method === "thread/resume";
331
+ if (resumed && fs.existsSync(archiveFile(m.params.threadId))) {
332
+ out({ id: m.id, error: { code: -32600, message: `session ${m.params.threadId} is archived. Unarchive it first.` } }); continue;
333
+ }
334
+ session = loadSession("codex", { sessionId: resumed ? m.params.threadId : undefined, resumed });
335
+ if (session.missing) { out({ id: m.id, error: { code: -32000, message: `no thread ${m.params.threadId}` } }); continue; }
336
+ session.resumed = resumed;
337
+ // A resumed thread's past turns, as the real server returns them (0.163.0 and 0.164.0 thread/resume excludeTurns):
338
+ // in the reply, after a deprecation notice as for a thread whose history is paginated (the threads relay starts
339
+ // are, under both versions), unless it is told to leave them out.
340
+ const full = resumed && m.params.excludeTurns !== true;
341
+ if (full) out({ method: "deprecationNotice", params: { summary: "Full-history hydration is deprecated for paginated threads; use `excludeTurns: true`, then page with `thread/turns/list` and `thread/items/list`.", details: null } });
342
+ const pastTurns = full ? Array.from({ length: session.sess.turns - 1 }, (_, i) => ({ id: `turn_${i + 1}`, items: [], status: "completed" })) : [];
343
+ // As the real server reports it: the model the thread will use and its provider. A test can overlay them.
344
+ // The service tier as the real server reports it (Codex 0.163.0): the one asked for, or null for one it does not know.
345
+ // With its fast_mode feature off, none at all.
346
+ const tier = fastMode(parsed.cfg) !== false && typeof m.params.serviceTier === "string" && ["default", "priority", "ultrafast"].includes(m.params.serviceTier) ? m.params.serviceTier : null;
347
+ // The model: the one asked for, else, resumed, the thread's own (as Codex restores it), else the default.
348
+ const model = m.params.model ?? (resumed ? session.sess.model : undefined) ?? newThreadModel();
349
+ session.sess.model = model;
350
+ // The thread's workspace roots, as the real server keeps them (0.163.0 thread/resume): the ones it is
351
+ // told, else on resume the ones the thread stored, else its directory. A server that ignores the ones
352
+ // it is told (STUB_CODEX_IGNORE_ROOTS, or a file codex-ignore-roots in STUB_DIR) restores the stored ones; a test can store others in the thread's file.
353
+ const cwd = m.params.cwd ?? process.cwd();
354
+ const ignore = process.env.STUB_CODEX_IGNORE_ROOTS || fs.existsSync(path.join(process.env.STUB_DIR, "codex-ignore-roots"));
355
+ const told = ignore ? undefined : m.params.runtimeWorkspaceRoots;
356
+ const roots = told ?? (resumed ? session.sess.roots : undefined) ?? [cwd];
357
+ session.sess.roots = roots;
358
+ fs.writeFileSync(sessionFile(session.sessionId), JSON.stringify(session.sess));
359
+ // STUB_CODEX_THREAD_OMIT: keys the result leaves out, for a server that does not report them.
360
+ // The profile the thread runs with: the one it names, else the one the server's config selects; and the legacy description of its sandbox.
361
+ const active = m.params.permissions ?? parsed.cfg.default_permissions;
362
+ const sandbox = sandboxOf(active, parsed.profile, roots.filter((r) => r !== cwd));
363
+ // Recorded with the turn: the parameters, the access they come to and the directories the thread reports writable.
364
+ threadParams = { ...m.params, access: accessOf(active, parsed.profile), sandboxWritable: sandbox.writableRoots ?? [] };
365
+ const result = {
366
+ thread: { id: session.sessionId, turns: pastTurns }, approvalPolicy: m.params.approvalPolicy, model, modelProvider: "openai", serviceTier: tier,
367
+ ...(m.params.sandbox !== undefined ? { sandbox: { type: m.params.sandbox } } : { sandbox, runtimeWorkspaceRoots: roots, activePermissionProfile: typeof active === "string" ? { id: active, extends: null } : null }),
368
+ ...JSON.parse(process.env.STUB_CODEX_THREAD ?? "{}"),
369
+ };
370
+ for (const k of JSON.parse(process.env.STUB_CODEX_THREAD_OMIT ?? "[]")) delete result[k];
371
+ out({ id: m.id, result });
372
+ continue;
373
+ }
374
+ if (m.method === "turn/interrupt" && stubborn.on) { record({ event: "interrupt", target: "codex", ignored: true }); out({ id: m.id, result: {} }); continue; }
375
+ if (m.method === "turn/interrupt") { out({ id: m.id, result: {} }); out({ method: "turn/completed", params: { turn: { id: "turn_1", status: "interrupted" } } }); process.exit(0); }
376
+ if (m.method === "turn/start") {
377
+ out({ id: m.id, result: { turn: { id: "turn_1" } } });
378
+ out({ method: "turn/started", params: { turn: { id: "turn_1" } } });
379
+ const prompt = m.params.input[0].text;
380
+ const access = threadParams.access;
381
+ record({ event: "start", env: SEEN_ENV, target: "codex", via: "app-server", argv, prompt, sessionId: session.sessionId, resumed: session.resumed, turn: session.sess.turns, access, cwd: process.cwd(), hasRelay: Boolean(parsed.relay), thread: threadParams, sandboxPolicy: m.params.sandboxPolicy ?? null, effort: m.params.effort ?? null, model: m.params.model ?? null, serviceTier: m.params.serviceTier ?? null, cyberAccessProgram: m.params.cyberAccessProgram ?? null, turnKeys: Object.keys(m.params) });
382
+ void (async () => {
383
+ const ask = (command) => new Promise((resolve) => {
384
+ // Told never to ask, the real server does not: the command simply fails inside the sandbox.
385
+ if (threadParams.approvalPolicy === "never") return resolve({ decision: "deny", message: "blocked by the sandbox" });
386
+ const id = nextId++;
387
+ const identity = typeof command !== "string" && command.threadId ? { threadId: command.threadId, turnId: command.turnId ?? "child-turn" } : {};
388
+ const patchId = command.itemId ?? (command.anonymous ? "patch_unknown" : "patch_1");
389
+ answers.set(id, (res) => {
390
+ record({ event: "approval-answer", target: "codex", ...identity, decision: res.decision });
391
+ const allowed = res.decision === "accept" || res.decision === "acceptForSession";
392
+ // A declined command or file change is reported as an item that ended declined.
393
+ if (!allowed) {
394
+ out({ method: "item/completed", params: { ...identity, item: typeof command !== "string" && command.edit
395
+ ? { type: "fileChange", id: patchId, status: "declined", changes: command.anonymous ? [] : [{ path: command.edit, kind: "update" }] }
396
+ : { type: "commandExecution", id: "exec_1", status: "declined", command: typeof command === "string" ? command : command.cmd ?? `curl ${command.web ?? command.fetch}` } } });
397
+ }
398
+ resolve(res.decision === "accept" ? { decision: "allow" } : res.decision === "acceptForSession" ? { decision: "allow", scope: "job" } : { decision: "deny" });
399
+ });
400
+ if (typeof command !== "string" && command.edit) {
401
+ // Codex announces the change as an item first; the approval request refers to it by id.
402
+ if (!command.anonymous) out({ method: "item/started", params: { ...identity, item: { type: "fileChange", id: patchId, changes: [{ path: command.edit, kind: "update" }] } } });
403
+ out({ id, method: "item/fileChange/requestApproval", params: { threadId: session.sessionId, turnId: "turn_1", ...identity, itemId: patchId, startedAtMs: Date.now(), reason: "needs to write outside the sandbox" } });
404
+ }
405
+ else {
406
+ // A request may carry what Codex's experimental API adds (additionalPermissions,
407
+ // availableDecisions), its kind (writeStdin) or a blocked host (networkApprovalContext).
408
+ // Generic approval-transport scenarios use input to an already running terminal:
409
+ // allowing it adds no filesystem authority, so PC's immutable store survives. Tests
410
+ // of command escalation must send an explicit object (kind:"command" or additions).
411
+ // PC's stdio fixture separately verifies a real broad request is declined before asking.
412
+ const generic = typeof command === "string" ||
413
+ ((command.web || command.fetch) && !["kind", "additionalPermissions", "networkApprovalContext"].some((k) => k in command));
414
+ const extra = generic ? { kind: "writeStdin" } : Object.fromEntries(["kind", "additionalPermissions", "availableDecisions", "networkApprovalContext"].filter((k) => k in command).map((k) => [k, command[k]]));
415
+ out({ id, method: "item/commandExecution/requestApproval", params: { threadId: session.sessionId, turnId: "turn_1", itemId: "exec_1", startedAtMs: Date.now(), command: typeof command === "string" ? command : command.cmd ?? `curl ${command.web ?? command.fetch}`, reason: "blocked by the sandbox", cwd: (typeof command === "string" ? undefined : command.cwd) ?? process.cwd(), ...extra } });
416
+ // withdraw: the request is resolved by Codex itself at once (its execution was cancelled,
417
+ // say), announced with serverRequest/resolved as Codex 0.167 does; an answer relay
418
+ // sends afterwards is recorded and has no effect.
419
+ if (typeof command !== "string" && command.withdraw) {
420
+ answers.set(id, (res) => record({ event: "approval-answer-after-withdraw", target: "codex", decision: res.decision }));
421
+ out({ method: "serverRequest/resolved", params: { threadId: session.sessionId, requestId: id } });
422
+ record({ event: "approval-withdrawn", target: "codex" });
423
+ resolve({ decision: "deny", withdrawn: true });
424
+ }
425
+ }
426
+ });
427
+ const r = await runSteps(codex, parsed, prompt, session.sess, ask);
428
+ record({ event: "end", target: "codex", sessionId: session.sessionId, ...r });
429
+ if (r.failure) out({ method: "turn/completed", params: { turn: { id: "turn_1", status: "failed", error: { message: r.failure } } } });
430
+ else {
431
+ // The thread's running total, as the real server reports it after each model response.
432
+ const n = session.sess.turns;
433
+ out({ method: "thread/tokenUsage/updated", params: { threadId: session.sessionId, turnId: "turn_1", tokenUsage: { total: { totalTokens: 1500 * n, inputTokens: 1000 * n, cachedInputTokens: 600 * n, outputTokens: 500 * n, reasoningOutputTokens: 100 * n }, last: { totalTokens: 1500 }, modelContextWindow: 400000 } } });
434
+ out({ method: "item/completed", params: { item: { type: "agentMessage", id: "msg_1", text: r.reply } } });
435
+ out({ method: "turn/completed", params: { turn: { id: "turn_1", status: "completed" } } });
436
+ }
437
+ })();
438
+ continue;
439
+ }
440
+ // A message added to the running turn, as the real server takes it (TurnSteerParams).
441
+ if (m.method === "turn/steer") {
442
+ record({ event: "steer", target: "codex", threadId: m.params.threadId, expectedTurnId: m.params.expectedTurnId, input: m.params.input });
443
+ out({ id: m.id, result: { turnId: m.params.expectedTurnId } });
444
+ continue;
445
+ }
446
+ if (m.id !== undefined) out({ id: m.id, error: { code: -32601, message: "unsupported" } });
447
+ }
448
+ }
449
+
450
+ const codex = {
451
+ id: "codex",
452
+ version: "codex-cli 0.163.0 (stub)",
453
+
454
+ intercept(argv) {
455
+ if (!(argv.includes("mcp") && argv.includes("list"))) return false;
456
+ process.stdout.write(process.env.STUB_CODEX_MCP_LIST ?? "[]");
457
+ return true;
458
+ },
459
+ serve: (argv) => (argv[0] === "app-server" ? appServer(argv) : null),
460
+ parse: parseCodex,
461
+ // As Codex names itself to the MCP servers it starts: relay believes a root's --host codex only
462
+ // while its clientInfo agrees (src/mcp/host.ts registrationAgrees).
463
+ mcpClientName: "codex-mcp-client",
464
+ // Codex passes MCP servers a filtered environment; emulate that so the tests prove that the
465
+ // explicit env in the injected entry is enough.
466
+ mcpEnv: (env, envVars = []) => Object.fromEntries(Object.entries(env).filter(([k]) => ["PATH", "HOME", "TMPDIR", ...envVars].includes(k) || k.startsWith("STUB_"))),
467
+
468
+ start(argv, parsed, sessionId) {
469
+ emit({ type: "thread.started", thread_id: sessionId });
470
+ emit({ type: "turn.started" });
471
+ },
472
+ ask: () => async () => ({ decision: "deny", message: "no approval channel" }),
473
+ fail: (failure) => emit({ type: "turn.failed", error: { message: failure } }),
474
+ finish(reply) {
475
+ emit({ type: "item.completed", item: { id: "item_0", type: "agent_message", text: reply } });
476
+ emit({ type: "turn.completed", usage: {} });
477
+ },
478
+ };
479
+ export default codex;