@jbkjr/relay 0.0.0-stage → 1.2.2

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 +393 -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 +1539 -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 +345 -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 +641 -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 +345 -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 +635 -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 +1518 -0
  186. package/docs/pinned-codex.md +333 -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,641 @@
1
+ import { openaiRefusal } from "../core/refusal.js";
2
+ import { assertNeverAdapter } from "./never-admission.js";
3
+ import { codexSignIn, freezeCodexConfig, prepareCodexHome } from "./codex-pin.js";
4
+ import { relayCodexProtected } from "../core/protected-config.js";
5
+ import { neverGrantProblem, neverProfileInputs, resolveNeverPolicy } from "../core/never-policy.js";
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { nativeTemp } from "./native-temp.js";
10
+ import { codexVersion, daybreakCatalog, daybreakDecision, skipDaybreak } from "./codex-daybreak.js";
11
+ import { authFor, canonical, RELAY_CLI, relayCodexHome } from "../core/config.js";
12
+ import { spawnFound } from "../core/executables.js";
13
+ import { codexSkillFiles } from "../core/extensions.js";
14
+ import { targetDef } from "../targets/index.js";
15
+ import { archiveCodexThread, CODEX_PROFILE, codexNetworkPreflight, codexPreflight, declinedItem, startCodexAppTurn } from "./codex-app.js";
16
+ import { NETWORK_MODE_TEXT } from "./codex-network.js";
17
+ import { MEDIATED_NETWORK_EFFECT, mediatedBaseline } from "../core/mediated-network-provider.js";
18
+ import { openStage2 } from "./codex-env.js";
19
+ import { stage2Wanted } from "./codex-stage2.js";
20
+ import { localModeInterlock, localModeRetired, RAW_NETWORK_TURN_NOTE } from "../core/raw-network.js";
21
+ import { HARNESS_CONFIG } from "../confine/seatbelt.js";
22
+ import { BROKER_SERVER_NAME, BROKER_TOKEN_ENV } from "../confine/broker-names.js";
23
+ import { agentEnv, releasedIn } from "./env.js";
24
+ import { CODEX_MCP_ENV_VARS, codexToolTimeoutS, codexWriteRootProblem } from "../targets/codex.js";
25
+ import { afterTurn, streamTurn } from "./stream.js";
26
+ import { CodexSubagents } from "./codex-subagents.js";
27
+ import { activityOf, usageFrom, relayServerCommand, turnPolicy } from "./types.js";
28
+ const scrub = () => false;
29
+ /**
30
+ * A string, or an array of strings, as a TOML value for a `-c` override. A TOML basic string takes
31
+ * the escapes JSON.stringify writes, but differs from a JSON string in two places: it may not hold
32
+ * DEL (U+007F) as it is, which JSON leaves unescaped, so it is escaped here; and it is UTF-8, so a
33
+ * lone UTF-16 surrogate, which JSON writes as a \uD8xx escape, is no Unicode scalar value TOML can
34
+ * hold in any form. Such a value is refused: Codex would refuse the whole override, with an error
35
+ * about TOML that names nothing relay set. (A granted directory never holds one: relay takes its
36
+ * name from the disk, which gives none.)
37
+ */
38
+ export function toml(v) {
39
+ for (const s of typeof v === "string" ? [v] : v) {
40
+ if (/\p{Cs}/u.test(s))
41
+ throw new Error(`relay cannot give Codex ${JSON.stringify(s)}: it holds a lone UTF-16 surrogate, which no TOML string can hold, so relay does not start the agent.`);
42
+ }
43
+ return JSON.stringify(v).replaceAll("\x7f", "\\u007f");
44
+ }
45
+ const codex = {
46
+ prepare(spec, tmpDir) {
47
+ // The agent's environment, built and checked first (review C6): its endpoint is refused before Codex is asked anything.
48
+ const env = agentEnv(spec, scrub);
49
+ env.CODEX_HOME = prepareCodexHome(spec.config);
50
+ const released = releasedIn(env);
51
+ env.TMPDIR = tmpDir;
52
+ spec.checkEnvironment?.(env);
53
+ if (spec.config.child_mcp !== "relay-only")
54
+ return { servers: [], env, released };
55
+ // Names of the MCP servers defined in the user's config, so they can be switched off for the
56
+ // child. Plugin-provided servers are excluded here: a -c override cannot disable those (it
57
+ // would create a second, broken entry), so they are dropped with `--disable plugins` instead.
58
+ const r = spawnFound(spec.config.targets.codex.bin, ["--disable", "plugins", "mcp", "list", "--json"], { encoding: "utf8", timeout: 20000, env }, env.PATH ?? "");
59
+ // The agent is not launched unless its other MCP servers can be named and switched off:
60
+ // they run outside its sandbox, with whatever access the user gave them.
61
+ const refuse = (why) => new Error(`relay could not list Codex's MCP servers (${why}), so it cannot switch them off for a launched agent and will not start one.`);
62
+ if (r.error)
63
+ throw refuse(r.error.message);
64
+ if (r.status !== 0)
65
+ throw refuse(`codex mcp list exited with ${r.status}: ${(r.stderr ?? "").trim().split("\n").pop() ?? ""}`);
66
+ let list;
67
+ try {
68
+ list = JSON.parse(r.stdout);
69
+ }
70
+ catch {
71
+ throw refuse("its output was not JSON");
72
+ }
73
+ if (!Array.isArray(list) || list.some((s) => !s || typeof s.name !== "string"))
74
+ throw refuse("its output was not a list of named servers");
75
+ return { servers: list.filter((s) => s.enabled !== false).map((s) => s.name), env, released };
76
+ },
77
+ /** `model`: the model the preflight checked a faster speed against where the turn names none (a continued thread's own). */
78
+ invocation(spec, prepared, flags, model) {
79
+ const cfg = spec.config;
80
+ const off = flags.off;
81
+ const c = [...flags.c];
82
+ if (spec.model ?? model)
83
+ c.push("-m", (spec.model ?? model));
84
+ if (spec.effort)
85
+ c.push("-c", `model_reasoning_effort=${toml(spec.effort)}`);
86
+ const common = ["--json", "--skip-git-repo-check", ...off, ...c];
87
+ const args = spec.sessionId ? ["exec", "resume", ...common, spec.sessionId, "-"] : ["exec", ...common, "-"];
88
+ return { command: cfg.targets.codex.bin, args, env: prepared.env };
89
+ },
90
+ /**
91
+ * The `codex exec` fallback's check, first, through a short-lived app server: the fallback cannot
92
+ * ask the server it is about to use. If that cannot be done, the agent is not started. Run in the
93
+ * worker itself, with the agent's environment, so that a stop can end it (spec.signal).
94
+ */
95
+ async preflight(spec, flags, env) {
96
+ let checked;
97
+ const problem = await codexPreflight({
98
+ bin: spec.config.targets.codex.bin, args: ["app-server", ...flags.off, ...flags.c], cwd: spec.cwd, env, expect: flags.expect, sessionId: spec.sessionId, model: spec.model, signal: spec.signal, onWaived: spec.onWaived,
99
+ onModel: (m) => (checked = m),
100
+ onDaybreakSkipped: (note) => skipDaybreak(flags, spec.onNote, note),
101
+ released: flags.released, onShellPolicyNote: (note) => spec.onNote?.(note),
102
+ });
103
+ if (problem)
104
+ throw new Error(problem.trim());
105
+ return checked;
106
+ },
107
+ /** Archives a durable thread once the turn's processes have stopped: ephemeral threads cannot survive relay's per-turn processes, and a fresh server also handles crashes and the exec fallback. */
108
+ async finish(spec, flags, env, result) {
109
+ const threadId = result.sessionId ?? spec.sessionId;
110
+ if (!threadId)
111
+ return result;
112
+ // The turn's app server and broker have already stopped. The separate archive client must
113
+ // neither reconnect to the released port nor inherit a dead turn's credential (§6).
114
+ const archiveEnv = flags.expect.broker ? { ...env } : env;
115
+ if (flags.expect.broker)
116
+ delete archiveEnv[BROKER_TOKEN_ENV];
117
+ const archiveFlags = flags.expect.broker ? [...flags.c, "-c", `mcp_servers.${BROKER_SERVER_NAME}.enabled=false`] : flags.c;
118
+ const warning = await archiveCodexThread({
119
+ bin: spec.config.targets.codex.bin, args: ["app-server", ...flags.off, ...archiveFlags],
120
+ cwd: spec.cwd, env: archiveEnv, threadId,
121
+ });
122
+ return warning ? { ...result, warnings: [...(result.warnings ?? []), warning] } : result;
123
+ },
124
+ onEvent(event, state, spec) {
125
+ const item = event.item;
126
+ if (!state.ended && ["item.started", "item.updated", "item.completed"].includes(String(event.type)) && item?.type === "collab_tool_call") {
127
+ const subagents = state.codexSubagents ??= new CodexSubagents();
128
+ subagents.collab(item, state.sessionId);
129
+ const warning = subagents.warning();
130
+ state.warnings = warning ? [warning] : [];
131
+ }
132
+ switch (event.type) {
133
+ case "item.started": {
134
+ const text = item?.type ? activityOf(item.type, item) : null;
135
+ if (text)
136
+ spec.onActivity?.(text);
137
+ break;
138
+ }
139
+ case "thread.started":
140
+ if (typeof event.thread_id === "string")
141
+ state.sessionId = event.thread_id;
142
+ break;
143
+ case "item.completed": {
144
+ // The final answer is the last agent_message. Items of type "error" are warnings, not failure.
145
+ if (item?.type === "agent_message" && typeof item.text === "string")
146
+ state.finalMessage = item.text;
147
+ const refused = declinedItem(event.item);
148
+ if (refused)
149
+ state.denials = [...(state.denials ?? []), refused];
150
+ break;
151
+ }
152
+ case "turn.completed": {
153
+ const usage = usageFrom(event.usage);
154
+ if (usage)
155
+ spec.onUsage?.(usage);
156
+ // An earlier "error" event can be a retried, non-fatal one; a completed turn supersedes it.
157
+ state.completed = true;
158
+ state.failed = undefined;
159
+ state.ended = true;
160
+ break;
161
+ }
162
+ case "turn.failed":
163
+ state.refusal ??= openaiRefusal(event.error);
164
+ state.failed = `codex turn failed: ${event.error?.message ?? "unknown error"}`;
165
+ state.ended = true;
166
+ break;
167
+ case "error":
168
+ state.refusal ??= openaiRefusal({ message: event.message });
169
+ state.failed = `codex error: ${String(event.message ?? "unknown error")}`;
170
+ break;
171
+ }
172
+ },
173
+ };
174
+ export const codexBackend = {
175
+ start: async (spec) => nativeTemp(spec, async (tmpDir) => {
176
+ assertNeverAdapter(spec);
177
+ spec = { ...spec, config: freezeCodexConfig(spec.config) };
178
+ // Relay's config refuses this combination; a run's stored config is checked again here.
179
+ if ((spec.skills || spec.extensionServers?.length) && spec.config.codex_backend === "exec") {
180
+ throw new Error('extensions for Codex need codex_backend "app-server": codex exec has no way for relay to give skills or to check which skills it loads, so relay does not start the agent.');
181
+ }
182
+ const prepared = codex.prepare(spec, tmpDir);
183
+ if (spec.overlay && !stage2Wanted(spec))
184
+ throw new Error("capability_unavailable: a consumed overlay requires the qualified stage2 executor; no baseline fallback");
185
+ // Stage 2 (docs/codex-confinement-design.md): the executor in relay's Seatbelt. Never taken with the switch off.
186
+ const stage2 = stage2Wanted(spec) ? await openStage2(spec, prepared, tmpDir) : undefined;
187
+ try {
188
+ const chosen = stage2 ? undefined : await chooseNetwork(spec, prepared, tmpDir);
189
+ const flags = codexFlags(spec, prepared.servers, prepared.env, prepared.released, chosen?.net, stage2?.plan);
190
+ if (flags.note)
191
+ spec.onNote?.(flags.note);
192
+ if (chosen)
193
+ spec.onNote?.(chosen.note);
194
+ // What the shell's network is this turn, in front of the turn's input: the preamble said only
195
+ // that the job has network.
196
+ // A stage-2 turn skips chooseNetwork, so its own note (raw network, PORT/PORTS, binding limited
197
+ // to the block, git writes fail and relay commits) goes in front instead.
198
+ const prefix = chosen?.prefix ?? (stage2 ? stage2InputPrefix(spec) : undefined);
199
+ const turn = prefix ? { ...spec, prompt: `${prefix}\n\n${spec.prompt}` } : spec;
200
+ // A stage-2 app server gets exactly the environment its admission checked, with relay's own
201
+ // CODEX_EXEC_SERVER_URL=none over it (Stage2Session.env): Codex then has no `local` environment.
202
+ const env = stage2 ? stage2.session.env : prepared.env;
203
+ let handle;
204
+ if (spec.config.codex_backend !== "exec") {
205
+ turnPolicy(spec); // Last check after config/skill discovery, immediately before spawn.
206
+ handle = startCodexAppTurn(turn, flags, env, stage2?.session);
207
+ }
208
+ else {
209
+ const checked = await codex.preflight(spec, flags, env);
210
+ turnPolicy(spec); // Recheck grant identities after the asynchronous preflight.
211
+ handle = streamTurn(turn, { invocation: codex.invocation(turn, prepared, flags, checked), onEvent: codex.onEvent });
212
+ }
213
+ return afterTurn(handle, (result) => codex.finish(spec, flags, env, result));
214
+ }
215
+ catch (err) {
216
+ // Before startCodexAppTurn owns the executor, a failure stops it here.
217
+ await stage2?.abort(err.message);
218
+ throw err;
219
+ }
220
+ }),
221
+ };
222
+ /**
223
+ * What doctor says about a new Codex job started in `cwd` with no grants, by the checks that job's
224
+ * turn makes before it starts: the never floor a new run captures (resolveNeverPolicy, as
225
+ * checkpointNever does for a run's first launch) and its admission (assertNeverAdapter,
226
+ * neverGrantProblem), the turn's own preparation (codex.prepare: the agent's environment, relay's
227
+ * Codex home and the config.toml relay writes there each turn, the user MCP servers it switches
228
+ * off), its flags (codexFlags), and the effective-configuration check (codexPreflight), in which a
229
+ * short-lived app server reports every layer merged: system, managed, this directory's project
230
+ * layers, relay's Codex home and relay's flags. The job is the configured default: its default
231
+ * model, effort and speed, and relay's own MCP server, which a job that may delegate is given. That
232
+ * server's command is an inert one of the real shape (relayServerCommand reads the run's registry,
233
+ * which doctor must not open); the app server is asked only for its configuration, so it never
234
+ * starts. No thread is started and no model is asked.
235
+ *
236
+ * - `problem`: why relay would refuse the job, or null.
237
+ * - `unchecked`: why the check could not be made here (relay's Codex home could not be prepared,
238
+ * say, as inside a launched agent whose sandbox denies it), which says nothing of a real turn.
239
+ * - `note`: what Codex's shell_environment_policy does with the names relay releases, when the turn would say so.
240
+ * - `released`: those names.
241
+ * - `stage2`: the job would run under stage 2 instead, which this does not judge (doctor's "codex stage 2" line does).
242
+ * - `account`: how the app server says relay's Codex home is signed in (account/read's account type,
243
+ * null for no account), read before any check; absent when it was not asked or did not say.
244
+ */
245
+ export async function codexLaunchCheck(cfg, cwd, access) {
246
+ const none = { problem: null, unchecked: null, note: null, released: [], stage2: false };
247
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "relay-doctor-codex-"));
248
+ try {
249
+ const config = freezeCodexConfig(cfg);
250
+ const t = config.targets.codex;
251
+ const spec = {
252
+ target: targetDef("codex"), prompt: "", cwd, access, config,
253
+ relay: { runId: "doctor", nodeId: "doctor", depth: 1, contextFile: path.join(tmp, "context.json"), mayDelegate: true, mayAsk: false },
254
+ ...(t.default_model ? { model: t.default_model } : {}), ...(t.default_effort ? { effort: t.default_effort } : {}), ...(t.speed ? { speed: t.speed } : {}),
255
+ neverPolicy: resolveNeverPolicy({ never: config.never, codexHome: t.home }),
256
+ dir: tmp, logPath: path.join(tmp, "log"), markers: { runId: "doctor", nodeId: "doctor", depth: 1 },
257
+ };
258
+ if (stage2Wanted(spec))
259
+ return { ...none, stage2: true };
260
+ try {
261
+ prepareCodexHome(config);
262
+ }
263
+ catch (err) {
264
+ return { ...none, unchecked: `relay could not prepare its Codex home here (${err.message})` };
265
+ }
266
+ const inert = (ctx) => ({
267
+ command: "/usr/bin/env", args: ["-i", `RELAY_RUN_ID=${ctx.runId}`, `RELAY_NODE_ID=${ctx.nodeId}`, `RELAY_DEPTH=${ctx.depth}`, "RELAY_INJECTED=1", process.execPath, RELAY_CLI, "mcp", "--context", ctx.contextFile], env: {},
268
+ });
269
+ let prepared;
270
+ let flags;
271
+ try {
272
+ assertNeverAdapter(spec);
273
+ const grantProblem = neverGrantProblem(spec.neverPolicy, {}, access === "write" ? [cwd] : []);
274
+ if (grantProblem)
275
+ throw new Error(grantProblem);
276
+ prepared = codex.prepare(spec, tmp);
277
+ flags = codexFlags(spec, prepared.servers, prepared.env, prepared.released, undefined, undefined, inert);
278
+ }
279
+ catch (err) {
280
+ return { ...none, problem: err.message };
281
+ }
282
+ let note = null;
283
+ let account;
284
+ const problem = await codexPreflight({
285
+ bin: t.bin, args: ["app-server", ...flags.off, ...flags.c], cwd, env: prepared.env, expect: flags.expect, model: spec.model,
286
+ released: flags.released, onShellPolicyNote: (n) => (note = n), onAccount: (type) => (account = type),
287
+ });
288
+ return { ...none, problem: problem?.trim() ?? null, note, released: flags.released, ...(account !== undefined ? { account } : {}) };
289
+ }
290
+ finally {
291
+ fs.rmSync(tmp, { recursive: true, force: true });
292
+ }
293
+ }
294
+ /** The effective stage-2 shell authority stated at the front of the model input. */
295
+ export function stage2InputPrefix(spec) {
296
+ const baseline = mediatedBaseline(spec.grant, spec.config);
297
+ const mediated = Boolean(baseline?.network && !baseline.raw_network
298
+ || spec.overlay?.request.capabilities.some(c => c.kind === "network" && c.mode === "mediated"));
299
+ const mediatedNote = `[relay] This turn uses stage-2 mediated network. ${MEDIATED_NETWORK_EFFECT}`;
300
+ if (spec.overlay) {
301
+ const overlay = `[relay] This new turn has the approved one-turn overlay ${spec.overlay.id}: ${JSON.stringify(spec.overlay.request.capabilities)}. It expires after this turn or its enforced deadline; standing grants are unchanged.`;
302
+ return mediated ? `${overlay}\n${mediatedNote}` : overlay;
303
+ }
304
+ if (spec.grant?.raw_network)
305
+ return RAW_NETWORK_TURN_NOTE;
306
+ if (mediated)
307
+ return mediatedNote;
308
+ return "[relay] Commands run in relay's stage-2 sandbox with direct network, UDP and DNS disabled. Ask relay to escalate for public network through a one-turn proxy when the task needs it.";
309
+ }
310
+ /**
311
+ * The shell network of a Codex turn given network (a grant or child_network; allow_dangerous aside,
312
+ * which has no sandbox): strict through Codex's proxy, or local for a write job whose grant says
313
+ * local_network (the person consented before the turn: session.ts), where a short-lived app server
314
+ * started with exactly those settings proves the proxy is there (codexNetworkPreflight); otherwise
315
+ * Codex's hosted web search only. Undefined for a turn without network. `note` is for the job's
316
+ * notes (so the caller sees which the turn got), `prefix` for the turn's input.
317
+ */
318
+ async function chooseNetwork(spec, prepared, tmpDir) {
319
+ const { dangerous, network } = turnPolicy(spec);
320
+ if (!network || dangerous)
321
+ return undefined;
322
+ const write = spec.access === "write";
323
+ const said = (mode, why) => ({
324
+ net: mode === "hosted" ? { mode } : { mode, sockets: write ? [canonical(tmpDir), ...(ownWorktree(spec) ? [canonical(spec.cwd)] : [])] : [] },
325
+ note: why ? `Codex network: ${NETWORK_MODE_TEXT.hosted}, because ${why}.` : `Codex network: ${NETWORK_MODE_TEXT[mode]}.`,
326
+ prefix: why
327
+ ? `[relay] This turn your shell has no network: ${why}. Codex's hosted web search still works.`
328
+ : `[relay] This turn your shell's network is ${NETWORK_MODE_TEXT[mode]}.`,
329
+ });
330
+ // The exec fallback has never given a read turn shell network (codexPermissions).
331
+ if (!write && spec.config.codex_backend === "exec")
332
+ return said("hosted");
333
+ const mode = write && spec.grant?.local_network ? "local" : "strict";
334
+ // Stage 2 switched on: no local mode at all (raw-network.ts localModeRetired, decision D2). session.ts
335
+ // has refused such a turn already; this refuses the launch rather than run it with less.
336
+ const retired = mode === "local" ? localModeRetired(spec.config) : null;
337
+ if (retired)
338
+ throw new Error(`relay does not start the Codex agent: ${retired}.`);
339
+ // Stage 2: no local-mode proxy while a raw-network turn runs (raw-network.ts localModeInterlock,
340
+ // review C2): Codex's proxy has no authentication. Null whenever no such turn runs, as always while
341
+ // stage 2 is switched off. TODO(D2): goes with local mode when stage 2 ships.
342
+ const locked = mode === "local" ? localModeInterlock("local") : null;
343
+ if (locked)
344
+ return said("hosted", locked);
345
+ const wanted = said(mode);
346
+ const flags = codexFlags(spec, prepared.servers, prepared.env, prepared.released, wanted.net);
347
+ const reason = await codexNetworkPreflight({
348
+ bin: spec.config.targets.codex.bin, args: ["app-server", ...flags.off, ...flags.c], cwd: spec.cwd, env: prepared.env, expect: flags.expect, mode, signal: spec.signal,
349
+ });
350
+ if (spec.signal?.aborted)
351
+ throw new Error("the turn was stopped while relay checked Codex's network proxy");
352
+ return reason ? said("hosted", `relay could not verify Codex's network proxy (${reason})`) : wanted;
353
+ }
354
+ /** Whether the turn runs in the job's own worktree as relay created it (its pin), whose Unix sockets a strict or local turn may use. */
355
+ function ownWorktree(spec) {
356
+ if (!spec.worktreePin)
357
+ return false;
358
+ try {
359
+ return canonical(spec.worktreePin.path) === canonical(spec.cwd);
360
+ }
361
+ catch {
362
+ return false;
363
+ }
364
+ }
365
+ /** `serverOf`: how relay's own MCP server is started for the turn; doctor's probe passes an inert one of the same shape (codexLaunchCheck), since relayServerCommand reads the run's registry. */
366
+ export function codexFlags(spec, servers, env, released = [], net, stage2, serverOf = relayServerCommand) {
367
+ const cfg = spec.config;
368
+ const c = [];
369
+ const set = (key, value) => c.push("-c", `${key}=${value}`);
370
+ const setting = cfg.targets.codex.daybreak;
371
+ // Unset preserves the native launch path, including no extra version or catalog lookup.
372
+ const daybreak = setting === undefined ? { enabled: false, explicit: false } : daybreakDecision(setting, spec.model, codexVersion(cfg.targets.codex.bin, env), setting ? daybreakCatalog(env) : { models: [] });
373
+ // Only an explicit false (or a skipped true) pins off; older CLIs get neither setting.
374
+ if (daybreak.explicit)
375
+ set("daybreak", String(daybreak.enabled));
376
+ if (daybreak.enabled) {
377
+ set("features.cli_daybreak", "true");
378
+ // The app server loads config before thread/start supplies its model. Do not validate
379
+ // Daybreak against an unrelated CLI default during that load.
380
+ set("model", toml(spec.model));
381
+ }
382
+ const { dangerous, network, writePaths } = turnPolicy(spec);
383
+ // Speed, pinned on every turn as a service tier: standard is the catalog's "default", said
384
+ // rather than left out, since a model's catalog entry may carry a faster default tier
385
+ // (defaultServiceTier; gpt-6-sol's is priority in Codex 0.163.0). The app server is also given
386
+ // it on the thread and the turn (codex-app.ts); this key is what `codex exec` goes by.
387
+ const speed = spec.speed ?? "standard";
388
+ const tier = speed === "standard" ? "default" : targetDef("codex").speeds[speed].id;
389
+ set("service_tier", toml(tier));
390
+ // With its fast_mode feature off, Codex drops every service tier, "default" included (0.163.0:
391
+ // its thread then reports none), so a standard turn turns it on for the pin to hold; the tier
392
+ // stays "default", so nothing runs faster for it. A faster turn leaves the person's switch as it
393
+ // is and is refused while it is off (codex-app.ts fastModeProblem). Set with -c, since `--enable`
394
+ // of a feature a Codex version does not know stops its server, where an unknown -c key does not.
395
+ if (speed === "standard")
396
+ set("features.fast_mode", "true");
397
+ const gitRoots = cfg.child_git === "native" ? (spec.gitDirs ?? []) : [];
398
+ const roots = [...gitRoots, ...writePaths];
399
+ // Each directory the turn may write by name, where Codex's sandbox cannot be built for it, refuses
400
+ // the turn before Codex starts (codexWriteRootProblem): a grant is checked when it is given, a
401
+ // repository's git directories and the turn's own directory only here.
402
+ if (spec.access === "write" && !dangerous) {
403
+ for (const [what, dir] of [["the turn's directory", spec.cwd], ...gitRoots.map((d) => ["the repository's git directory", d]), ...writePaths.map((d) => ["the granted directory", d])]) {
404
+ const why = codexWriteRootProblem(dir);
405
+ if (why)
406
+ throw new Error(`relay does not start the Codex agent: ${what} ${JSON.stringify(dir)} ${why}.`);
407
+ }
408
+ }
409
+ // The sandbox, as a permission profile of relay's own (codexPermissions): the config keys work for
410
+ // `exec` and the app server alike, new and resumed sessions, and the app server is also told to
411
+ // use it on the thread (codex-app.ts), which no session's stored setting outranks.
412
+ // Stage 2 (WP-D): `:danger-full-access` inside relay's Seatbelt, enforcement "relay" (codex-stage2.ts).
413
+ const permissions = stage2?.permissions ?? codexPermissions(spec, { dangerous, network, roots, ...(net ? { net } : {}), codexHome: env.CODEX_HOME });
414
+ c.push(...permissionFlags(permissions));
415
+ // Codex's network proxy, for a turn whose shell network goes through it (codex-network.ts); and,
416
+ // on every turn, no access added to one command's sandbox: neither the request_permissions tool,
417
+ // whose requests (item/permissions/requestApproval) relay does not answer, nor
418
+ // exec_permission_approvals. With the latter on, a command an exec-policy allow rule matches is
419
+ // run without asking (core exec_policy.rs: Skip), with whatever with_additional_permissions it
420
+ // names merged into its sandbox (sandboxing policy_transforms.rs), so no request reaches relay's
421
+ // autoDenial: network on a session without the proxy, Seatbelt's open policy (review r_17565c33
422
+ // X1; reproduced model-free). All read back (configProblem) and from the feature list (featuresProblem).
423
+ if (permissions.proxy)
424
+ set("features.network_proxy", "true");
425
+ set("features.request_permissions_tool", "false");
426
+ set("features.exec_permission_approvals", "false");
427
+ const features = { request_permissions_tool: false, exec_permission_approvals: false, ...(permissions.proxy ? { network_proxy: true } : {}) };
428
+ // Pin the reviewer: with any other reviewer exec does not hold its approval policy at `never`,
429
+ // and requests would go to an automatic reviewer instead of to relay.
430
+ set("approvals_reviewer", toml("user"));
431
+ // Codex's own web search tool: live with a network grant, whatever network the shell gets
432
+ // (strict, local, or none where the proxy cannot be verified): the search runs at OpenAI, not on
433
+ // this Mac, and its results still reach the agent's context. Without a grant it keeps the user's
434
+ // setting, or is switched off when child_web is "ask" (Codex has no way to ask per search), and
435
+ // for a turn given MCP servers, where a search could carry a credential past relay's gate.
436
+ // Switched off, it is read back too (configProblem): a layer that outranks relay's flags could turn
437
+ // it back on. "live" is not: it widens nothing the network grant has not, and a layer that keeps
438
+ // the search narrower takes nothing away from the job but the search.
439
+ const webOff = Boolean(spec.neverPolicy?.hosts.length || cfg.never?.hosts?.length) || (!network && (cfg.child_web === "ask" || Boolean(spec.extensionServers?.length)));
440
+ if (webOff)
441
+ set("web_search", toml("disabled"));
442
+ else if (network)
443
+ set("web_search", toml("live"));
444
+ // Stage 2 has no local environment for stdio MCP. Its tools use the HTTP broker instead.
445
+ const relay = stage2 ? null : spec.relay;
446
+ if (relay) {
447
+ const server = serverOf(relay);
448
+ // Same name as a user-level entry: -c merges key by key, so these values replace it.
449
+ set("mcp_servers.relay.command", toml(server.command));
450
+ set("mcp_servers.relay.args", toml(server.args));
451
+ set("mcp_servers.relay.env_vars", toml(CODEX_MCP_ENV_VARS));
452
+ for (const [k, v] of Object.entries(server.env))
453
+ set(`mcp_servers.relay.env.${k}`, toml(v));
454
+ set("mcp_servers.relay.enabled", "true");
455
+ // Without this, Codex asks for approval of MCP tools that are not marked read-only.
456
+ set("mcp_servers.relay.default_tools_approval_mode", toml("approve"));
457
+ // Longer than an approval request may make a call wait: a call of an extension's tool waits for
458
+ // the person (gateway.ts), first behind an earlier request of the same agent (up to
459
+ // approval_timeout_s), then for the answer (up to approval_timeout_s again). Cut off sooner, the
460
+ // call would fail for the agent while relay still waited, and a later allow could run it.
461
+ set("mcp_servers.relay.tool_timeout_sec", String(codexToolTimeoutS(cfg.approval_timeout_s)));
462
+ set("mcp_servers.relay.startup_timeout_sec", "30");
463
+ }
464
+ else {
465
+ // Codex filters env for MCP servers, so a user-level relay would not see the child markers
466
+ // and would act as a root. It must never load in a child that may not delegate. This is
467
+ // unconditional (it does not depend on listing the user's servers); the command is given so
468
+ // the entry is well-formed even when the user has no relay entry.
469
+ set("mcp_servers.relay.command", toml("false"));
470
+ set("mcp_servers.relay.args", "[]");
471
+ set("mcp_servers.relay.enabled", "false");
472
+ }
473
+ const relayOnly = cfg.child_mcp === "relay-only";
474
+ if (stage2?.broker) {
475
+ const key = `mcp_servers.${BROKER_SERVER_NAME}`;
476
+ set(`${key}.url`, toml(stage2.broker.url));
477
+ set(`${key}.bearer_token_env_var`, toml(BROKER_TOKEN_ENV));
478
+ set(`${key}.environment_id`, toml("local"));
479
+ set(`${key}.enabled`, "true");
480
+ set(`${key}.required`, "true");
481
+ set(`${key}.startup_readiness`, toml("connection"));
482
+ set(`${key}.default_tools_approval_mode`, toml("approve"));
483
+ set(`${key}.startup_timeout_sec`, "30");
484
+ set(`${key}.tool_timeout_sec`, String(stage2.broker.toolTimeoutS));
485
+ }
486
+ if (relayOnly) {
487
+ for (const name of servers)
488
+ if (name !== "relay" && !(stage2?.broker && name === BROKER_SERVER_NAME))
489
+ set(`mcp_servers.${/^[A-Za-z0-9_-]+$/.test(name) ? name : toml(name)}.enabled`, "false");
490
+ }
491
+ const off = [...(cfg.child_hooks ? [] : ["--disable", "hooks"]), ...(relayOnly ? ["--disable", "plugins"] : [])];
492
+ // Every launched turn, including one given no extensions:
493
+ // every skill Codex would find by itself, the person's and the repository's, is switched off for
494
+ // this server (a session override, written nowhere), and so is installing a skill's MCP
495
+ // dependencies, which would be a second MCP server beside relay's gateway. Relay's own package,
496
+ // if any, is added as an extra skill root once the server is up, and what Codex will load is
497
+ // checked then (codex-app.ts): the session gets exactly what the person consented to.
498
+ {
499
+ const files = codexSkillFiles(spec.cwd, env);
500
+ set("skills.config", `[${files.map((f) => `{path=${toml(f)},enabled=false}`).join(",")}]`);
501
+ off.push("--disable", "skill_mcp_dependency_install");
502
+ }
503
+ // Stage 2 (WP-D): its settings and the features it pins off, read back like the others (§2.5).
504
+ if (stage2) {
505
+ c.push(...stage2.c);
506
+ off.push(...stage2.off);
507
+ Object.assign(features, stage2.features);
508
+ }
509
+ const expect = {
510
+ ...(daybreak.explicit ? { daybreak: daybreak.enabled } : {}),
511
+ permissions, features, relay: relay ? serverOf(relay) : null, relayOnly,
512
+ ...(stage2?.broker ? { broker: stage2.broker } : {}),
513
+ ...(webOff ? { webSearch: "disabled" } : {}),
514
+ accountLogin: authFor(cfg, "codex") === "login",
515
+ signIn: { home: relayCodexHome(cfg), once: codexSignIn(cfg), again: codexSignIn(cfg, true) },
516
+ ...(spec.model ? { model: spec.model } : {}),
517
+ ...(cfg.codex_endpoint_override === "accept" ? { endpointOverride: true } : {}),
518
+ skills: { root: spec.skills ? path.join(spec.skills.dir, "skills") : null, names: spec.skills?.names ?? [] },
519
+ speed: { name: speed, tier },
520
+ };
521
+ return { off, c, expect, released, ...(daybreak.note ? { note: daybreak.note } : {}) };
522
+ }
523
+ /**
524
+ * The permissions of a Codex turn, as a permission profile (Codex 0.163.0 `[permissions.<id>]`,
525
+ * selected by `default_permissions`). It describes the same sandbox as the legacy settings relay
526
+ * used before (`sandbox_mode` and `sandbox_workspace_write`), plus one thing they could not say:
527
+ *
528
+ * - a read turn reads everything and writes nothing (`:root` read), with the network only when it
529
+ * is granted. The `codex exec` fallback has never given a read turn the network (the legacy
530
+ * read-only mode had no network key, and exec takes no per-turn setting), and still does not;
531
+ * - a write turn reads everything and writes its worktree, each granted directory (and, with
532
+ * child_git "native", the repository's git directories) and its own TMPDIR, never the rest of
533
+ * /tmp; the network only when granted. The granted directories are workspace roots of the
534
+ * profile, as they were of the legacy settings (Codex seeded its workspace roots from
535
+ * `writable_roots`), so every rule about workspace roots holds for them too;
536
+ * - and, new, at the top of every workspace root, the harness configuration relay's own sandbox
537
+ * also refuses (HARNESS_CONFIG) is read-only, present or not: a job cannot plant a
538
+ * `.claude/settings.json`, `.gemini/` or `.mcp.json` that the person's own agent would load once
539
+ * the work is merged. Codex keeps its own protection of `.git`, `.agents`, `.codex` and `.aws`
540
+ * on top of this (protocol/src/permissions.rs, default_read_only_subpaths_for_writable_root);
541
+ * - under allow_dangerous, a write turn runs with Codex's built-in `:danger-full-access`;
542
+ * - every confined turn carries the captured never floor's built-in and user paths, including
543
+ * aliases: all-access denies become `deny`, write-only denies become `read`, with the full
544
+ * profile checked through the existing exact config/read readback;
545
+ * - every confined turn, read or write, may not read the credential stores of deniedCredentials,
546
+ * which also keeps every command in the sandbox, approved or allowed by an exec-policy rule;
547
+ * - the network, where a turn has it, only through Codex's network proxy (codex-network.ts): strict
548
+ * (no loopback or private destinations), or local for a write turn the person consented for;
549
+ * Unix sockets only under the directories named (`net.sockets`: a write turn's TMPDIR and its
550
+ * job's worktree; a read turn none). Where the proxy cannot be verified (`net.mode` "hosted"),
551
+ * none at all: Codex's hosted web search is set apart (codexFlags).
552
+ *
553
+ * Both Codex's shell sandbox and its own file edits (apply_patch) follow the profile. A command or
554
+ * file change a person approves to run outside the sandbox gets write access to the whole disk but
555
+ * still not the denied credential stores, with the turn's own network (deniedCredentials).
556
+ */
557
+ /**
558
+ * Credential stores every confined Codex turn may not read (or write), as profile entries Codex
559
+ * keeps under any approval: `~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.netrc` and Codex's own login
560
+ * (`$CODEX_HOME/auth.json` where CODEX_HOME is set, else `~/.codex/auth.json`). Spelled as
561
+ * config/read echoes them back ("deny"; "none" is its legacy alias), so the exact profile readback
562
+ * confirms them on every turn.
563
+ *
564
+ * They also change what an approval can do. Codex lets no command leave its sandbox while the
565
+ * profile denies a read, since the sandbox is what enforces the denial (core tools/sandboxing.rs
566
+ * unsandboxed_execution_allowed, sandbox_permissions_preserving_denied_reads): a command an
567
+ * exec-policy rule allows runs sandboxed like any other, and a command approved to run outside the
568
+ * sandbox runs in it with write access to `/` and these denials kept (protocol
569
+ * permissions/target.rs for_approved_command), with the turn's own network.
570
+ */
571
+ export function deniedCredentials(codexHome, cfg) {
572
+ const auth = codexHome && path.isAbsolute(codexHome) ? path.join(codexHome, "auth.json") : "~/.codex/auth.json";
573
+ return Object.fromEntries(["~/.ssh", "~/.aws", "~/.gnupg", "~/.netrc", "~/.codex/auth.json", auth, ...relayCodexProtected(cfg).homes.map((p) => p.path)].map((p) => [p, "deny"]));
574
+ }
575
+ export function codexPermissions(spec, o) {
576
+ if (o.dangerous)
577
+ return { id: DANGER_PROFILE, profile: null, sandbox: "danger-full-access", network: true, proxy: null };
578
+ const write = spec.access === "write";
579
+ // The shell's network (codex-network.ts): through Codex's proxy (strict, or local for a write turn
580
+ // the person consented for), or none (hosted search only). The exec fallback has never given a
581
+ // read turn the network, and still does not. Plain `network.enabled = true` without the proxy,
582
+ // which opens loopback and Unix sockets anywhere, is never set.
583
+ const want = o.network && (write || spec.config.codex_backend !== "exec") ? (o.net ?? { mode: "strict" }) : { mode: "hosted" };
584
+ const proxy = want.mode === "hosted" ? null : want.mode === "local" && write ? "local" : "strict";
585
+ const sockets = write ? (want.sockets ?? []) : [];
586
+ const network = proxy
587
+ ? {
588
+ enabled: true, domains: { "*": "allow" }, allow_local_binding: proxy === "local", allow_upstream_proxy: false,
589
+ ...(sockets.length ? { unix_sockets: Object.fromEntries(sockets.map((d) => [d, "allow"])) } : {}),
590
+ }
591
+ : { enabled: false };
592
+ const floor = spec.neverPolicy ? neverProfileInputs(spec.neverPolicy) : undefined;
593
+ const denied = { ...Object.fromEntries(relayCodexProtected(spec.config.targets ? spec.config : undefined).stores.map((p) => [p.path, "read"])),
594
+ ...Object.fromEntries((floor?.denyWrite ?? []).map(p => [p, "read"])),
595
+ ...deniedCredentials(o.codexHome, spec.config.targets ? spec.config : undefined),
596
+ ...Object.fromEntries((floor?.denyAll ?? []).map(p => [p, "deny"])) };
597
+ if (!write)
598
+ return { id: CODEX_PROFILE, profile: { filesystem: { ":root": "read", ...denied }, network }, sandbox: "read-only", network: network.enabled, proxy };
599
+ const carveOuts = Object.fromEntries(HARNESS_CONFIG.map((name) => [name, "read"]));
600
+ return {
601
+ id: CODEX_PROFILE,
602
+ profile: {
603
+ ...(o.roots.length ? { workspace_roots: Object.fromEntries(o.roots.map((r) => [r, true])) } : {}),
604
+ filesystem: { ":root": "read", ":tmpdir": "write", ":workspace_roots": { ".": "write", ...carveOuts }, ...denied },
605
+ network,
606
+ },
607
+ sandbox: "workspace-write", network: network.enabled, proxy,
608
+ };
609
+ }
610
+ /** Codex's built-in profile without a sandbox (allow_dangerous). */
611
+ const DANGER_PROFILE = ":danger-full-access";
612
+ /**
613
+ * A TOML inline table of `entries`, every key quoted. A name such as `.claude` or a path is a key
614
+ * inside the value, never part of the dotted key of a `-c` override, which Codex splits at every
615
+ * dot (config/src/overrides.rs).
616
+ */
617
+ export function tomlInline(entries) {
618
+ const value = (v) => (typeof v === "string" ? toml(v) : typeof v === "boolean" ? String(v) : tomlInline(v));
619
+ return `{${Object.entries(entries).map(([k, v]) => `${toml(k)}=${value(v)}`).join(",")}}`;
620
+ }
621
+ /** The `-c` overrides that define and select a turn's permission profile. */
622
+ export function permissionFlags(p) {
623
+ const out = ["-c", `default_permissions=${toml(p.id)}`];
624
+ if (!p.profile)
625
+ return out;
626
+ const key = `permissions.${CODEX_PROFILE}`;
627
+ out.push("-c", `${key}.filesystem=${tomlInline(p.profile.filesystem)}`);
628
+ if (p.profile.workspace_roots)
629
+ out.push("-c", `${key}.workspace_roots=${tomlInline(p.profile.workspace_roots)}`);
630
+ const n = p.profile.network;
631
+ out.push("-c", `${key}.network.enabled=${n.enabled}`);
632
+ if (n.domains)
633
+ out.push("-c", `${key}.network.domains=${tomlInline(n.domains)}`);
634
+ if (n.allow_local_binding !== undefined)
635
+ out.push("-c", `${key}.network.allow_local_binding=${n.allow_local_binding}`);
636
+ if (n.allow_upstream_proxy !== undefined)
637
+ out.push("-c", `${key}.network.allow_upstream_proxy=${n.allow_upstream_proxy}`);
638
+ if (n.unix_sockets)
639
+ out.push("-c", `${key}.network.unix_sockets=${tomlInline(n.unix_sockets)}`);
640
+ return out;
641
+ }