@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,363 @@
1
+ import { preamble, turnSubagents } from "./steering.js";
2
+ import { sessionParams } from "./params.js";
3
+ import { extensionsLine } from "./extensions.js";
4
+ import { networkOn } from "./config.js";
5
+ import { inSideOrder, sideName, sidePrefix, targetDef } from "../targets/index.js";
6
+ import { relayToolName } from "../backends/tool-discovery.js";
7
+ /**
8
+ * Text on one line, cut to `max`, for a prompt: model input, not a person's screen, so nothing is
9
+ * escaped (unlike shown.ts oneLine, which is for what a person sees).
10
+ */
11
+ const flat = (s, max = 200) => {
12
+ const line = s.replace(/\s+/g, " ").trim();
13
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
14
+ };
15
+ export const DELEGATION_NORM = "Delegate only well-defined chunks that are meaningfully smaller than your assignment, and do real work yourself. " +
16
+ "Never forward your whole assignment, and never hand work back to an ancestor. Handle small tasks directly.";
17
+ /**
18
+ * What the relay tools are for, said to a launched agent of `target` that has them. `model`: the
19
+ * model its session runs, which is its family on a harness of several families' models.
20
+ */
21
+ export function crossFamily(target, cfg, model, access = "write") {
22
+ return preamble(target, cfg, model, turnSubagents(target, access));
23
+ }
24
+ export const REPORT_FIELDS = ["Summary", "Files changed", "Branch", "Tests run", "Open issues"];
25
+ /**
26
+ * Where in the repository the person was working, for a write job: its agent always starts at the
27
+ * worktree root (a subdirectory path could be redirected), so the position is said instead.
28
+ */
29
+ function subdirLine(node) {
30
+ const subdir = sessionParams(node).subdir;
31
+ return typeof subdir === "string" && subdir ? ` The person was working in ${subdir}/ of this repository; your working directory is the worktree's root.` : "";
32
+ }
33
+ /**
34
+ * Whether an agent of `target` can be given relay's tools at all (a harness that drops relay's bridge
35
+ * cannot: Copilot). A harness that takes them through its own tool discovery (Gemini) is offered them
36
+ * on every version; where discovery did not run, its turn's prompt is corrected at launch
37
+ * (PreparedState.beforePrompt), so the preamble needs no reading of the version here.
38
+ */
39
+ const hasRelayTools = (target) => !target || targetDef(target).capabilities.relayTools !== false;
40
+ const NO_RELAY_TOOLS = "Relay's tools are not available to you in this harness, so you cannot delegate; do the work yourself.";
41
+ /**
42
+ * For a harness that names relay's tools with a prefix of its own (Gemini's discovered tools), what
43
+ * they are called there, since relay's texts and its tools' descriptions name them without it.
44
+ */
45
+ function toolNames(target) {
46
+ const prefix = targetDef(target).toolDiscovery?.prefix;
47
+ if (!prefix)
48
+ return "";
49
+ const named = ["delegate", "status", "result", "merge"].map((t) => relayToolName(target, t)).join(", ");
50
+ return ` In this harness each relay tool's name starts with ${prefix} (${named}, and so on): where relay's texts name a tool without it, call it with it.`;
51
+ }
52
+ export function delegationPreamble(node, cfg, rootTask, parentTask, scope, grant, canAsk = false, extensions) {
53
+ const tools = hasRelayTools(node.target);
54
+ const canDelegate = tools && node.allow_delegation === 1 && node.depth < cfg.max_depth;
55
+ const lines = [
56
+ `[relay] You are a delegated agent, started by another agent through relay. Depth ${node.depth} of max ${cfg.max_depth}.`,
57
+ `Root task: ${flat(rootTask)}`,
58
+ `Parent task: ${flat(parentTask)}`,
59
+ `Your scope: ${scope?.length ? scope.join(", ") : "not restricted"}.`,
60
+ node.mode === "write"
61
+ ? `Mode: write. You are in your own git worktree on branch ${node.branch}; your writes are limited to it.${subdirLine(node)}`
62
+ : "Mode: read. Your session is read-only; do not try to modify files.",
63
+ canDelegate
64
+ ? `You may delegate further using the relay tools.${toolNames(node.target)} ${crossFamily(node.target, cfg, node.model, node.mode)}`
65
+ : node.allow_delegation === 1
66
+ ? (tools ? "You are at the maximum depth, so you cannot delegate; do the work yourself." : NO_RELAY_TOOLS)
67
+ : "You may not delegate; do the work yourself.",
68
+ DELEGATION_NORM,
69
+ "If you use your own subagents, wait for every one to finish before your final answer, because relay stops any still running when your turn ends.",
70
+ ];
71
+ if (canDelegate) {
72
+ lines.push("Jobs you start keep running after your turn ends, but nobody else will collect them. Wait for them" +
73
+ (node.mode === "write" ? ", and integrate their branches with the relay merge tool, before you report." : " before you report."));
74
+ }
75
+ if (node.mode === "write") {
76
+ lines.push(cfg.child_git === "native"
77
+ ? "Commit your work on your branch before you report."
78
+ : "Relay commits your work when your turn ends, so you do not need to run git commit (the sandbox may block it).");
79
+ }
80
+ // Relay stops what it can still trace to the agent when the turn ends, which is not everything.
81
+ lines.push("Stop any process you start (servers, watchers, anything in the background) before you report. Nothing else is certain to stop it once your turn is over.");
82
+ const network = networkOn(cfg, grant);
83
+ const extras = [
84
+ network ? "network and web access" : "",
85
+ network && node.mode === "write" && grant?.local_network ? "this Mac's loopback and the local network from your shell, once the user consents" : "",
86
+ ...(node.mode === "write" ? (grant?.write_paths ?? []) : []).map((p) => `write access to ${p}`),
87
+ ].filter(Boolean);
88
+ if (extras.length)
89
+ lines.push(`Granted beyond your sandbox: ${extras.join("; ")}.`);
90
+ if (extensions)
91
+ lines.push(extensionsLine(node.target, extensions));
92
+ // A job always has a target.
93
+ lines.push(blockedAdvice(node.target, node.mode, canAsk, network, webWithheld(cfg)));
94
+ lines.push("End your final message with this report, with every field filled in (write \"none\" where nothing applies):", "## RELAY REPORT", ...REPORT_FIELDS.map((f) => `${f}: …`), "", "Your assignment:", "");
95
+ return lines.join("\n");
96
+ }
97
+ /**
98
+ * Whether the run's captured never.hosts withholds the host's own web tools (backends/claude.ts
99
+ * applyClaudeNeverPolicy denies Claude's WebSearch and WebFetch whenever its floor lists a host). A
100
+ * run's floor only adds to the captured config, so a host listed there is always in it: true means
101
+ * denied. False does not mean allowed: the durable floor can gain a host after capture (a later
102
+ * checkpoint, core/never-checkpoint.ts), and copied user deny rules can deny the tools too. This
103
+ * reads no checkpoint; instead Claude's web wording (targets/claude.ts WEB_TOOLS) is conditional on
104
+ * permission policy, so it never promises an approval prompt and says to finish and report after a
105
+ * policy denial.
106
+ */
107
+ const webWithheld = (cfg) => (cfg.never?.hosts?.length ?? 0) > 0;
108
+ /**
109
+ * What an agent should do when its sandbox stops it, worded for how that agent asks. `webDenied`:
110
+ * never.hosts withholds the host's own web tools (Claude's; see TargetDef.text.blockedAsks).
111
+ */
112
+ export function blockedAdvice(target, mode, canAsk, network, webDenied = false) {
113
+ const blocked = mode === "write"
114
+ ? (network ? "a path outside your worktree" : "the network, or a path outside your worktree")
115
+ : (network ? "a command the read-only sandbox blocks" : "web access, or a command the read-only sandbox blocks");
116
+ const text = targetDef(target).text;
117
+ const shell = !network && text.shellNetwork ? ` ${text.shellNetwork(canAsk && !webDenied)}` : "";
118
+ // What this turn can actually ask for; null: nothing, so it is told to finish and report.
119
+ const asks = text.blockedAsks ? text.blockedAsks(mode, { network, webDenied }) : blocked;
120
+ // Nothing approved takes an agent out of relay's own sandbox, so it is not told it can ask.
121
+ if (!canAsk || !targetDef(target).capabilities.escalation || asks === null) {
122
+ return `If you need something your sandbox blocks (${blocked}), do not work around it. Finish what you can and say exactly what you needed${mode === "write" ? " under Open issues" : ""}, so it can be granted.${shell}`;
123
+ }
124
+ return (`If you genuinely need something your sandbox blocks (${asks}), you may ask for approval: ${text.blockedHow(mode)}. ` +
125
+ "The request goes to the user and may take a while. If it is denied, do not work around it; finish what you can and say what you needed." +
126
+ (mode === "read" ? " You cannot ask to change files; this session stays read-only." : "") + shell);
127
+ }
128
+ /** Tolerant parser for the final report. Missing fields are null; the raw message is always kept elsewhere. */
129
+ export function parseReport(message) {
130
+ const idx = message.toUpperCase().lastIndexOf("RELAY REPORT");
131
+ const body = idx >= 0 ? message.slice(idx) : message;
132
+ const labels = REPORT_FIELDS.map((f) => f.replace(" ", "\\s+")).join("|");
133
+ const field = (name) => {
134
+ const re = new RegExp(`^[\\s>*_#-]*${name.replace(" ", "\\s+")}[*_]*\\s*:[*_]*\\s*([\\s\\S]*?)(?=^[\\s>*_#-]*(?:${labels})[*_]*\\s*:|(?![\\s\\S]))`, "im");
135
+ const m = re.exec(body);
136
+ const value = m?.[1]?.trim();
137
+ return value ? value : null;
138
+ };
139
+ const out = {
140
+ summary: field("Summary"),
141
+ files_changed: field("Files changed"),
142
+ branch: field("Branch"),
143
+ tests_run: field("Tests run"),
144
+ open_issues: field("Open issues"),
145
+ };
146
+ return { ...out, report_parsed: idx >= 0 && Object.values(out).every((v) => v !== null) };
147
+ }
148
+ export function consultHeader(caller, target, mayDelegate, opts) {
149
+ return [
150
+ `[relay] Another agent (${caller}) is consulting you mid-task and is waiting for your answer.`,
151
+ "Your session is read-only.",
152
+ mayDelegate && hasRelayTools(target) ? `You may use the relay tools to delegate.${toolNames(target)} ${crossFamily(target, opts.cfg, opts.model, "read")}` : "You may not delegate; answer from your own work.",
153
+ ...(opts.network ? ["You have network and web access."] : []),
154
+ ...(opts.extensions ? [extensionsLine(target, opts.extensions)] : []),
155
+ blockedAdvice(target, "read", opts.canAsk, opts.network, webWithheld(opts.cfg)),
156
+ "Follow-up questions will arrive in this same session.",
157
+ "",
158
+ ].join("\n");
159
+ }
160
+ export function contextBlock(paths) {
161
+ return paths?.length ? `Context files to read first:\n${paths.map((p) => `- ${p}`).join("\n")}\n\n` : "";
162
+ }
163
+ // Discussions
164
+ export const HUMAN_LABEL = "[Message from the human user, not from the other participant]";
165
+ export const ROLE_PRESETS = {
166
+ proposer: "You are the proposer. Put forward a concrete position on the topic and defend or revise it on the merits.",
167
+ critic: "You are the critic. Test the other side's position against the evidence, and say what you would do instead where you disagree.",
168
+ peer: "You are a peer. Defend or revise your own points on the merits, evaluate the other side's points, merge duplicates, " +
169
+ "and drop anything you are persuaded is wrong (say what persuaded you).",
170
+ };
171
+ export const DISCUSSION_RULES = [
172
+ "Rules for this discussion:",
173
+ "- Argue from evidence: files, lines, test output, docs.",
174
+ "- Do not concede unless an argument actually persuades you, and say what did.",
175
+ "- End every turn with exactly one of these, on its own line as the last thing you write:",
176
+ " CONTINUE",
177
+ " AGREE: <conclusion>",
178
+ " CRUX: <the specific remaining disagreement>",
179
+ "- Reply AGREE only if you accept the other side's conclusion as they stated it. If yours differs in substance, use CONTINUE and say how.",
180
+ ].join("\n");
181
+ export function discussionOpening(opts) {
182
+ return [
183
+ opts.resumed
184
+ ? "[relay] This is a new phase of your existing session: a discussion with another agent. Keep everything you already know from this session."
185
+ : "[relay] You are taking part in a discussion with another agent.",
186
+ `The other participant is ${opts.other}, working in its own session. Relay passes each of you the other's messages verbatim and keeps the record.`,
187
+ `Your session is read-only for this discussion.${opts.mayDelegate && hasRelayTools(opts.target) ? ` You may use the relay tools to delegate.${toolNames(opts.target)} ${crossFamily(opts.target, opts.cfg, opts.model, "read")}` : " You may not delegate."}`,
188
+ "",
189
+ `Topic: ${opts.topic}`,
190
+ "",
191
+ contextBlock(opts.context).trimEnd(),
192
+ `Your role: ${opts.role}`,
193
+ "",
194
+ DISCUSSION_RULES,
195
+ opts.extraRules ?? "",
196
+ "",
197
+ ].filter((l, i, a) => !(l === "" && a[i - 1] === "")).join("\n");
198
+ }
199
+ /**
200
+ * Finds the turn's final marker: the last line that begins with CONTINUE, AGREE: or CRUX:. Failing
201
+ * that, a marker at the end of the last line, after the end of a sentence ("Looks right. AGREE:
202
+ * use X"), but only when it is unambiguous: the last line is not quoted, no quotation mark comes
203
+ * before the marker on that line, that AGREE: or CRUX: is the only one anywhere in the message,
204
+ * and its conclusion is one sentence naming no other marker (a CONTINUE must end the line). When
205
+ * in doubt there is no marker, and the caller is told so (marker_note).
206
+ */
207
+ export function parseMarker(message) {
208
+ const lines = message.split("\n");
209
+ for (let i = lines.length - 1; i >= 0; i--) {
210
+ // Quoted (">") and bulleted ("-") lines are not stripped: a copy of the other side's closing
211
+ // line inside a quote must not count as this turn's marker.
212
+ const line = lines[i].replace(/^[\s*_`#]+/, "");
213
+ const m = /^(AGREE|CRUX)\s*[*_]*\s*:[*_]*\s*(.*)$/s.exec(line);
214
+ if (m) {
215
+ const text = [m[2], ...lines.slice(i + 1)].join("\n").trim();
216
+ return { kind: m[1], text };
217
+ }
218
+ if (/^CONTINUE\b/.test(line))
219
+ return { kind: "CONTINUE" };
220
+ }
221
+ const last = lines.map((l) => l.trim()).filter(Boolean).pop() ?? "";
222
+ if (last.startsWith(">"))
223
+ return { kind: "NONE" };
224
+ const inline = /(?:^|[.!?)\]]\s+)[*_]*(AGREE|CRUX)[*_]*:[*_]*\s*(\S.*)$/.exec(last);
225
+ if (inline) {
226
+ const text = inline[2].trim();
227
+ const alone = (message.match(/\b(?:AGREE|CRUX)[*_]*\s*:/g) ?? []).length === 1;
228
+ // More after the conclusion's first sentence, or another marker in it, could be what the
229
+ // marker was meant to be followed by, or a quotation of the other side going on.
230
+ const more = /[.!?]["'”’)\]]*\s+\S/.test(text) || /\b(?:CONTINUE|AGREE|CRUX)\b/.test(text);
231
+ if (alone && !more && !quotedBefore(last.slice(0, inline.index + inline[0].length - inline[2].length))) {
232
+ return { kind: inline[1], text, inline: true };
233
+ }
234
+ return { kind: "NONE" };
235
+ }
236
+ const cont = /(?:^|[.!?)\]]\s+)[*_]*CONTINUE[*_]*\.?$/.exec(last);
237
+ if (cont && !quotedBefore(last.slice(0, cont.index + 1)))
238
+ return { kind: "CONTINUE", inline: true };
239
+ return { kind: "NONE" };
240
+ }
241
+ /**
242
+ * Whether a line, up to a marker found inside it, has a quotation mark: " “ ” or a backtick, or an
243
+ * apostrophe (' or ’) that is not inside a word ("don't" is no quotation; "'stop" is).
244
+ */
245
+ function quotedBefore(text) {
246
+ return /["“”`]/.test(text) || /(?<![\p{L}\p{N}])['’]|['’](?![\p{L}\p{N}])/u.test(text);
247
+ }
248
+ export const PASS_RULE = "A pass over coverage that is not declared complete is recorded as unknown.";
249
+ /** The JSON block every review ends with, by example. */
250
+ export const reviewJsonShape = (kind) => JSON.stringify({
251
+ verdict: "fail",
252
+ coverage: kind === "plan" ? { complete: false, examined: ["steps 1-4", "src/a.ts"], not_examined: ["step 5"] } : { complete: false, examined: ["src/a.ts"], not_examined: ["the tests"] },
253
+ items: [{ n: 1, severity: "major", confidence: "high", file: kind === "plan" ? "src/a.ts" : "path/file.ts", lines: [42, 47], location: kind === "plan" ? "step 2" : "fetchUser", summary: "…", evidence: "…", fix: "…" }],
254
+ });
255
+ /** How every review is written, by either side: its items, its verdict and what it covers, ending in one JSON block. */
256
+ export function reviewFormat(kind) {
257
+ const plan = kind === "plan";
258
+ return [
259
+ "Give numbered feedback items. Each item has:",
260
+ "- severity: blocker, major, minor, or nit",
261
+ "- confidence: high, medium, or low (how sure you are that it is real)",
262
+ plan
263
+ ? "- file and lines: where it has one, the file and inclusive line range ([start, end]) it concerns, in the plan's file or in existing code the plan misjudges"
264
+ : "- file and lines: the file and inclusive line range ([start, end]) it concerns, where it has one",
265
+ plan ? "- location: the step or section of the plan, or a symbol" : "- location: anything else that places it, such as a symbol",
266
+ "- summary: the problem in one sentence",
267
+ "- evidence: what you observed that shows the problem",
268
+ "- fix: the change you suggest",
269
+ "",
270
+ "Then give your verdict and say what your review covers:",
271
+ plan
272
+ ? '- verdict: "pass" if the plan can go ahead as it stands, "fail" if something should change first, "unknown" if you cannot tell'
273
+ : '- verdict: "pass" if nothing you found should hold the work back, "fail" if something should, "unknown" if you cannot tell',
274
+ plan
275
+ ? "- coverage: the parts of the plan and the existing code you checked it against (examined), and what you did not get to (not_examined). complete is true only if you examined all of the plan and everything it builds on."
276
+ : "- coverage: what you examined (files, areas, checks you ran) and what you did not (not_examined). complete is true only if you examined everything the target covers.",
277
+ ` ${PASS_RULE}`,
278
+ "",
279
+ "Write your review as prose first if you wish, then end with a fenced JSON block in exactly this shape:",
280
+ "```json",
281
+ reviewJsonShape(kind),
282
+ "```",
283
+ "If you find nothing worth raising, return an empty items array.",
284
+ ];
285
+ }
286
+ /** The reviewer's instructions, built from the subject and focus alone. A string subject is code. */
287
+ export function reviewerPrompt(subject, focus) {
288
+ const s = typeof subject === "string" ? { kind: "code", target: subject } : subject;
289
+ const isolation = "Do not look for the other review outside the target; relay gives it to you after yours is finished.";
290
+ if (s.kind === "code") {
291
+ return [
292
+ `[relay] You are an independent code reviewer. Another reviewer is reviewing the same target separately; ${isolation}`,
293
+ "Your session is read-only and you may not delegate.",
294
+ "",
295
+ `Review target: ${s.target}`,
296
+ focus ? `Focus: ${focus}` : "Focus: none given; review for correctness first, then design and maintainability.",
297
+ "",
298
+ "Read the target and whatever surrounding code you need to judge it. Report only what you can support with evidence.",
299
+ ...reviewFormat("code"),
300
+ ].join("\n");
301
+ }
302
+ return [
303
+ `[relay] You are an independent plan reviewer. Another reviewer is reviewing the same plan separately; ${isolation}`,
304
+ "Your session is read-only and you may not delegate.",
305
+ "",
306
+ ...("path" in s ? [`The plan to review is in the file ${s.path}.`] : ["The plan to review follows.", "----- plan -----", s.text.trim(), "----- end of plan -----"]),
307
+ focus ? `Focus: ${focus}` : "Focus: none given; review whether the plan would work first, then whether it is the right plan.",
308
+ "",
309
+ "The plan describes work that has not been done yet. Do not expect the code, files or changes it proposes to exist, and do not report their absence as a problem.",
310
+ "Judge whether it would work and whether it is the right plan: assumptions about the existing code that do not hold (read the code it builds on to check), missing or misordered steps, risks and failure modes it leaves open, simpler alternatives, and how its result would be tested. Report only what you can support with evidence.",
311
+ ...reviewFormat("plan"),
312
+ ].join("\n");
313
+ }
314
+ /** The rules of a review's reconciliation, for its two sides (side labels: target ids, or CALLER_LABEL). */
315
+ export function reviewDiscussionRules(labels) {
316
+ const from = inSideOrder(labels).map((l, i) => `${sidePrefix(l)}<n>${i ? "" : " came"} from the ${sideName(l)} reviewer`).join(", ");
317
+ const [a, b] = inSideOrder(labels).map(sidePrefix);
318
+ const block = {
319
+ verdict: "fail", coverage: { complete: false, examined: ["…"], not_examined: ["…"] },
320
+ consensus: [{ ids: [`${a}1`, `${b}3`], severity: "major", confidence: "high", status: "agreed", summary: "…", file: "…", lines: [1, 2], location: "…", evidence: "…", fix: "…" }],
321
+ };
322
+ return [
323
+ `- Items are identified by id: ${from}. Refer to items by id.`,
324
+ "- When you write AGREE, and on your final turn whatever marker you use, put a fenced JSON block immediately before the marker line listing every original item id exactly once, with the verdict and coverage you hold the two reviews to reach together:",
325
+ " ```json",
326
+ ` ${JSON.stringify(block)}`,
327
+ " ```",
328
+ " status is \"agreed\" (both of you hold that it is a real issue at that severity) or \"dropped\" (you hold that it should not be raised). Merge duplicates into one entry with several ids. An item is agreed or dropped only where both your closing blocks give it that status and the same severity (an entry without a severity holds the one its items have in the reviews); anything else is unresolved, with each block's position.",
329
+ ` verdict is "pass" if nothing agreed should hold the work back, "fail" if something should, "unknown" if you cannot tell. coverage is what the two reviews examined between them; complete is true only if together they examined everything under review. ${PASS_RULE} The review's verdict is the one both your closing blocks reach; if they differ it is unresolved. Anything both reviews declared not examined counts against complete unless your closing coverage lists it under examined, in the same words.`,
330
+ ].join("\n");
331
+ }
332
+ /** Returns the last fenced JSON block in a message that parses and satisfies pick. */
333
+ export function lastJsonBlock(message, pick) {
334
+ // Fences are paired line by line, so a block tagged with another language (```ts) is skipped
335
+ // as a whole and cannot throw the pairing off.
336
+ const blocks = [];
337
+ let open = null;
338
+ for (const line of message.split("\n")) {
339
+ if (/^\s*```[\w-]*\s*$/.test(line)) {
340
+ if (open) {
341
+ blocks.push(open.join("\n"));
342
+ open = null;
343
+ }
344
+ else {
345
+ open = [];
346
+ }
347
+ }
348
+ else if (open) {
349
+ open.push(line);
350
+ }
351
+ }
352
+ for (let i = blocks.length - 1; i >= 0; i--) {
353
+ try {
354
+ const picked = pick(JSON.parse(blocks[i]));
355
+ if (picked !== null)
356
+ return picked;
357
+ }
358
+ catch {
359
+ // Not JSON; try the previous block.
360
+ }
361
+ }
362
+ return null;
363
+ }
@@ -0,0 +1,238 @@
1
+ // Relay's configuration decides authority just as its registry does. Keep this list shared by
2
+ // admission, file approvals and both sandbox policies. Do not turn a broad config directory into
3
+ // a protected tree: RELAY_CONFIG and symlinks may put a single file in a project or the home folder.
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { canonical, configPath, inside, insideAnyCase, loadConfig, overlapsEntryAnyCase, relayHome, worktreesHome, DEFAULT_CONFIG, relayCodexHome, relayCodexPinStore } from "./config.js";
8
+ import { developerDirs, findExecutable, gitExecutable, testSystemTools, XCRUN_SHIMS } from "./executables.js";
9
+ import { git } from "./git.js";
10
+ import { TARGET_IDS, targetDef } from "../targets/index.js";
11
+ export const installRecordPath = () => path.join(path.dirname(configPath()), "install.json");
12
+ export const installBackupsPath = () => path.join(path.dirname(configPath()), "install-backups");
13
+ /**
14
+ * Relay's local config: machine-local settings that must never be synced (api-keys.ts reads it),
15
+ * which say which API key file relay reads for a key-only target, and so whose account that target
16
+ * runs on. `~/.config/relay/local.json`, wherever RELAY_HOME or RELAY_CONFIG put the config, so
17
+ * every relay process on the machine reads the same one. One of relay's own files: protected with
18
+ * them, and no reason to protect its directory less.
19
+ */
20
+ export const localConfigPath = () => path.join(os.homedir(), ".config", "relay", "local.json");
21
+ /** Relay's MCP server definitions (docs/extensions.md): beside config.json, machine-local, never synced. */
22
+ export const mcpFile = () => path.join(path.dirname(configPath()), "mcp.json");
23
+ const under = (p, d) => p === d || p.startsWith(d.endsWith(path.sep) ? d : d + path.sep);
24
+ /** Include the name of a symlink as well as its destination, including missing tails. */
25
+ export const pathOverlaps = (a, b) => under(path.resolve(a), path.resolve(b)) || under(path.resolve(b), path.resolve(a)) || inside(a, b) || inside(b, a);
26
+ export function configProtection() {
27
+ const configured = path.resolve(configPath());
28
+ // mcp.json says which servers run outside launched agents' sandboxes, so it is protected like
29
+ // config.json, also while it does not exist: a job that wrote one would define what they run.
30
+ const originals = [configured, mcpFile(), installRecordPath(), installBackupsPath()].map((p) => path.resolve(p));
31
+ // A missing config is valid: keep its configured name without realpathSync on a missing file.
32
+ const named = (p) => fs.existsSync(p) ? [p, fs.realpathSync(p)] : [p];
33
+ const files = [...new Set(originals.flatMap(named))];
34
+ // The local config is protected as relay's file wherever it is, and counts as relay's in the
35
+ // directory test below; only the config's own directories are judged for whole protection.
36
+ const local = named(path.resolve(localConfigPath()));
37
+ const directories = [];
38
+ const fileOnly = [];
39
+ for (const directory of new Set(files.map((p) => path.dirname(p)))) {
40
+ let reason = null;
41
+ if ([os.homedir(), relayHome(), worktreesHome()].some((p) => inside(p, directory))) {
42
+ reason = "it is or contains the home, control or worktrees directory";
43
+ }
44
+ else {
45
+ const repo = git(directory, ["rev-parse", "--show-toplevel"]);
46
+ if (repo.ok && repo.out && inside(repo.out, directory))
47
+ reason = "it is or contains a git work tree";
48
+ }
49
+ if (!reason) {
50
+ try {
51
+ const names = new Set([...files, ...local].filter((p) => path.dirname(p) === directory).map((p) => path.basename(p)));
52
+ if (fs.readdirSync(directory).some((n) => !names.has(n)))
53
+ reason = "it holds files other than relay's config and install files";
54
+ }
55
+ catch {
56
+ reason = "relay cannot read the directory to establish that it is dedicated to relay";
57
+ }
58
+ }
59
+ if (reason) {
60
+ // The control directory already has whole-tree protection, independently of this list.
61
+ if (!inside(directory, relayHome()))
62
+ fileOnly.push({ directory, reason });
63
+ }
64
+ else
65
+ directories.push(directory);
66
+ }
67
+ return { paths: [...new Set([...files, ...local, ...directories])], directories, fileOnly };
68
+ }
69
+ /**
70
+ * Relay's own installation: the package the running code was loaded from, which holds dist/ (this
71
+ * module is dist/core/protected-config.js), package.json and relay's native helper. Relay runs that
72
+ * code outside every sandbox: at its next start (dist/*.js) and, while it runs, dist/native's
73
+ * sandbox_check helper. So no job may write there (review r_0c11d860 X1). Always the running copy,
74
+ * never a configured one: a test or a development checkout protects itself.
75
+ */
76
+ export const relayPackageRoot = () => path.resolve(import.meta.dirname, "..", "..");
77
+ /** Defaults, machine config and a run's saved config stay protected together. */
78
+ export function relayCodexProtected(cfg) {
79
+ const configs = [DEFAULT_CONFIG, loadConfig(() => { }), ...(cfg ? [cfg] : [])];
80
+ const parts = (paths, what) => [...new Set(paths)].flatMap((p) => {
81
+ // Resolve existing ancestors as well: the root need not have been bootstrapped yet.
82
+ return [...new Set([p, canonical(p)])].map((path) => ({ what, path }));
83
+ });
84
+ return {
85
+ homes: parts(configs.map(relayCodexHome), "relay's Codex credential home"),
86
+ stores: parts(configs.map(relayCodexPinStore), "relay's qualified Codex pin store"),
87
+ };
88
+ }
89
+ export const relayCredentialProtected = (cfg) => relayCodexProtected(cfg).homes;
90
+ const realOf = (p) => {
91
+ try {
92
+ return fs.realpathSync.native(p);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ };
98
+ /** Prefixes many installations share: an executable's directory there is no package of its own. */
99
+ const SHARED_PREFIXES = new Set(["/", "/usr", "/usr/local", "/opt/homebrew", "/opt/local", os.homedir()]);
100
+ /**
101
+ * The directory an executable was installed as a whole with, when relay can tell: a Homebrew keg
102
+ * (Cellar/<name>/<version>, Caskroom/<name>/<version>), the npm package that holds it (the nearest
103
+ * directory with a package.json below a node_modules), or a Node distribution's prefix (bin/node
104
+ * beside include/node, as fnm, nvm and the official tarballs lay it out). Writing anywhere in it
105
+ * could change what the executable loads, not only the file itself. Null when none is found.
106
+ */
107
+ export function installDirOf(real) {
108
+ const keg = /^(.*\/(?:Cellar|Caskroom)\/[^/]+\/[^/]+)(?:\/|$)/.exec(real);
109
+ if (keg)
110
+ return keg[1];
111
+ if (real.split(path.sep).includes("node_modules")) {
112
+ for (let dir = path.dirname(real); path.basename(dir) !== "node_modules" && path.dirname(dir) !== dir; dir = path.dirname(dir)) {
113
+ if (fs.existsSync(path.join(dir, "package.json")))
114
+ return dir;
115
+ }
116
+ }
117
+ const bin = path.dirname(real);
118
+ const prefix = path.dirname(bin);
119
+ if (path.basename(bin) === "bin" && path.basename(real).startsWith("node") && !SHARED_PREFIXES.has(prefix) && fs.existsSync(path.join(prefix, "include", "node")))
120
+ return prefix;
121
+ return null;
122
+ }
123
+ /**
124
+ * One executable's parts: the name relay starts (findExecutable's: a link's own name, on purpose),
125
+ * the file it leads to, and the installation holding that. All three are protected alike.
126
+ */
127
+ function executableParts(what, named) {
128
+ const real = realOf(named);
129
+ const dir = real ? installDirOf(real) : null;
130
+ return [
131
+ { what, path: named },
132
+ ...(real && real !== named ? [{ what, path: real }] : []),
133
+ ...(dir ? [{ what: `the installation of ${what}`, path: dir }] : []),
134
+ ];
135
+ }
136
+ /**
137
+ * What relay itself runs on and from: its package (relayPackageRoot), by its name and real path,
138
+ * the Node binary running it (with its installation), and the git it runs (executables.ts
139
+ * gitExecutable: the name on PATH, the file it leads to and its Homebrew keg; for the xcrun shim
140
+ * /usr/bin/git, the developer directories whose git the shim runs). Every Seatbelt profile relay
141
+ * writes denies writing these, and so does Claude's sandbox; no grant may cover them.
142
+ */
143
+ export function relayRuntime() {
144
+ const root = relayPackageRoot();
145
+ const real = realOf(root);
146
+ const gitBin = gitExecutable();
147
+ const gitReal = gitBin ? realOf(gitBin) : null;
148
+ return [
149
+ { what: "relay's own installation", path: root },
150
+ ...(real && real !== root ? [{ what: "relay's own installation", path: real }] : []),
151
+ ...executableParts("the Node binary relay runs on", process.execPath),
152
+ ...(gitBin ? executableParts("the git relay runs", gitBin) : []),
153
+ ...(gitReal && XCRUN_SHIMS.has(gitReal) ? developerDirs().map((d) => ({ what: "the developer tools whose git /usr/bin/git runs", path: d })) : []),
154
+ ];
155
+ }
156
+ /**
157
+ * The directories on relay's PATH: where relay found the programs it runs, and where a program put
158
+ * by a job would be found before them by a later lookup (a new process of relay's, your own shell).
159
+ * No grant may cover one (caller.ts grantPathProblem), and no file request may write in one.
160
+ */
161
+ export function relayPathDirs(searchPath = process.env.PATH ?? "") {
162
+ // With the stand-ins' directory of a test of the terminal commands, where honoured (executables.ts testSystemTools).
163
+ const dirs = [...searchPath.split(path.delimiter), testSystemTools() ?? ""];
164
+ return [...new Set(dirs.filter((d) => d && path.isAbsolute(d)).map((d) => path.resolve(d)))];
165
+ }
166
+ /** Whether `p` and a protected `part` overlap: either holds the other, by any case or data-volume name, or `p` covers or names a link `part` by its own name. */
167
+ export const overlapsPart = (p, part) => insideAnyCase(p, part) || insideAnyCase(part, p) || overlapsEntryAnyCase(p, part);
168
+ /**
169
+ * relayRuntime, and every target CLI relay could start outside any sandbox (codex app-server,
170
+ * claude, gemini and the others, and their version probes): for each target, enabled or not (one
171
+ * enabled later would run what a grant given now let a job write), its configured `bin` and its
172
+ * default name, each as found on PATH now, the file it leads to, and that file's installation
173
+ * (installDirOf). What no grant may overlap, new or kept (caller.ts grantPathProblem). A grant's
174
+ * paths are checked against this when given and on every later turn that keeps them.
175
+ * This deliberately includes interactive Codex even when launches use the sealed pin: the
176
+ * configured/default CLI remains a possible executable (including an explicit pin opt-out).
177
+ * Protect its resolved installation too, not only the stable symlink: a write through another
178
+ * name in that installation could change what the CLI loads. Package-manager replacements
179
+ * therefore invalidate a captured identity checkpoint. A later checkpoint can absorb ordinary
180
+ * CLI/runtime replacements; only sealed Codex pin-store replacements require a fresh run.
181
+ */
182
+ export function relayInstallation() {
183
+ let bins = {};
184
+ try {
185
+ const cfg = loadConfig(() => { });
186
+ bins = Object.fromEntries(TARGET_IDS.map((id) => [id, cfg.targets[id]?.bin ?? targetDef(id).defaultBin]));
187
+ }
188
+ catch {
189
+ // A config relay cannot load refuses the call elsewhere; the default names are still protected.
190
+ }
191
+ const parts = relayRuntime();
192
+ // The Node relay's launcher (bin/relay) would choose at its next start, where it can be told now:
193
+ // RELAY_NODE, then the first node on PATH. Not the version managers' fallbacks it tries after them.
194
+ for (const node of [process.env.RELAY_NODE, "node"]) {
195
+ const named = node ? findExecutable(node) : null;
196
+ if (named)
197
+ parts.push(...executableParts("the Node relay's launcher starts relay on", named));
198
+ }
199
+ for (const id of TARGET_IDS) {
200
+ for (const bin of new Set([bins[id], targetDef(id).defaultBin].filter((b) => Boolean(b)))) {
201
+ const named = findExecutable(bin);
202
+ if (named)
203
+ parts.push(...executableParts(`the ${id} target's CLI (${targetDef(id).product})`, named));
204
+ }
205
+ }
206
+ const seen = new Set();
207
+ return parts.filter((p) => !seen.has(p.path) && Boolean(seen.add(p.path)));
208
+ }
209
+ /**
210
+ * What every sandbox relay sets up denies writing (seatbelt.ts boundaryPaths, Claude's denyWrite):
211
+ * relayInstallation, and each directory on relay's PATH.
212
+ */
213
+ export function relayWriteProtected() {
214
+ const codex = relayCodexProtected();
215
+ return [...relayInstallation(), ...codex.homes, ...codex.stores, ...relayPathDirs().map((d) => ({ what: "a directory on relay's PATH", path: d }))];
216
+ }
217
+ /**
218
+ * Why a turn may not start a target's CLI, as found on the PATH its launch uses (`searchPath`), or
219
+ * null: when that CLI, the file it leads to or its installation overlaps one of the turn's write
220
+ * paths, or one of the turn's write paths covers or lies in a directory of that PATH. Admission
221
+ * judged grants against relay's own PATH and config (caller.ts grantPathProblem); this judges them
222
+ * against the turn's, so the two cannot disagree.
223
+ */
224
+ export function targetLaunchProblem(what, bin, searchPath, writePaths) {
225
+ if (!writePaths.length)
226
+ return null;
227
+ const named = findExecutable(bin, searchPath);
228
+ const parts = named ? executableParts(what, named) : [];
229
+ for (const p of writePaths) {
230
+ const part = parts.find((x) => overlapsPart(p, x.path));
231
+ if (part)
232
+ return `relay will not start ${what} for this turn: it is ${named}, and its ${part.path === named ? "name" : part.what === what ? "file" : "installation"} (${part.path}) overlaps the job's write path ${p}, which a job could change. Grant a directory outside it.`;
233
+ const dir = relayPathDirs(searchPath).find((d) => insideAnyCase(p, d) || insideAnyCase(d, p));
234
+ if (dir)
235
+ return `relay will not start ${what} for this turn: the job's write path ${p} overlaps ${dir}, a directory on the PATH the turn would start it from, where a job could put a program found first. Grant a directory outside it.`;
236
+ }
237
+ return null;
238
+ }