@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,998 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { localModeInterlock, rawNetworkConsentProblem, stage2Enabled } from "../core/raw-network.js";
5
+ import { loopbackAliasProblem } from "../confine/ports.js";
6
+ import { canonical, escalationEnabled, networkOn } from "../core/config.js";
7
+ import { mediatedBaseline, mediatedNetworkProblem } from "../core/mediated-network-provider.js";
8
+ import { setParam } from "../core/db.js";
9
+ import { codexVersion } from "./codex-daybreak.js";
10
+ import { codexPinVersion } from "./codex-pin.js";
11
+ import { ensurePrivateRoot, privateStateRoot } from "../confine/private-root.js";
12
+ import { privateTurnTemp } from "../confine/turn.js";
13
+ import { spawnFound } from "../core/executables.js";
14
+ // Wire names shared with broker-http.ts (§8.4). Kept here too so BC can build before BA lands.
15
+ const BROKER_SERVER_NAME = "relay_tools";
16
+ const BROKER_TOKEN_ENV = "RELAY_BROKER_TOKEN";
17
+ /**
18
+ * Stage 2's admission gates, Codex settings, readback and accounting (docs/codex-confinement-design.md
19
+ * §2.2 steps 1-5 and 10-11, §2.4, §2.5; docs/codex-mcp-broker-design.md §7.1, §8.4). Owner: BC.
20
+ *
21
+ * A stage-2 turn's commands and file edits run in relay's executor, inside relay's Seatbelt; the app
22
+ * server stays outside, unconfined. It runs with CODEX_EXEC_SERVER_URL=none (STAGE2_APP_SERVER_ENV),
23
+ * so Codex registers no environment of its own (`local`) at all: the executor is the only place a
24
+ * command can run, by construction, whatever turn Codex starts (review r_0c11d860 C1+X2). And
25
+ * everything the app server would do on its own is switched off and read back before the prompt:
26
+ * approvals always come to relay (on-request), only relay's authenticated HTTP MCP broker may
27
+ * connect, no plugins, apps, hooks, image generation or skill-dependency installs, and the 1.0.5
28
+ * pins. A setting that does not read back as relay set it refuses the turn; it is never downgraded.
29
+ */
30
+ /** The first Codex with environments as relay uses them (environment/add, thread/start.environments; W163). */
31
+ export const STAGE2_MIN_CODEX = [0, 164, 0];
32
+ /**
33
+ * What relay adds to a stage-2 app server's environment, its own value (review r_0c11d860 C1+X2):
34
+ * `CODEX_EXEC_SERVER_URL=none` makes Codex register no environment of its own (exec-server
35
+ * environment_provider.rs normalize_exec_server_url: "none" disables, so the snapshot has no `local`
36
+ * and no default). Verified model-free on 0.164.0 (2026-10-28): `environment/status` for `local`
37
+ * answers `unknown`, before and after relay's environment/add; thread/start without environments
38
+ * gives `[]`, and with `local` is refused ("unknown turn environment id `local`"); a resumed thread's
39
+ * environments are `[]`; Codex's user shell command, its one-off command execution ("local
40
+ * environment is not configured") and its file-system calls ("local filesystem is not configured")
41
+ * are refused, should anything call them (relay does not); an enabled stdio MCP server does not
42
+ * start ("local stdio MCP server … requires a local environment"). So a turn Codex starts by itself
43
+ * (a queued or mailbox message, a goal, a source not known yet) and that relay's turn/start then
44
+ * steers into keeps the environments it started with, which hold nothing but relay's executor, if
45
+ * anything: there is nowhere unconfined for its commands to run.
46
+ *
47
+ * No stdio MCP server can run on a stage-2 turn. relay's tools instead use the authenticated HTTP
48
+ * broker, which needs no `local` environment (codex-mcp-broker-design.md §2.1). Admission refuses the
49
+ * person's own CODEX_EXEC_SERVER_* variables (stage2SettingsProblems): this value is relay's alone.
50
+ */
51
+ export const STAGE2_APP_SERVER_ENV = Object.freeze({ CODEX_EXEC_SERVER_URL: "none" });
52
+ /** The environment a stage-2 app server runs with: `checked` (what admission checked) and STAGE2_APP_SERVER_ENV over it, frozen. */
53
+ export function stage2AppServerEnv(checked) {
54
+ return Object.freeze({ ...checked, ...STAGE2_APP_SERVER_ENV });
55
+ }
56
+ /**
57
+ * Features pinned off and read back on stage-2 sessions (§2.5). Each one, when on, lets the app
58
+ * server act on this Mac itself, outside relay's Seatbelt, or widens what an approval does:
59
+ * image generation saves under CODEX_HOME (D7); apps, plugins and their sync, remote plugins and
60
+ * sharing, MCP apps, browser and computer use, tool suggestions; hooks and plugin hooks; installs
61
+ * of a skill's MCP dependencies; Codex's network proxy and the request_permissions tool, and
62
+ * per-command permission additions (exec_permission_approvals): the 1.0.5 pins; the JavaScript
63
+ * REPL; memories, their import from other agents and Chronicle's screen context; the standalone
64
+ * (extension-run) web search; goals (below). `respect_system_proxy` stays off for the broker's
65
+ * HTTP client (§5.8); BB also merges loopback into NO_PROXY/no_proxy in the app server's environment.
66
+ *
67
+ * `goals` is pinned off because a goal starts turns by itself: an active goal of the thread (set by
68
+ * the model's create_goal in an earlier turn, or by another client) makes Codex start a
69
+ * continuation turn as soon as `thread/resume` leaves the thread idle, before relay's `turn/start`
70
+ * can bind the turn to its executor. With Codex's own `local` registered, that turn ran with the
71
+ * resumed thread's environments `[local, relay]`, and its commands in `local`, unconfined (WP-C,
72
+ * 2026-10-28, on 0.164.0; with `features.goals=false` no turn started). Since the app server has no
73
+ * `local` (STAGE2_APP_SERVER_ENV), such a turn has no environment and cannot run a command; the pin
74
+ * stays as defence in depth, with the turn guard (Stage2TurnGuard).
75
+ *
76
+ * `code_mode` is pinned off too, but that changes nothing for the models relay runs: every gpt-6.x
77
+ * and gpt-5.6 entry of Codex 0.164.0's catalog is `tool_mode: "code_mode_only"`, which overrides the
78
+ * feature, so those models get code mode's `exec` anyway (STAGE2_TOOLS). It is kept off for a model
79
+ * in direct mode, where the feature alone would add `exec`.
80
+ *
81
+ * `deferred_tool_world_state` is different: it adds no host action. At rust-v0.167.0 its feature
82
+ * description reads "Describe deferred tool namespaces in the model-visible world state"
83
+ * (features/src/lib.rs); when on, core session/world_state.rs adds a section naming the deferred
84
+ * tool namespaces, and core tools/spec_plan.rs drops the source listing from tool_search's own
85
+ * description. 0.164.0 and 0.166.0 list it under development, default off; 0.167.0 makes it
86
+ * stable and on by default. Every version stage 2 admits (STAGE2_MIN_CODEX) lists it, so it is in
87
+ * this base list rather than version-gated. It is pinned off as defence in depth and to keep the
88
+ * model-visible context of the qualified 0.166.0.
89
+ */
90
+ export const STAGE2_FEATURES_OFF = [
91
+ "image_generation", "apps", "plugins", "remote_plugin", "plugin_sharing", "enable_mcp_apps", "browser_use", "computer_use", "tool_suggest",
92
+ "hooks", "plugin_hooks", "skill_mcp_dependency_install", "network_proxy", "request_permissions_tool",
93
+ "exec_permission_approvals", "js_repl", "code_mode", "memories", "external_agent_memory_import", "chronicle",
94
+ "standalone_web_search", "goals", "respect_system_proxy", "deferred_tool_world_state",
95
+ ];
96
+ /** 0.166.0 adds these keys; older binaries must not be required to list them. Source at
97
+ * rust-v0.166.0: app-server message_processor.rs and core-plugins manager.rs start host-side
98
+ * discovery prefetch (also gated by plugins=false); core session/mod.rs preserves parent tool
99
+ * declarations only in MCP-disabled prediction/sample forks, APIs relay never calls. Both stay
100
+ * off as defence in depth.
101
+ *
102
+ * 0.167.2 adds `incremental_tools_legacy_gcp`, stable and on by default ("Publish incremental tool
103
+ * declarations on regular GCP Responses", features/src/lib.rs); 0.167.0 and 0.167.1 do not list it.
104
+ * Core session/step_context.rs selects it only when the turn's model provider is `gcp`, so it
105
+ * changes nothing on relay's OpenAI-provider turns and adds no tool or host action. It is pinned
106
+ * off as defence in depth and to keep the qualified 0.167.0's behaviour, rather than admitted.
107
+ *
108
+ * 0.170.0 turns on by default seven features older versions list off or not at all
109
+ * (STAGE2_FEATURES_OFF_0170). None adds a tool or a host action, and each is pinned off to keep
110
+ * the qualified 0.167.2's behaviour rather than admitted. 0.170.0 also marks
111
+ * `plugin_discovery_prefetch` removed: config ignores it and the list reports it off, so its pin
112
+ * still reads back. */
113
+ export function stage2FeaturesOff(version) {
114
+ let off = atLeast(version, [0, 166, 0])
115
+ ? [...STAGE2_FEATURES_OFF, "plugin_discovery_prefetch", "prediction_preserve_parent_tools"]
116
+ : STAGE2_FEATURES_OFF;
117
+ if (atLeast(version, [0, 167, 2]))
118
+ off = [...off, "incremental_tools_legacy_gcp"];
119
+ return atLeast(version, [0, 170, 0]) ? [...off, ...STAGE2_FEATURES_OFF_0170] : off;
120
+ }
121
+ /**
122
+ * Features Codex 0.170.0 turns on by default, pinned off from 0.170.0 (source at rust-v0.170.0):
123
+ * - `code_mode_host_grpc`: core thread_manager.rs picks the gRPC code-mode host over the
124
+ * process-owned one. Both run the same unsandboxed `codex-code-mode-host` child over its stdio
125
+ * (core code_mode_host.rs, `--listen grpc+stdio://`, no listener) in a process group of its
126
+ * own, as the process-owned one already was (code-mode remote_session/connection.rs, 0.167.2).
127
+ * Relay's teardown stops it either way as a recorded descendant of the app server (watchProcess),
128
+ * and both hosts exited within 0.25 s of the app server's death with a busy cell running
129
+ * (2026-11-18, docs/qualification/codex-0.170.0.md). Only the wire protocol and session recovery
130
+ * differ: no confinement reason to refuse it, pinned off for parity with 0.167.2 until a
131
+ * qualification runs with it on.
132
+ * - `code_mode_host_output_truncation`: wraps the code-mode provider to truncate `exec` output in
133
+ * the host instead of the client (thread_manager.rs); what the model sees, nothing else.
134
+ * - `guardian_include_additional_context`: adds additional-context tool outputs to Guardian's
135
+ * review history (context_manager/history.rs). Relay answers approvals itself.
136
+ * - `incremental_tools_legacy`: read only for the Amazon Bedrock providers (session/step_context.rs),
137
+ * as `incremental_tools_legacy_gcp` is for `gcp`; inert on relay's OpenAI-provider turns.
138
+ * - `retain_client_tool_outputs`: keeps client tool outputs across remote compaction
139
+ * (compact_remote_v2.rs, compact_remote_history.rs, session/mod.rs).
140
+ * - `unified_image_budget`: one image budget for prepared images (image_preparation.rs).
141
+ * - `untrusted_as_tool_output`: renders untrusted additional context, a turn's `additionalContext`
142
+ * or a goal's objective, as a tool output (namespace `agent`) rather than a user fragment
143
+ * (session/turn_input.rs, state/additional_context.rs). Relay sends no additional context and
144
+ * pins goals off, so it is inert on relay's turns.
145
+ * 0.170.0 lists each; older versions are not required to.
146
+ */
147
+ export const STAGE2_FEATURES_OFF_0170 = [
148
+ "code_mode_host_grpc", "code_mode_host_output_truncation", "guardian_include_additional_context", "incremental_tools_legacy",
149
+ "retain_client_tool_outputs", "unified_image_budget", "untrusted_as_tool_output",
150
+ ];
151
+ // Admission probes the selected executable, not the mutable pin link. Retain its checked version
152
+ // for this turn (including explicit unpinned executables); planning never probes `current` again.
153
+ const admittedVersions = new WeakMap();
154
+ /**
155
+ * The features a stage-2 session may run with on, on the Codex versions qualified (0.164.0): what
156
+ * experimentalFeature/list reported enabled with relay's stage-2 settings and a scratch CODEX_HOME,
157
+ * model-free (WP-D readback probe, 2026-10-28). Any other feature on refuses the turn: a feature a
158
+ * new Codex adds, or one a layer of the person's turns on, may add a tool or an action of the app
159
+ * server's own, and waits until it is qualified (§2.5, the per-release allowlist).
160
+ */
161
+ export const STAGE2_FEATURES_ALLOWED_ON = [
162
+ // core/session/reasoning_effort.rs and core/client.rs (rust-v0.166.0): trusted
163
+ // configuration_update items carry effort changes; no tool or host-side action is added.
164
+ "reasoning_effort_override",
165
+ // Stable, on by default. Shell snapshots are not taken for a remote environment such as relay's
166
+ // executor (core shell_snapshot.rs); daemon_auto_start acts only for the TUI and remote control;
167
+ // workspace_dependencies is read nowhere in 0.164.0; code_mode_host runs `exec`'s V8 isolate.
168
+ "api_key_cyber_access_programs", "api_key_model_discovery", "auth_elicitation", "bedrock_setup_wizard", "cli_daybreak",
169
+ "code_mode_host", "code_mode_interrupt", "compaction_image_budget", "content_item_kinds", "daemon_auto_start",
170
+ "enable_request_compression", "fast_mode", "guardian_approval", "guardian_reuse_parent_compaction",
171
+ "incremental_tools", "instant_interrupt", "mcp_oauth_refresh_coordination", "mentions_v2", "multi_agent", "shell_snapshot",
172
+ "shell_tool", "skill_search", "sleep_tool", "system_proxy_fallback", "tool_call_mcp_elicitation", "ultrafast_mode",
173
+ "unbounded_connection_retries", "unified_exec", "unified_exec_tty", "view_image", "workspace_dependencies", "write_stdin_approval",
174
+ // Gates the desktop apps read from requirements, not the app server.
175
+ "browser_annotation_api", "browser_use_external", "browser_use_full_cdp_access", "in_app_browser", "in_app_chat",
176
+ "in_app_dictation", "in_app_local_automation", "in_app_updates", "in_app_voice",
177
+ // Removed in 0.164.0, listed as on: no-ops.
178
+ "collaboration_modes", "item_ids", "realtime_conversation", "resize_all_images", "sqlite", "steer", "terminal_resize_reflow",
179
+ "tool_search_always_defer_mcp_tools", "tui_app_server", "worktrees",
180
+ ];
181
+ /** relayServer's child tools; per-turn listings use broker.listTools(), which may be narrower. */
182
+ const BROKER_TOOL_NAMES = ["escalate", "delegate", "status", "result", "resume", "cancel", "merge", "ask", "brief", "discuss", "review"];
183
+ const brokerToolSurfaces = (names) => ["mcp__relay_tools", ...names, ...names.map((name) => `mcp__relay_tools__${name}`)];
184
+ const BROKER_TOOL_SURFACES = brokerToolSurfaces(BROKER_TOOL_NAMES);
185
+ /**
186
+ * The tools a stage-2 session may offer the model on the Codex versions qualified (§2.5, §9.3): an
187
+ * allowlist the advertised set must be a subset of (stage2ToolsProblem). Not an exact list: the set
188
+ * varies by model. WP-F's qualification (§7.2 item 10) checks it per release with the fake model.
189
+ * Relay cannot check it per turn: the tool list goes from the app server to OpenAI over TLS, and the
190
+ * app server reports it nowhere relay can read. The per-turn guard is the config and feature
191
+ * readback (stage2Readback, STAGE2_FEATURES_ALLOWED_ON).
192
+ *
193
+ * Seen on 0.164.0 with relay's stage-2 flags, a scratch CODEX_HOME and the fake Responses server
194
+ * (WP-D probe, every catalog model, all `code_mode_only`): the model gets an `additional_tools`
195
+ * input item, not `body.tools`, with namespace `functions` (`exec`, `wait`, `request_user_input`,
196
+ * and on 6.x `request_user_input_async`), on 6.x `clock` (`sleep`; `curr_time`, inside `exec` as
197
+ * `clock__curr_time`) and `collaboration` (`spawn_agent`, `wait_agent`, `send_message`,
198
+ * `followup_task`, `interrupt_agent`, `list_agents`); inside `exec`: `apply_patch`, `exec_command`,
199
+ * `write_stdin`, `view_image`, the goal tools (gone since `goals` is pinned off) and the MCP
200
+ * resource tools. A model in direct mode
201
+ * (gpt-5.5, WP-F) gets the classic list and `tool_search`. MCP tools are confined to
202
+ * `mcp__relay_tools` and the broker's own names (broker design §8.6).
203
+ *
204
+ * Where each runs: `exec_command`, `write_stdin`, `apply_patch` and `view_image` in relay's
205
+ * executor; `web_search` at OpenAI; subagents inherit the turn's environments, which relay binds
206
+ * to its executor (stage2TurnParams); the plan, clock, user-input, tool-search and MCP-resource
207
+ * tools in the app server, touching no file or network of this Mac's themselves. `exec` runs model-written JavaScript in a V8 isolate in
208
+ * `codex-code-mode-host`, an unsandboxed child of the app server (core code_mode_host.rs
209
+ * HostConnection::spawn), with no Node, file system or network bindings; its nested tools go through
210
+ * Codex's router to the thread's environment, relay's executor. The same host runs today for every
211
+ * Codex turn under relay 1.0.5, so stage 2 does not widen it. Residual: an escape from the isolate
212
+ * would run as the app server, unconfined (§8).
213
+ * `request_user_input` is refused by Codex itself in default collaboration mode ("unavailable in
214
+ * Default mode", WP-D probe); were it asked, relay answers item/tool/requestUserInput with an error
215
+ * (codex-app.ts onServerRequest), so it fails closed.
216
+ */
217
+ export const STAGE2_TOOLS = [
218
+ // Namespaces (code mode).
219
+ "functions", "clock", "collaboration",
220
+ // Code mode's own.
221
+ "exec", "wait", "request_user_input", "request_user_input_async", "sleep", "curr_time", "clock__curr_time",
222
+ // Collaboration (multi-agent v2), and multi-agent v1 in direct mode.
223
+ "spawn_agent", "wait_agent", "send_message", "followup_task", "interrupt_agent", "list_agents", "send_input", "resume_agent", "close_agent",
224
+ // Classic, and nested inside `exec`.
225
+ "exec_command", "write_stdin", "apply_patch", "view_image", "web_search", "update_plan", "tool_search",
226
+ "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource",
227
+ // ext/web-search's standalone search (namespace `web`, tool `run`; `web__run` inside `exec`), offered
228
+ // to code-mode models whenever the provider is OpenAI's and web search is on (relay sets "live" for
229
+ // a network grant; the `standalone_web_search` pin does not remove it; WP-F item 10). It runs in the
230
+ // app server but only POSTs the model's search commands, open_page URLs included, to the provider's
231
+ // search endpoint (codex-api endpoint/search.rs SEARCH_ENDPOINT, ext/web-search tool.rs): the
232
+ // provider fetches pages, not this Mac. Same trust as model traffic and hosted web_search; the
233
+ // prompt-injection residual of search results is 1.0.5's (X6).
234
+ "web", "run", "web__run",
235
+ // Codex 0.170.0's catalog lists it in a model's `experimental_supported_tools`, which offers it
236
+ // whatever the feature `send_message_to_user_async` says (core tools/spec_plan.rs), to root
237
+ // turns only. Its handler (tools/handlers/send_message_to_user_async.rs) emits an agent message
238
+ // item and returns `{"accepted":true}`: no file, process or network of this Mac's.
239
+ "send_message_to_user_async",
240
+ ...BROKER_TOOL_SURFACES,
241
+ ];
242
+ /**
243
+ * Which advertised tools are not on the allowlist, for the per-release qualification (WP-F, §7.2
244
+ * item 10): each name as the request carries it, a namespace by its own name and its members, and
245
+ * `exec`'s nested tools. Pass the actual broker tool names to narrow the qualified child-tool union
246
+ * for a turn whose policy disables delegation. What is not allowed, or null.
247
+ */
248
+ export function stage2ToolsProblem(advertised, brokerTools = BROKER_TOOL_NAMES) {
249
+ const qualified = brokerTools.filter((t) => BROKER_TOOL_NAMES.includes(t));
250
+ const allowed = new Set([...STAGE2_TOOLS.filter((t) => !BROKER_TOOL_SURFACES.includes(t)), ...brokerToolSurfaces(qualified)]);
251
+ const extra = [...new Set(advertised.filter((t) => !allowed.has(t)))].sort();
252
+ return extra.length ? `Codex offers the model tools relay has not qualified for stage 2: ${extra.join(", ")}` : null;
253
+ }
254
+ /** The session-params key that records a turn's enforcement (no registry schema change): `codex_confinement` (params.ts). */
255
+ export const CONFINEMENT_PARAM = "codex_confinement";
256
+ /** Codex's own permission profile without its sandbox; on a stage-2 turn relay's Seatbelt around the executor confines instead. */
257
+ const FULL_ACCESS = ":danger-full-access";
258
+ /** Network grants always require stage 2 when enabled, even if qualification must refuse.
259
+ * Network-disabled origins use it when they can request a restart. */
260
+ export function stage2Wanted(spec) {
261
+ if (!stage2Enabled(process.env, spec.config) || spec.target.id !== "codex")
262
+ return false;
263
+ if (networkOn(spec.config, spec.grant))
264
+ return true;
265
+ return spec.config.codex_backend !== "exec" && (spec.grant?.raw_network === true
266
+ || spec.overlay?.state === "running" || (escalationEnabled(spec.config) && !spec.config.allow_dangerous));
267
+ }
268
+ /** Which confinement a turn runs under: relay's (stage 2) or Codex's own, verified (§2.4). */
269
+ export function turnConfinement(spec) {
270
+ return stage2Wanted(spec) ? "relay-enforced" : "verified";
271
+ }
272
+ /** Where Codex keeps its home for `env`: CODEX_HOME, else ~/.codex (as Codex resolves it). */
273
+ function codexHomeOf(env) {
274
+ return env.CODEX_HOME || path.join(env.HOME || os.homedir(), ".codex");
275
+ }
276
+ /** Whether version `v` is `min` or later. */
277
+ function atLeast(v, min) {
278
+ for (let i = 0; i < min.length; i++) {
279
+ const a = v[i] ?? 0;
280
+ if (a !== min[i])
281
+ return a > min[i];
282
+ }
283
+ return true;
284
+ }
285
+ /**
286
+ * The settings of relay's and of Codex's that stage 2 needs, read without starting anything: what
287
+ * is wrong, each as a phrase. Admission refuses on any; doctor reports them.
288
+ */
289
+ export function stage2SettingsProblems(cfg, env, version) {
290
+ const wrong = [];
291
+ if (cfg.codex_backend === "exec")
292
+ wrong.push('codex_backend is "exec", and stage 2 runs only through Codex\'s app server');
293
+ if (!version)
294
+ wrong.push("relay could not read Codex's version");
295
+ else if (!atLeast(version, STAGE2_MIN_CODEX))
296
+ wrong.push(`Codex is ${version.join(".")}, and stage 2 needs ${STAGE2_MIN_CODEX.join(".")} or later (its execution environments)`);
297
+ // Codex takes CODEX_HOME/environments.toml over environment/add and over CODEX_EXEC_SERVER_URL
298
+ // (exec-server environment.rs from_codex_home), and the Noise variables over both: any of them
299
+ // decides which environments the app server has, `local` included. relay sets
300
+ // CODEX_EXEC_SERVER_URL=none itself (STAGE2_APP_SERVER_ENV), so a value of the person's, or any
301
+ // other executor variable, is refused, never merged.
302
+ const toml = path.join(codexHomeOf(env), "environments.toml");
303
+ if (fs.existsSync(toml))
304
+ wrong.push(`${toml} exists, and Codex would take its environments from it rather than from relay`);
305
+ const routed = Object.keys(env).filter((k) => k.startsWith("CODEX_EXEC_SERVER_")).sort();
306
+ if (routed.length)
307
+ wrong.push(`the agent's environment sets ${routed.join(", ")}, which route Codex's commands to another executor`);
308
+ if (Object.hasOwn(env, BROKER_TOKEN_ENV))
309
+ wrong.push(`the person's environment sets ${BROKER_TOKEN_ENV}, which relay reserves for its per-turn broker credential`);
310
+ // Review C1, C6: an MCP server or hook would run in the app server, outside relay's Seatbelt. Without
311
+ // `local` no stdio server can start, but a streamable-HTTP one still can (codex-mcp runtime.rs
312
+ // resolve_server_environment: local HTTP uses the app server's own client), so the person's servers
313
+ // are still switched off by name (child_mcp "relay-only") and plugins with them, and read back.
314
+ if (cfg.child_mcp !== "relay-only")
315
+ wrong.push('child_mcp is not "relay-only", and the person\'s MCP servers would run outside relay\'s sandbox');
316
+ if (cfg.child_hooks)
317
+ wrong.push("child_hooks is on, and Codex's hooks would run outside relay's sandbox");
318
+ return wrong;
319
+ }
320
+ const PROBES = {
321
+ consent: (spec) => rawNetworkConsentProblem(spec.markers?.nodeId, spec.grant),
322
+ version: (bin, env) => codexVersion(bin, env),
323
+ mcpServers: (bin, env, cwd) => {
324
+ const r = spawnFound(bin, ["--disable", "plugins", "mcp", "list", "--json"], { encoding: "utf8", timeout: 20000, env, cwd }, env.PATH ?? "");
325
+ if (r.error)
326
+ throw r.error;
327
+ if (r.status !== 0)
328
+ throw new Error(`codex mcp list exited with ${r.status}`);
329
+ let list;
330
+ try {
331
+ list = JSON.parse(r.stdout);
332
+ }
333
+ catch {
334
+ throw new Error("codex mcp list did not return JSON");
335
+ }
336
+ if (!Array.isArray(list) || list.some((s) => typeof s?.name !== "string"))
337
+ throw new Error("codex mcp list did not return named servers");
338
+ return list.map((s) => s.name);
339
+ },
340
+ interlock: () => localModeInterlock("stage2"),
341
+ aliases: () => loopbackAliasProblem(),
342
+ };
343
+ /**
344
+ * Admission (§2.2 steps 1-5): for a raw-network grant, the person's consent stored for the very
345
+ * grant this turn launches with (raw-network.ts rawNetworkConsentProblem; review R2), Codex 0.164 or later, no ~/.codex/environments.toml, no
346
+ * CODEX_EXEC_SERVER_URL or Noise variables in `env` (the person's environment, before relay adds its
347
+ * own STAGE2_APP_SERVER_ENV), no person's broker-token variable or relay_tools config entry,
348
+ * child_mcp relay-only, child_hooks off, no extension servers (unsupported on stage-2 jobs),
349
+ * the interlock (raw-network.ts), no lo0 aliases (ports.ts). The reason it cannot run, or null. A
350
+ * check that cannot be made refuses. `probes`: tests only.
351
+ */
352
+ export function stage2Admission(spec, env, probes = {}) {
353
+ admittedVersions.delete(spec);
354
+ const p = { ...PROBES, ...probes };
355
+ const refuse = (why) => `relay cannot run this Codex job under stage 2: ${why}. It does not start the agent; there is no native strict or raw fallback.`;
356
+ if (!stage2Wanted(spec))
357
+ return refuse("this turn does not select stage 2");
358
+ const baseline = mediatedBaseline(spec.grant, spec.config);
359
+ if (baseline?.network && !baseline.raw_network) {
360
+ if (!spec.neverPolicy)
361
+ return refuse("mediated launch has no checked never policy");
362
+ const unavailable = mediatedNetworkProblem({ capabilities: spec.overlay?.request.capabilities ?? [], baseline, policy: spec.neverPolicy });
363
+ if (unavailable)
364
+ return refuse(unavailable);
365
+ }
366
+ if (spec.grant?.raw_network && spec.access !== "write" && !spec.overlay)
367
+ return refuse("raw network is for write jobs");
368
+ // caller.ts refuses network with extension servers already (NO_NETWORK_WITH_SERVERS); a stored run is checked again here.
369
+ if (spec.extensionServers?.length)
370
+ return refuse("stage-2 jobs do not support extension servers");
371
+ let unconsented;
372
+ try {
373
+ // A consumed overlay carries its separately authenticated one-turn authority. It cannot mint
374
+ // standing raw consent, and the launch gate verifies its destination and immutable digest.
375
+ unconsented = !spec.grant?.raw_network ? null : p.consent(spec);
376
+ }
377
+ catch (err) {
378
+ unconsented = `relay could not read the person's consent (${err.message})`;
379
+ }
380
+ if (unconsented)
381
+ return refuse(unconsented);
382
+ let version = null;
383
+ try {
384
+ version = p.version(spec.config.targets.codex.bin, env);
385
+ }
386
+ catch {
387
+ version = null;
388
+ }
389
+ const wrong = stage2SettingsProblems(spec.config, env, version);
390
+ if (wrong.length)
391
+ return refuse(wrong.join("; "));
392
+ try {
393
+ if (p.mcpServers(spec.config.targets.codex.bin, env, spec.cwd).includes(BROKER_SERVER_NAME)) {
394
+ return refuse(`the person's Codex config defines ${BROKER_SERVER_NAME}; remove or rename it, because Codex's recursive merge would retain inherited fields in relay's broker entry`);
395
+ }
396
+ }
397
+ catch (err) {
398
+ return refuse(`relay could not read the person's MCP server names (${err.message}), so it cannot rule out a ${BROKER_SERVER_NAME} entry`);
399
+ }
400
+ for (const [what, check] of [["whether a relay local-network job runs", p.interlock], ["this Mac's loopback addresses", p.aliases]]) {
401
+ let problem;
402
+ try {
403
+ problem = check();
404
+ }
405
+ catch (err) {
406
+ problem = `relay could not check ${what} (${err.message})`;
407
+ }
408
+ if (problem)
409
+ return refuse(problem);
410
+ }
411
+ admittedVersions.set(spec, Object.freeze([...version]));
412
+ return null;
413
+ }
414
+ /** The exact HTTP entry (§7.1). Unexpected keys are named, never printed: they may hold a secret. */
415
+ export function stage2BrokerConfigProblem(entry, expected) {
416
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
417
+ return `Codex does not report relay's ${BROKER_SERVER_NAME} MCP entry`;
418
+ const server = entry;
419
+ const required = {
420
+ url: expected.url, bearer_token_env_var: BROKER_TOKEN_ENV, environment_id: "local",
421
+ enabled: true, required: true, default_tools_approval_mode: "approve",
422
+ startup_timeout_sec: 30, tool_timeout_sec: expected.toolTimeoutS,
423
+ };
424
+ for (const [key, value] of Object.entries(required)) {
425
+ if (server[key] !== value)
426
+ return `Codex's ${BROKER_SERVER_NAME} MCP entry does not have the ${key} relay set`;
427
+ }
428
+ if (Object.hasOwn(server, "startup_readiness") && server.startup_readiness !== "connection")
429
+ return `Codex's ${BROKER_SERVER_NAME} MCP entry does not have startup_readiness "connection" (or the absent default)`;
430
+ const extra = Object.keys(server).filter((key) => !Object.hasOwn(required, key) && key !== "startup_readiness").sort();
431
+ return extra.length ? `Codex's ${BROKER_SERVER_NAME} MCP entry has unexpected keys (${extra.join(", ")}); relay permits no other auth or tool-filter settings` : null;
432
+ }
433
+ /**
434
+ * The plan for a turn's network (§2.4: `:danger-full-access`, enforcement "relay"; §2.5: features
435
+ * off). Every feature is pinned with `-c features.<name>=false`, not `--disable`: a `--disable` of a
436
+ * feature a Codex version does not know stops its server, and the readback decides instead.
437
+ * Approval policy on-request (review C1) is set here for config/read and on the thread
438
+ * (stage2ThreadParams). `net` decides nothing of Codex's: relay's profile around the executor
439
+ * carries it (WP-A, WP-C).
440
+ */
441
+ export function stage2Plan(_spec, _net) {
442
+ const off = stage2FeaturesOff(admittedVersions.get(_spec) ?? codexPinVersion(_spec.config) ?? STAGE2_MIN_CODEX);
443
+ const features = Object.fromEntries(off.map((f) => [f, false]));
444
+ const c = ["-c", 'approval_policy="on-request"',
445
+ // Codex 0.164 has one key here: `agents.max_threads` is a legacy alias of
446
+ // `agents.max_concurrent_threads_per_session` (config key_aliases.rs). It is v1's limit (default 6);
447
+ // v2 takes `features.multi_agent_v2.max_concurrent_threads_per_session`, else this value + 1
448
+ // (core config resolve_multi_agent_v2_config). Pinned at v1's default: at most 6 subagents either way,
449
+ // so with the root thread at most 7 broker sessions, inside the broker's cap of 8.
450
+ "-c", "agents.max_concurrent_threads_per_session=6",
451
+ ...off.flatMap((f) => ["-c", `features.${f}=false`])];
452
+ return { permissions: stage2Permissions(true), c, off: [], features };
453
+ }
454
+ /** The permissions a stage-2 turn runs with and must read back (§2.4). */
455
+ export function stage2Permissions(network) {
456
+ return { id: FULL_ACCESS, profile: null, sandbox: "danger-full-access", network, proxy: null, enforcement: "relay" };
457
+ }
458
+ /**
459
+ * Overlaid on thread/start and thread/resume (codex-env.ts Stage2Session.threadParams): the
460
+ * executor as the thread's only environment, at the turn's directory, and approvals always
461
+ * on-request (review C1), whatever the turn's escalation. Codex 0.164's thread/resume takes no
462
+ * `environments` (it ignores the key), so a resumed thread gets Codex's defaults instead: with
463
+ * Codex's own `local` registered, every environment the server knows, `local` first; on a stage-2
464
+ * app server, which has none (STAGE2_APP_SERVER_ENV), no environment at all (`[]`, verified on
465
+ * 0.164.0). The turn's own binding (stage2TurnParams) then gives it relay's executor.
466
+ */
467
+ export function stage2ThreadParams(cwd, environmentId) {
468
+ return { environments: [{ environmentId, cwd }], approvalPolicy: "on-request" };
469
+ }
470
+ /**
471
+ * Overlaid on every stage-2 turn/start, fresh or resumed (codex-env.ts Stage2Session.turnParams):
472
+ * the executor as the turn's only environment, at the turn's directory. Codex 0.164 applies
473
+ * `turn/start.environments` to this turn and every later one of the thread (app-server-protocol
474
+ * v2/turn.rs TurnStartParams), in the same request that carries the prompt, before the turn starts
475
+ * (turn_processor.rs builds the thread settings, then start_or_steer_turn). A resumed thread has no
476
+ * environment until then (`[]`: the app server has no `local`, STAGE2_APP_SERVER_ENV), so without
477
+ * this binding its commands would fail rather than run; with Codex's own `local` registered they ran
478
+ * there, unconfined (WP-F item 11; WP-C, 2026-10-28). Subagents a bound turn spawns, and earlier
479
+ * turns' subagents it reaches again (followup_task, send_message; v1 resume_agent, send_input),
480
+ * take the parent's live environments, so they are bound too (core agent/control/spawn.rs; verified
481
+ * live, v1 and v2).
482
+ *
483
+ * The binding does not reach a turn Codex started by itself before relay's turn/start: turn/start
484
+ * then steers into that turn, which keeps the environments it started with (turn_processor.rs maps
485
+ * Started and Steered to the same reply; turn_input.rs apply_steered changes the sticky settings
486
+ * only). That turn has no environment, since the app server has none of its own, so it cannot run a
487
+ * command; Stage2TurnGuard fails it as well.
488
+ */
489
+ export function stage2TurnParams(cwd, environmentId) {
490
+ return { environments: [{ environmentId, cwd }] };
491
+ }
492
+ /** Every feature the server reports (experimentalFeature/list, every page): name to enabled. */
493
+ async function listedFeatures(rpc) {
494
+ const listed = new Map();
495
+ let cursor = null;
496
+ for (let page = 0; page < 50; page++) {
497
+ const r = await rpc.request("experimentalFeature/list", { limit: 500, ...(cursor ? { cursor } : {}) });
498
+ for (const f of (r?.data ?? []))
499
+ if (typeof f?.name === "string")
500
+ listed.set(f.name, f.enabled);
501
+ cursor = typeof r?.nextCursor === "string" && r.nextCursor ? r.nextCursor : null;
502
+ if (!cursor)
503
+ return listed;
504
+ }
505
+ throw new Error("it gave more than 50 pages");
506
+ }
507
+ async function listedMcpServers(rpc, threadId) {
508
+ const listed = [];
509
+ let cursor = null;
510
+ for (let page = 0; page < 50; page++) {
511
+ const r = await rpc.request("mcpServerStatus/list", { detail: "toolsAndAuthOnly", ...(threadId ? { threadId } : {}), ...(cursor ? { cursor } : {}) });
512
+ if (!Array.isArray(r?.data))
513
+ throw new Error("its reply has no list of servers");
514
+ listed.push(...r.data);
515
+ cursor = typeof r?.nextCursor === "string" && r.nextCursor ? r.nextCursor : null;
516
+ if (!cursor)
517
+ return listed;
518
+ }
519
+ throw new Error("it gave more than 50 pages");
520
+ }
521
+ /**
522
+ * What is wrong with the MCP servers Codex lists for this app server (§2.2 step 11, §2.5), or null:
523
+ * only the broker, when expected, and servers config/read reports as `enabled: false` (the stdio
524
+ * `relay` entry and the person's relay-only servers), from no plugin. The broker must list exactly
525
+ * its own tools, HTTP origin and bearer auth; a per-thread listing must also say connected.
526
+ * Codex's catalog includes plugin and app servers absent from config/read. A threadless listing
527
+ * reports no running state; an off server with any state other than "disabled" is refused.
528
+ */
529
+ function mcpListProblem(listed, configured, broker, thread = false) {
530
+ const on = [];
531
+ let found = false;
532
+ const names = new Set();
533
+ for (const s of listed) {
534
+ if (typeof s?.name !== "string")
535
+ return "Codex listed an MCP server without a name (mcpServerStatus/list), so relay cannot tell which servers it would run";
536
+ if (names.has(s.name))
537
+ return `Codex listed the MCP server ${s.name} more than once (mcpServerStatus/list)`;
538
+ names.add(s.name);
539
+ if (broker && s.name === BROKER_SERVER_NAME) {
540
+ found = true;
541
+ if (s.pluginId != null)
542
+ return `Codex lists ${BROKER_SERVER_NAME} from a plugin, not relay's broker`;
543
+ if (s.httpOrigin !== new URL(broker.url).origin)
544
+ return `Codex does not list ${BROKER_SERVER_NAME} at relay's expected httpOrigin`;
545
+ if (s.authStatus !== "bearerToken")
546
+ return `Codex does not list ${BROKER_SERVER_NAME} with bearerToken auth`;
547
+ if (s.toolsError != null)
548
+ return `Codex reports a toolsError for ${BROKER_SERVER_NAME}`;
549
+ if (thread ? s.runtimeStatus !== "connected" : s.runtimeStatus != null && s.runtimeStatus !== "connected")
550
+ return `Codex does not list ${BROKER_SERVER_NAME} as connected${thread ? " on this thread" : " (or without a threadless running state)"}`;
551
+ const tools = s.tools;
552
+ if (!tools || typeof tools !== "object" || Array.isArray(tools))
553
+ return `Codex did not list the tools of ${BROKER_SERVER_NAME}`;
554
+ const entries = Object.entries(tools);
555
+ const expected = new Set(broker.tools);
556
+ if (entries.length !== expected.size || entries.some(([name, tool]) => !expected.has(name) || tool?.name !== name))
557
+ return `Codex lists tools for ${BROKER_SERVER_NAME} that do not match the broker's own tool names`;
558
+ continue;
559
+ }
560
+ const plugin = s.pluginId != null;
561
+ const off = configured[s.name]?.enabled === false && !plugin && (s.runtimeStatus == null || s.runtimeStatus === "disabled");
562
+ if (!off)
563
+ on.push(plugin ? `${s.name} (from the plugin ${JSON.stringify(s.pluginId)})` : s.name);
564
+ }
565
+ if (on.length)
566
+ return `Codex lists MCP servers it would run (${on.sort().join(", ")}; mcpServerStatus/list), where a stage-2 turn runs ${broker ? `only ${BROKER_SERVER_NAME}` : "none"}: they would run outside relay's sandbox`;
567
+ return broker && !found ? `Codex did not list relay's ${BROKER_SERVER_NAME} MCP broker (mcpServerStatus/list)` : null;
568
+ }
569
+ /** A trustworthy counter, not merely a truthy count (NaN/Infinity must not pass the evidence gate). */
570
+ function brokerSessions(broker) {
571
+ const n = broker.sessionsServed();
572
+ if (!Number.isSafeInteger(n) || n < 0)
573
+ throw new Error("the broker did not report a valid authenticated session count");
574
+ return n;
575
+ }
576
+ /** Read relay's own expected names before asking Codex to connect to any MCP server. */
577
+ async function brokerTools(broker) {
578
+ const tools = await broker.listTools();
579
+ if (!Array.isArray(tools) || tools.some((t) => typeof t?.name !== "string" || !t.name) || new Set(tools.map((t) => t.name)).size !== tools.length)
580
+ throw new Error("the broker did not report distinct tool names");
581
+ return tools.map((t) => t.name);
582
+ }
583
+ /**
584
+ * After thread/start or thread/resume (§7.1). BB takes `sessionsBeforeThread` after the successful
585
+ * threadless readback and before starting/resuming the thread. A thread connects during startup,
586
+ * before this listing, so a delta taken at the beginning of this function would be too late.
587
+ */
588
+ export async function stage2ThreadMcpProblem(rpc, eff, threadId, broker, sessionsBeforeThread) {
589
+ if (!threadId)
590
+ return stopped("Codex did not name the thread whose MCP connection relay must read back");
591
+ try {
592
+ if (broker) {
593
+ const problem = stage2BrokerConfigProblem(eff?.mcp_servers?.[BROKER_SERVER_NAME], broker);
594
+ if (problem)
595
+ return stopped(problem);
596
+ if (!Number.isSafeInteger(sessionsBeforeThread) || sessionsBeforeThread < 1)
597
+ return stopped("relay has no valid broker session checkpoint from before starting the thread");
598
+ }
599
+ const tools = broker ? await brokerTools(broker) : [];
600
+ const problem = mcpListProblem(await listedMcpServers(rpc, threadId), eff?.mcp_servers ?? {}, broker ? { url: broker.url, tools } : undefined, true);
601
+ if (problem)
602
+ return stopped(problem);
603
+ if (broker && brokerSessions(broker) <= sessionsBeforeThread)
604
+ return stopped("the broker recorded no authenticated, peer-verified thread session after relay's threadless listing");
605
+ return null;
606
+ }
607
+ catch (err) {
608
+ return stopped(`relay could not read back the thread's MCP connection (mcpServerStatus/list: ${err.message})`);
609
+ }
610
+ }
611
+ /**
612
+ * Before the prompt (§2.2 step 11; review r_0c11d860 C1+X2): Codex's own environment is absent
613
+ * from this app server. `environment/status` for `local` must answer `unknown` (Codex 0.164.0:
614
+ * `{ status: "unknown", error: "unknown environment id \`local\`" }`, as for any id the server
615
+ * does not know; `ready` when Codex registered it). Any other answer, or an error, refuses: relay
616
+ * cannot tell that the app server has nowhere unconfined to run a command. What is wrong, or null.
617
+ */
618
+ export async function stage2LocalProblem(rpc) {
619
+ let r;
620
+ try {
621
+ r = await rpc.request("environment/status", { environmentId: CODEX_LOCAL_ENVIRONMENT_ID });
622
+ }
623
+ catch (err) {
624
+ return `relay could not ask Codex whether its own ${JSON.stringify(CODEX_LOCAL_ENVIRONMENT_ID)} environment exists (environment/status: ${err.message})`;
625
+ }
626
+ if (r?.status === "unknown")
627
+ return null;
628
+ return `Codex reports its own ${JSON.stringify(CODEX_LOCAL_ENVIRONMENT_ID)} environment as ${JSON.stringify(r?.status ?? null)} (environment/status), where relay started it with none (CODEX_EXEC_SERVER_URL=none), so a command could run there, outside relay's sandbox`;
629
+ }
630
+ /**
631
+ * Readback after config/read (§2.2 step 11, broker design §7.1): no `local`, pinned features and
632
+ * subagent limits, hooks/list empty, and only the expected broker may connect.
633
+ * What is wrong, or null. `cwd`: the turn's directory, for hooks/list (else the server's own).
634
+ * `off`: the exact version-specific off-list used by the launch plan, retained for the turn.
635
+ *
636
+ * - environment/status: Codex's own `local` environment absent (stage2LocalProblem);
637
+ * - config/read: approval policy on-request; the broker's exact entry, the stdio `relay` entry off,
638
+ * and every other server off; subagent limits 6 (v1) and 4 including the parent (v2), so BA's
639
+ * session cap holds; every feature of STAGE2_FEATURES_OFF false (other values count as on);
640
+ * - experimentalFeature/list: every feature of STAGE2_FEATURES_OFF listed and off (a Codex that does
641
+ * not list one is not the Codex qualified), and nothing on but STAGE2_FEATURES_ALLOWED_ON. The
642
+ * features are what relay can read per turn of what decides the tools; the tool list itself it
643
+ * cannot see (STAGE2_TOOLS), and the per-release qualification guards it;
644
+ * - hooks/list: no hook, and no error reading them;
645
+ * - mcpServerStatus/list, last and only when everything above reads back as relay set it: exactly
646
+ * the expected broker plus switched-off servers (mcpListProblem), with fresh authenticated,
647
+ * peer-verified evidence from BA. Codex starts every enabled server once to read its tools
648
+ * (collect_mcp_server_status_snapshot_with_detail); the earlier checks ensure only the broker
649
+ * can start. Without a broker (spec.relay null), all MCP servers must remain off.
650
+ */
651
+ export async function stage2Readback(rpc, eff, cwd, broker, off = STAGE2_FEATURES_OFF) {
652
+ const wrong = [];
653
+ const local = await stage2LocalProblem(rpc);
654
+ if (local)
655
+ wrong.push(local);
656
+ if (eff?.approval_policy !== "on-request")
657
+ wrong.push(`approval_policy is ${JSON.stringify(eff?.approval_policy ?? null)} where relay set "on-request"`);
658
+ const servers = (eff?.mcp_servers ?? {});
659
+ const on = Object.entries(servers).filter(([name, s]) => !(broker && name === BROKER_SERVER_NAME) && s?.enabled !== false).map(([name]) => name);
660
+ if (on.length)
661
+ wrong.push(`MCP servers are on (${on.join(", ")}), where a stage-2 turn runs ${broker ? `only ${BROKER_SERVER_NAME}` : "none"}`);
662
+ if (broker) {
663
+ if (servers.relay?.enabled !== false)
664
+ wrong.push("Codex does not report the stdio relay MCP entry switched off");
665
+ const problem = stage2BrokerConfigProblem(servers[BROKER_SERVER_NAME], broker);
666
+ if (problem)
667
+ wrong.push(problem);
668
+ }
669
+ for (const [key, value] of [["max_concurrent_threads_per_session", 6]]) {
670
+ if (eff?.agents?.[key] !== value)
671
+ wrong.push(`agents.${key} is not ${value} where relay pinned it`);
672
+ }
673
+ const set = (eff?.features ?? {});
674
+ const notOff = off.filter((f) => set[f] !== false);
675
+ if (notOff.length)
676
+ wrong.push(`the features ${notOff.map((f) => `${f} (${JSON.stringify(set[f] ?? null)})`).join(", ")} are not false where relay set them false`);
677
+ let listed = null;
678
+ try {
679
+ listed = await listedFeatures(rpc);
680
+ }
681
+ catch (err) {
682
+ wrong.push(`relay could not read the features Codex runs with (experimentalFeature/list: ${err.message})`);
683
+ }
684
+ if (listed) {
685
+ const unlisted = off.filter((f) => !listed.has(f));
686
+ if (unlisted.length)
687
+ wrong.push(`Codex does not list the features ${unlisted.join(", ")}, so it is not a Codex relay has qualified for stage 2`);
688
+ const on = off.filter((f) => listed.has(f) && listed.get(f) !== false);
689
+ if (on.length)
690
+ wrong.push(`Codex reports ${on.join(", ")} on where relay set ${on.length > 1 ? "them" : "it"} off`);
691
+ const unqualified = [...listed].filter(([f, v]) => v !== false && !STAGE2_FEATURES_ALLOWED_ON.includes(f) && !off.includes(f)).map(([f]) => f).sort();
692
+ if (unqualified.length)
693
+ wrong.push(`Codex reports features on that relay has not qualified for stage 2 (${unqualified.join(", ")}): they may give the agent tools or actions of the app server's own, outside relay's sandbox`);
694
+ }
695
+ try {
696
+ const r = await rpc.request("hooks/list", cwd ? { cwds: [cwd] } : {});
697
+ const entries = Array.isArray(r?.data) ? r.data : null;
698
+ if (!entries)
699
+ wrong.push("Codex did not say which hooks it would run (hooks/list)");
700
+ else {
701
+ const hooks = entries.flatMap((e) => (Array.isArray(e?.hooks) ? e.hooks : e?.hooks == null ? [] : [e.hooks]));
702
+ if (hooks.length)
703
+ wrong.push(`Codex would run ${hooks.length} hook${hooks.length > 1 ? "s" : ""} (hooks/list), outside relay's sandbox`);
704
+ if (entries.some((e) => (Array.isArray(e?.errors) ? e.errors.length > 0 : e?.errors != null)))
705
+ wrong.push("Codex reported errors reading its hooks, so relay cannot tell that none would run");
706
+ }
707
+ }
708
+ catch (err) {
709
+ wrong.push(`relay could not read the hooks Codex would run (hooks/list: ${err.message})`);
710
+ }
711
+ if (!wrong.length) {
712
+ try {
713
+ const tools = broker ? await brokerTools(broker) : [];
714
+ const before = broker ? brokerSessions(broker) : 0;
715
+ const problem = mcpListProblem(await listedMcpServers(rpc), servers, broker ? { url: broker.url, tools } : undefined);
716
+ if (problem)
717
+ wrong.push(problem);
718
+ if (broker && brokerSessions(broker) <= before)
719
+ wrong.push("the broker recorded no new authenticated, peer-verified session during that MCP listing");
720
+ }
721
+ catch (err) {
722
+ wrong.push(`relay could not read the MCP servers Codex would run (mcpServerStatus/list: ${err.message})`);
723
+ }
724
+ }
725
+ return wrong.length ? `relay will not start a Codex agent under stage 2, because Codex's settings for it are not what relay set: ${wrong.join("; ")}.` : null;
726
+ }
727
+ /** Whether `a` names the turn's directory. */
728
+ const same = (a, cwd) => typeof a === "string" && canonical(a) === canonical(cwd);
729
+ /** Codex's own environment (exec-server environment.rs LOCAL_ENVIRONMENT_ID): commands there run in the app server's process tree, unconfined. A stage-2 app server has none (STAGE2_APP_SERVER_ENV). */
730
+ export const CODEX_LOCAL_ENVIRONMENT_ID = "local";
731
+ /**
732
+ * What is wrong with a thread's environments, as a phrase after "its thread", or null. Exactly
733
+ * relay's executor at `cwd` with the workspace roots `[cwd]`; or, for a thread/resume reply
734
+ * (`resumed`), that or no environment at all (`[]`: Codex 0.164's thread/resume takes no
735
+ * environments, and the app server has none of its own to default to). Never `local` or any other
736
+ * environment, on a fresh thread or a resumed one (review r_0c11d860 C1+X2): the app server was
737
+ * started without `local`, and one showing it is not the server relay set up.
738
+ */
739
+ function environmentsProblem(envs, cwd, environmentId, resumed) {
740
+ const only = `only its executor (${JSON.stringify(environmentId)})`;
741
+ if (resumed && Array.isArray(envs) && envs.length === 0)
742
+ return null;
743
+ if (!Array.isArray(envs) || envs.length !== 1) {
744
+ return `reports the environments ${JSON.stringify(envs ?? null)}${resumed ? " after thread/resume" : ""} where relay set ${only}${resumed ? " or none" : ""}, so its commands could run elsewhere`;
745
+ }
746
+ const e = envs[0];
747
+ if (e?.environmentId !== environmentId)
748
+ return `runs in the environment ${JSON.stringify(e?.environmentId ?? null)}, not relay's executor (${JSON.stringify(environmentId)})`;
749
+ if (!same(e.cwd, cwd))
750
+ return `runs in its environment at ${JSON.stringify(e.cwd ?? null)}, not at ${JSON.stringify(cwd)}`;
751
+ const roots = e.runtimeWorkspaceRoots;
752
+ if (!Array.isArray(roots) || roots.length !== 1 || !same(roots[0], cwd))
753
+ return `reports its environment's workspace roots as ${JSON.stringify(roots ?? null)} where relay set only ${JSON.stringify(cwd)}`;
754
+ return null;
755
+ }
756
+ /**
757
+ * The thread's reply (§2.2 step 11): profile, sandbox kind, environments. What is wrong, or null.
758
+ * Shape as Codex 0.164.0 replies to thread/start and thread/resume: approvalPolicy,
759
+ * activePermissionProfile, sandbox and runtimeWorkspaceRoots at the top, the environments on
760
+ * `thread` (each with its cwd and runtimeWorkspaceRoots). A thread/start reply must show exactly
761
+ * relay's executor. A thread/resume reply (`resumed`) shows relay's executor or, as Codex 0.164
762
+ * replies, nothing (environmentsProblem), since thread/resume takes no environments and the app
763
+ * server has no `local` to default to; with nothing, it reports no workspace roots either. The turn's
764
+ * binding then gives it relay's executor (stage2TurnParams), read back after turn/start
765
+ * (stage2TurnReadback). `local` is refused on both. The workspace roots are checked here, not by
766
+ * threadPermissionsProblem (codex-app.ts), which leaves a relay-enforced thread's to this check.
767
+ */
768
+ export function stage2ThreadProblem(t, cwd, environmentId, o = {}) {
769
+ const refuse = (why) => `relay will not start a Codex agent under stage 2, because its thread ${why}.`;
770
+ const r = (t ?? {});
771
+ if (r.approvalPolicy !== "on-request")
772
+ return refuse(`reports the approval policy ${JSON.stringify(r.approvalPolicy ?? null)} where relay set "on-request", so the app server could approve its own actions`);
773
+ if (r.activePermissionProfile?.id !== FULL_ACCESS)
774
+ return refuse(`runs with the permission profile ${JSON.stringify(r.activePermissionProfile?.id ?? null)} where relay set ${JSON.stringify(FULL_ACCESS)}`);
775
+ if (r.sandbox?.type !== "dangerFullAccess")
776
+ return refuse(`reports a ${JSON.stringify(r.sandbox?.type ?? null)} sandbox where relay set "dangerFullAccess"`);
777
+ const wrong = environmentsProblem(r.thread?.environments, cwd, environmentId, Boolean(o.resumed));
778
+ if (wrong)
779
+ return refuse(wrong);
780
+ // Codex reports the primary environment's workspace roots as the thread's (core session.rs
781
+ // primary_workspace_roots_for), whatever runtimeWorkspaceRoots asked: a resumed thread with no
782
+ // environment reports none (seen on 0.164.0 without `local`), and relay's binding then gives it its
783
+ // executor with the roots [cwd], read back after turn/start (stage2TurnReadback).
784
+ const roots = r.runtimeWorkspaceRoots;
785
+ const unbound = Boolean(o.resumed) && Array.isArray(r.thread?.environments) && r.thread.environments.length === 0;
786
+ if (unbound && Array.isArray(roots) && roots.length === 0)
787
+ return null;
788
+ if (!Array.isArray(roots) || roots.length !== 1 || !same(roots[0], cwd))
789
+ return refuse(`reports the workspace roots ${JSON.stringify(roots ?? null)} where relay set only ${JSON.stringify(cwd)}`);
790
+ return null;
791
+ }
792
+ /**
793
+ * Before thread/resume of a stage-2 session: no message waits in the session's Codex queue. Codex
794
+ * starts a queued message by itself as soon as thread/resume leaves the thread idle (ext/queue
795
+ * on_thread_idle), before relay's turn/start can bind that turn to the executor. With Codex's own
796
+ * `local` registered it ran with `[local, relay]`, its command in `local` (WP-C, 2026-10-28, on
797
+ * 0.164.0, a message queued through thread/queue/add on the stored thread). On a stage-2 app
798
+ * server, which has no `local` (STAGE2_APP_SERVER_ENV), such a turn has no environment and cannot
799
+ * run a command; this check, which a message queued after it passes cannot satisfy anyway, stays as
800
+ * defence in depth, with Stage2TurnGuard. Only a client of the person's CODEX_HOME can queue (relay
801
+ * never does; the executor cannot reach CODEX_HOME, D8). What is wrong, or null; an unreadable
802
+ * queue refuses.
803
+ */
804
+ export async function stage2QueueProblem(rpc, threadId) {
805
+ const refuse = (why) => `relay will not resume this Codex session under stage 2, because ${why}.`;
806
+ let r;
807
+ try {
808
+ r = await rpc.request("thread/queue/list", { threadId, limit: 1 });
809
+ }
810
+ catch (err) {
811
+ return refuse(`it could not read the session's queued messages (thread/queue/list: ${err.message}), and Codex would start one by itself on resume, before relay can bind that turn to its sandboxed executor`);
812
+ }
813
+ if (!Array.isArray(r?.data))
814
+ return refuse("Codex did not say whether the session has queued messages (thread/queue/list), and it would start one by itself on resume, before relay can bind that turn to its sandboxed executor");
815
+ if (r.data.length)
816
+ return refuse("a message is queued for the session in Codex (put there by another Codex client), and Codex would start it by itself on resume, before relay can bind that turn to its sandboxed executor; send or remove it from that client, then resume again");
817
+ return null;
818
+ }
819
+ /** A stage-2 turn relay stops after the prompt went in: the app server is killed, the turn fails. */
820
+ const stopped = (why) => `relay stopped the Codex agent under stage 2 and failed the turn, because ${why}.`;
821
+ /**
822
+ * thread/read's refusal while a new thread's rollout has no session metadata yet: Codex creates the
823
+ * rollout file at once and writes its first line only after collecting the git information of a git
824
+ * cwd (rollout recorder.rs write_session_meta, git-utils collect_git_info: up to two git commands
825
+ * with a 5 s timeout each), and thread/read of a loaded thread reads that line first (thread_processor.rs
826
+ * read_thread_view, load_persisted_thread_for_read). Measured on 0.164.0: about 20 ms after
827
+ * turn/start's reply in a small repository; never in a plain directory, where no rollout exists
828
+ * yet and the live thread is read instead.
829
+ */
830
+ const ROLLOUT_NOT_YET_WRITTEN = /failed to read session metadata .*: rollout at .* is empty/;
831
+ /** How long stage2TurnReadback retries that refusal, at most: Codex's own worst case for the git information (two 5 s timeouts). */
832
+ export const TURN_READBACK_DEADLINE_MS = 10_000;
833
+ const TURN_READBACK_RETRY_MS = 25;
834
+ /**
835
+ * After a stage-2 turn/start: the thread's environments, read back (thread/read reports the live
836
+ * thread's, apply_live_thread_settings), must be exactly relay's executor at `cwd`. What is wrong,
837
+ * or null; the caller kills the app server and fails the turn.
838
+ *
839
+ * thread/read is retried only on the refusal of a rollout not written yet
840
+ * (ROLLOUT_NOT_YET_WRITTEN), every TURN_READBACK_RETRY_MS, until `deadlineMs` after the first try;
841
+ * any other error, or the deadline passing, refuses. relay asks for no other read: the
842
+ * environments are on no notification (turn/started's Turn and thread/settings/updated's
843
+ * ThreadSettings carry none), and thread/loaded/list gives ids only.
844
+ *
845
+ * What this proves and what it does not. The binding travels in the same request as the prompt,
846
+ * and Codex applies it before starting the turn (stage2TurnParams), so there is no window between
847
+ * binding and prompt. The readback, once it succeeds, proves that the live thread is bound to relay's
848
+ * executor alone after the prompt went in. It runs after turn/start's reply, while the model may
849
+ * already be answering: it catches a Codex that ignored or reverted `turn/start.environments`, but
850
+ * only after the fact. Were that so on a resumed thread, the turn would have no environment (the
851
+ * app server has no `local`, STAGE2_APP_SERVER_ENV), so its commands would fail, not run elsewhere;
852
+ * the per-release qualification still checks the binding (codex-stage2.mjs item 11, resumed and
853
+ * bound). Nor does it see the environments of a turn Codex started by itself, into which turn/start
854
+ * steered: thread/read reports the thread's sticky settings, which turn/start changed, not that
855
+ * turn's (Stage2TurnGuard fails such a turn; it has no environment either). The retries add no
856
+ * window of their own: a resumed thread's rollout is already written, so they happen only on a fresh
857
+ * thread, whose thread/start reply has already shown relay's executor alone.
858
+ */
859
+ export async function stage2TurnReadback(rpc, threadId, cwd, environmentId, o = {}) {
860
+ const refuse = stopped;
861
+ const until = Date.now() + (o.deadlineMs ?? TURN_READBACK_DEADLINE_MS);
862
+ let r;
863
+ for (;;) {
864
+ try {
865
+ r = await rpc.request("thread/read", { threadId, includeTurns: false });
866
+ break;
867
+ }
868
+ catch (err) {
869
+ const message = err.message;
870
+ if (!ROLLOUT_NOT_YET_WRITTEN.test(message))
871
+ return refuse(`it could not read back the environments of the turn it had bound to its sandboxed executor (thread/read: ${message})`);
872
+ if (Date.now() >= until)
873
+ return refuse(`it could not read back the environments of the turn it had bound to its sandboxed executor within ${Math.round((o.deadlineMs ?? TURN_READBACK_DEADLINE_MS) / 1000)} s: Codex had not yet written the thread's session (thread/read: ${message})`);
874
+ await new Promise((res) => setTimeout(res, o.retryMs ?? TURN_READBACK_RETRY_MS));
875
+ }
876
+ }
877
+ const wrong = environmentsProblem(r?.thread?.environments, cwd, environmentId, false);
878
+ return wrong ? refuse(`after relay bound the turn to its sandboxed executor, the thread ${wrong}`) : null;
879
+ }
880
+ /**
881
+ * The turns Codex starts during a stage-2 turn (WP-C). relay binds only the turn it asks for
882
+ * (stage2TurnParams). A turn Codex starts by itself is not bound: a goal continuation or a queued or
883
+ * mailbox message on resume (goals pinned off, stage2QueueProblem before resume), or whatever a later
884
+ * Codex adds. It cannot run a command, since the app server has no environment of its own
885
+ * (STAGE2_APP_SERVER_ENV) and a resumed thread none until relay binds it; with Codex's `local` it ran
886
+ * there (review r_0c11d860 C1+X2). Defence in depth: any turn that starts before relay asks for its
887
+ * own, and any second turn on the session's thread beside relay's, fails the turn;
888
+ * startCodexAppTurn kills the app server first. Subagents' turns (other threads) after relay's
889
+ * request are expected: they take the bound turn's environments.
890
+ *
891
+ * This sees `turn/started`, which Codex sends as the turn begins and before it asks the model, and
892
+ * relay kills the server at once. It is not what keeps such a turn's commands in relay's sandbox
893
+ * (there is nowhere else for them to run); it keeps relay from reporting another turn's work as its own.
894
+ */
895
+ export class Stage2TurnGuard {
896
+ #requested = false;
897
+ #own = null;
898
+ #seen = null;
899
+ /** relay is about to send its turn/start. */
900
+ request() {
901
+ this.#requested = true;
902
+ }
903
+ /** A turn/started notification: the thread it names, the session's thread, the turn's id. What is wrong, or null. */
904
+ started(thread, sessionThread, turn) {
905
+ const id = typeof turn === "string" ? turn : null;
906
+ if (!this.#requested)
907
+ return stopped(`Codex started a turn by itself (${JSON.stringify(id)}) before relay had delivered the prompt and bound the turn to its sandboxed executor`);
908
+ if (typeof thread === "string" && thread !== sessionThread)
909
+ return null;
910
+ const ours = this.#own ?? this.#seen;
911
+ if (ours !== null && id !== ours)
912
+ return stopped(`Codex started a second turn (${JSON.stringify(id)}) on the session's thread beside relay's (${JSON.stringify(ours)}), which relay did not bind to its sandboxed executor`);
913
+ this.#seen ??= id;
914
+ return null;
915
+ }
916
+ /** turn/start's reply. What is wrong, or null. */
917
+ replied(turn) {
918
+ const id = typeof turn === "string" && turn ? turn : null;
919
+ if (!id)
920
+ return stopped("Codex did not say which turn it started for relay's prompt");
921
+ this.#own = id;
922
+ if (this.#seen !== null && this.#seen !== id)
923
+ return stopped(`relay's prompt went into turn ${JSON.stringify(id)} while Codex had started turn ${JSON.stringify(this.#seen)} on the session's thread`);
924
+ return null;
925
+ }
926
+ }
927
+ /**
928
+ * Before relay shows a stage-2 command approval (review R4): Codex names the environment the
929
+ * command will run in (CommandExecutionRequestApprovalParams.environmentId, app-server-protocol
930
+ * v2/item.rs; set for unified exec, write_stdin and network approvals, core tools/approvals.rs).
931
+ * Only relay's executor is acceptable: a command bound anywhere else, or with no environment named,
932
+ * is declined and fails the turn. What is wrong, or null. File-change approvals name no environment
933
+ * (FileChangeRequestApprovalParams), so there is nothing to check here; stage2ApprovalDetail leaves
934
+ * them unmarked.
935
+ */
936
+ export function stage2CommandEnvironmentProblem(environmentId, expected) {
937
+ if (environmentId === expected)
938
+ return null;
939
+ return stopped(`Codex asked to approve a command in the environment ${JSON.stringify(environmentId ?? null)}, not relay's sandboxed executor (${JSON.stringify(expected)}); relay declined it`);
940
+ }
941
+ /**
942
+ * The detail added to a stage-2 approval (§2.4, C9). A command approval is marked confined: relay
943
+ * shows it only once stage2CommandEnvironmentProblem has found it bound to the executor. A
944
+ * file-change approval is left unmarked: Codex names no environment for it, and neither its item
945
+ * (ThreadItem::FileChange) nor the request carries one relay could check, so it keeps the
946
+ * outside-the-sandbox wording (review R4), although with the turn bound to the executor alone
947
+ * (stage2TurnReadback) its apply_patch runs there. Any other kind (an MCP tool, an extension, a
948
+ * hosted tool) keeps its normal accounting (core/approvals.ts) and is an error here.
949
+ */
950
+ export function stage2ApprovalDetail(kind) {
951
+ if (kind !== "command" && kind !== "file")
952
+ throw new Error(`relay does not mark a ${JSON.stringify(kind)} approval as inside its sandbox`);
953
+ return kind === "command" ? { confined: true } : {};
954
+ }
955
+ /** Records a turn's enforcement in the session's params (CONFINEMENT_PARAM), for status, brief and the approval view. */
956
+ export function recordEnforcement(nodeId, turnId, enforcement) {
957
+ if (enforcement !== "codex" && enforcement !== "relay")
958
+ throw new Error(`not an enforcement: ${JSON.stringify(enforcement)}`);
959
+ setParam(nodeId, CONFINEMENT_PARAM, { turn: turnId, enforcement });
960
+ }
961
+ /**
962
+ * The per-turn asset directory for relay's skill package, readable by commands and outside every
963
+ * writable root (§2.3, C8). Null when the turn has no package. The package relay built is in its
964
+ * control directory, which relay's profile denies; this copy (directories and regular files only)
965
+ * goes to a fresh `relay-ext-*` under relay's private root (~/.relay-t, mode 0700), which no grant
966
+ * may cover and the profile does not make writable. The caller removes it when the turn ends.
967
+ * Returns the copy's root, laid out as the package (`skills/<name>/…`).
968
+ */
969
+ export function stage2SkillAssets(spec) {
970
+ if (!spec.skills)
971
+ return null;
972
+ const from = path.join(spec.skills.dir, "skills");
973
+ const root = privateTurnTemp(ensurePrivateRoot(privateStateRoot()), "relay-ext-");
974
+ try {
975
+ const copy = (src, dst) => {
976
+ fs.mkdirSync(dst, { mode: 0o700 });
977
+ for (const ent of fs.readdirSync(src, { withFileTypes: true })) {
978
+ const s = path.join(src, ent.name), d = path.join(dst, ent.name);
979
+ if (ent.isDirectory())
980
+ copy(s, d);
981
+ else if (ent.isFile())
982
+ fs.copyFileSync(s, d, fs.constants.COPYFILE_EXCL);
983
+ else
984
+ throw new Error(`${s} is neither a directory nor a regular file`);
985
+ }
986
+ };
987
+ copy(from, path.join(root, "skills"));
988
+ for (const name of spec.skills.names) {
989
+ if (!fs.lstatSync(path.join(root, "skills", name, "SKILL.md")).isFile())
990
+ throw new Error(`the skill ${name} has no SKILL.md`);
991
+ }
992
+ return root;
993
+ }
994
+ catch (err) {
995
+ fs.rmSync(root, { recursive: true, force: true });
996
+ throw new Error(`relay could not copy the turn's skills where its commands can read them: ${err.message}`);
997
+ }
998
+ }