@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,453 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { SPEEDS, TARGET_IDS, targetDef } from "../targets/index.js";
6
+ import { backendOwnedEnvironmentName, effectiveChildEnv, ENVIRONMENT_NAME, mandatoryEnvironmentReason } from "./env-policy.js";
7
+ import { NEVER_RETIRED_BUILTIN_IDS, NeverConfigSchema } from "./never-schema.js";
8
+ /** Whether a session's turns have the network: a grant gives it, and so does child_network for every launched agent. */
9
+ export const networkOn = (cfg, grant) => Boolean(grant?.network || cfg.child_network);
10
+ /** relay's own CLI as built (dist/cli.js), which relay runs to start its workers and launched agents' relay servers. */
11
+ export const RELAY_CLI = path.resolve(import.meta.dirname, "..", "cli.js");
12
+ /**
13
+ * `p` with a leading `~` (alone, or followed by `/`) replaced by the home folder. Nothing else:
14
+ * each caller resolves the result, or checks that it is absolute, in its own way (review C1).
15
+ */
16
+ export const expandHome = (p) => p.replace(/^~(?=$|\/)/, os.homedir());
17
+ /** Relay's version, from package.json. */
18
+ export const VERSION = (() => {
19
+ try {
20
+ return String(JSON.parse(fs.readFileSync(path.resolve(import.meta.dirname, "..", "..", "package.json"), "utf8")).version);
21
+ }
22
+ catch {
23
+ return "unknown";
24
+ }
25
+ })();
26
+ const vendorOf = (id) => targetDef(id).vendor;
27
+ /** A target's entry when the config says nothing about it. */
28
+ const targetDefaults = (id) => ({ enabled: targetDef(id).enabledByDefault, bin: targetDef(id).defaultBin,
29
+ ...(id === "codex" ? { home: "~/.local/share/relay-codex-home", pin_store: "~/.local/share/relay-codex-pins", pinned: true } : {}) });
30
+ export const relayCodexHome = (cfg) => path.resolve(expandHome(cfg.targets.codex.home ?? "~/.local/share/relay-codex-home"));
31
+ export const relayCodexPinStore = (cfg) => path.resolve(expandHome(cfg.targets.codex.pin_store ?? "~/.local/share/relay-codex-pins"));
32
+ /** The earlier per-target keys, and the field of targets.<id> each one sets. */
33
+ const LEGACY = { bin: "bin", default_model: "default_model", default_effort: "default_effort" };
34
+ export const DEFAULT_CONFIG = {
35
+ never: { paths: [], ports: [], hosts: [], override_builtin: [] },
36
+ max_depth: 3,
37
+ max_concurrent: 4,
38
+ block_s: 240,
39
+ job_timeout_s: null,
40
+ turn_timeout_s: null,
41
+ cancel_grace_ms: 5000,
42
+ child_mcp: "relay-only",
43
+ child_hooks: false,
44
+ child_network: false,
45
+ child_git: "relay",
46
+ allow_dangerous: false,
47
+ escalation: true,
48
+ approval_timeout_s: 3600,
49
+ desktop_notifications: false,
50
+ ask_user: "auto",
51
+ child_web: "inherit",
52
+ codex_backend: "app-server",
53
+ allow_temp_home: false,
54
+ child_settings: "isolated",
55
+ child_auth: "login",
56
+ child_env: { policy: "allowlist", pass: [], drop: [], request: [] },
57
+ trust_git_filters: false,
58
+ claude_managed_settings: "refuse",
59
+ claude_settings_env: "refuse",
60
+ codex_endpoint_override: "refuse",
61
+ allow_untested: false,
62
+ same_family: "allow",
63
+ keep_records_days: null,
64
+ log_max_mb: null,
65
+ // Every target's entry, from the registry, read when first used (the registry may still be loading when this module is).
66
+ get targets() {
67
+ return Object.fromEntries(TARGET_IDS.map((id) => [id, targetDefaults(id)]));
68
+ },
69
+ default_target: {},
70
+ };
71
+ /** State directory: registry, logs, transcripts, worktrees. */
72
+ export function relayHome() {
73
+ return process.env.RELAY_HOME || path.join(os.homedir(), ".local", "state", "relay");
74
+ }
75
+ /**
76
+ * Where job worktrees live. Deliberately outside the control directory: agents write in their
77
+ * worktrees, and nothing an agent can write should sit next to the registry.
78
+ */
79
+ export function worktreesHome() {
80
+ if (process.env.RELAY_WORKTREES)
81
+ return process.env.RELAY_WORKTREES;
82
+ if (process.env.RELAY_HOME)
83
+ return `${process.env.RELAY_HOME.replace(/\/+$/, "")}-worktrees`;
84
+ return path.join(os.homedir(), ".local", "share", "relay", "worktrees");
85
+ }
86
+ /**
87
+ * Where relay keeps the state of harnesses it confines itself (Copilot's home, say), one directory
88
+ * per session, so that their sessions carry from turn to turn. Outside the control directory,
89
+ * which a confined agent may not read, and beside the worktrees, as theirs is agents' state.
90
+ */
91
+ export function harnessHome() {
92
+ if (process.env.RELAY_HOME)
93
+ return `${process.env.RELAY_HOME.replace(/\/+$/, "")}-harness`;
94
+ return path.join(os.homedir(), ".local", "share", "relay", "harness");
95
+ }
96
+ /**
97
+ * Where consults work when their root session names no directory and relay was started outside any
98
+ * project (the desktop app): each new thread in a new, empty directory of its own under this one
99
+ * (caller.ts newConsultDir), so that a question needs no project and the consulted agent is not
100
+ * pointed at your home. Outside the control directory; no job may be granted it.
101
+ */
102
+ export function consultHome() {
103
+ if (process.env.RELAY_HOME)
104
+ return `${process.env.RELAY_HOME.replace(/\/+$/, "")}-consult`;
105
+ return path.join(os.homedir(), ".local", "share", "relay", "consult");
106
+ }
107
+ export function worktreeDir(runId, jobId) {
108
+ return path.join(worktreesHome(), runId, jobId);
109
+ }
110
+ /**
111
+ * The real path, for a path that may not exist yet: its nearest existing ancestor is resolved and
112
+ * the rest appended. On macOS /tmp and /var are aliases, and a directory about to be created
113
+ * under one of them must compare equal to its resolved form. The existing part is resolved by the
114
+ * system (realpath(3)), which also gives each name its case on disk: on macOS's default disks,
115
+ * which ignore case, `~/.CONFIG` is `~/.config`, and Node's own realpathSync keeps the case it was given.
116
+ */
117
+ export function canonical(p) {
118
+ let cur = path.resolve(p);
119
+ const rest = [];
120
+ for (;;) {
121
+ try {
122
+ return path.join(fs.realpathSync.native(cur), ...rest);
123
+ }
124
+ catch {
125
+ const parent = path.dirname(cur);
126
+ if (parent === cur)
127
+ return path.join(cur, ...rest);
128
+ rest.unshift(path.basename(cur));
129
+ cur = parent;
130
+ }
131
+ }
132
+ }
133
+ const under = (c, p) => c === p || c.startsWith(p.endsWith(path.sep) ? p : p + path.sep);
134
+ /** True when child is parent or lies under it. Correct for a filesystem root, which already ends in a separator. */
135
+ export const inside = (child, parent) => under(canonical(child), canonical(parent));
136
+ /**
137
+ * A canonical path as a check that keeps paths out compares it (relay's own directories and config
138
+ * files): on macOS, whose default disks ignore case and Unicode normalisation, without either,
139
+ * and under the short name of a directory the data volume firmlinks into / (/Users for
140
+ * /System/Volumes/Data/Users). canonical() gives the part of a path that exists its name on disk,
141
+ * but not a part that does not exist yet, and a file made there under another case of a name is the
142
+ * file of that name.
143
+ */
144
+ export const foldedPath = (p) => {
145
+ if (process.platform !== "darwin")
146
+ return canonical(p);
147
+ const folded = canonical(p).normalize("NFC").toLowerCase();
148
+ // The data volume's own name for a firmlinked directory: /System/Volumes/Data/Users is /Users, and
149
+ // realpath(3) leaves each name as it is given. Folded to the short name, so that neither names a
150
+ // kept-out path past the check. A name with no firmlink behind it is folded too: that can only keep
151
+ // more out.
152
+ if (folded === DATA_VOLUME)
153
+ return "/";
154
+ return folded.startsWith(`${DATA_VOLUME}/`) ? folded.slice(DATA_VOLUME.length) : folded;
155
+ };
156
+ /** Where macOS mounts the data volume, whose top-level directories are firmlinked into / (lower case, as foldedPath compares). */
157
+ const DATA_VOLUME = "/system/volumes/data";
158
+ /**
159
+ * inside(), for a check that keeps a path out: on macOS a name in another case, or under the data
160
+ * volume's name, counts as the same. Never for a check that lets a path in, where a disk that does
161
+ * tell case apart would make two names one.
162
+ */
163
+ export const insideAnyCase = (child, parent) => under(foldedPath(child), foldedPath(parent));
164
+ /**
165
+ * insideAnyCase in either direction for an entry that is (or will be) a link, compared by its own
166
+ * name: its directory is resolved, the entry is not. True for a path that covers the link (and so
167
+ * could replace it) or names it. A path through a link that exists resolves to where the link leads
168
+ * and is not caught here: a check of that place (the grant check's of ~/.rn) has to catch it.
169
+ */
170
+ export const overlapsEntryAnyCase = (p, entry) => {
171
+ const byName = (q) => {
172
+ const name = path.basename(path.resolve(q));
173
+ return path.join(foldedPath(path.dirname(path.resolve(q))), process.platform === "darwin" ? name.normalize("NFC").toLowerCase() : name);
174
+ };
175
+ const own = byName(entry);
176
+ // `p` resolved, and `p` by its own last name (the link itself, when `p` names it).
177
+ return [foldedPath(p), byName(p)].some((other) => under(own, other) || under(other, own));
178
+ };
179
+ /** True when a path is in a directory that both agents' sandboxes leave writable. */
180
+ export function underTemp(p) {
181
+ return [os.tmpdir(), "/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"].some((t) => inside(p, t));
182
+ }
183
+ export function configPath() {
184
+ if (process.env.RELAY_CONFIG)
185
+ return process.env.RELAY_CONFIG;
186
+ if (process.env.RELAY_HOME)
187
+ return path.join(process.env.RELAY_HOME, "config.json");
188
+ return path.join(os.homedir(), ".config", "relay", "config.json");
189
+ }
190
+ /** An object keyed by target id, every key optional, no other keys. */
191
+ const byTarget = (value) => z.object(Object.fromEntries(TARGET_IDS.map((id) => [id, value]))).partial().strict();
192
+ const side = byTarget(z.string().min(1));
193
+ /**
194
+ * A skill as targets.<id>.skills names it: a skill directory's name (looked up in the target CLI's
195
+ * own user skill directories), or the path of a skill directory, absolute or under ~/.
196
+ */
197
+ const skillRef = z.string().refine((v) => /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(v) || ((v.startsWith("/") || v.startsWith("~/")) && !v.split("/").includes("..")), {
198
+ message: "a skill is the name of one of your skill directories (letters, digits, '.', '_', '-') or the absolute or ~/ path of a skill directory",
199
+ });
200
+ /** A server's name in relay's mcp.json. It prefixes its tools' names (<server>__<tool>), so it holds no double underscore. */
201
+ export const SERVER_NAME = /^(?!.*__)[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
202
+ const serverName = z.string().regex(SERVER_NAME, "an MCP server's name is up to 32 letters, digits, '_' or '-', without '__'");
203
+ const toolName = z.string().min(1).max(64);
204
+ const environmentName = z.string().regex(ENVIRONMENT_NAME, "use an exact environment variable name (letters, digits and underscore; no wildcards)");
205
+ const childEnvSchema = z.object({
206
+ policy: z.enum(["allowlist", "legacy"], { error: "child_env.policy must be allowlist or legacy; tool-denylist is not available yet" }).optional(),
207
+ pass: z.array(environmentName).optional(), drop: z.array(environmentName).optional(), request: z.array(environmentName).optional(),
208
+ }).strict();
209
+ const targetSchema = z.object({
210
+ enabled: z.boolean(), bin: z.string().min(1), default_model: z.string().min(1), default_effort: z.string().min(1),
211
+ speed: z.enum(SPEEDS),
212
+ child_auth: z.enum(["login", "any"]),
213
+ child_env: childEnvSchema,
214
+ experimental: z.boolean(),
215
+ skills: z.union([z.enum(["none", "user"]), z.array(skillRef).min(1)]),
216
+ mcp_servers: z.array(z.union([serverName, z.object({ name: serverName, allow_tools: z.array(toolName).optional() }).strict()])),
217
+ }).partial().strict();
218
+ const codexTargetSchema = targetSchema.extend({ daybreak: z.boolean().optional(), stage2: z.boolean().optional(),
219
+ home: z.string().min(1).refine((p) => path.isAbsolute(expandHome(p)), "must be absolute or start with ~/").optional(),
220
+ pin_store: z.string().min(1).refine((p) => path.isAbsolute(expandHome(p)), "must be absolute or start with ~/").optional(),
221
+ pinned: z.boolean().optional() });
222
+ const seconds = z.number().positive();
223
+ /** What a config file may contain. Unknown keys and wrong types are errors, not ignored: a quoted "false" must never read as true. */
224
+ export const ConfigSchema = z.object({
225
+ never: NeverConfigSchema,
226
+ max_depth: z.number().int().min(1).max(10),
227
+ max_concurrent: z.number().int().min(1).max(64),
228
+ block_s: seconds, job_timeout_s: seconds.nullable(), turn_timeout_s: seconds.nullable(),
229
+ cancel_grace_ms: z.number().nonnegative(),
230
+ child_mcp: z.enum(["relay-only", "inherit"]),
231
+ child_hooks: z.boolean(), child_network: z.boolean(),
232
+ child_git: z.enum(["relay", "native"]),
233
+ allow_dangerous: z.boolean(), escalation: z.union([z.boolean(), z.strictObject({ enabled: z.boolean().optional(), port0_authority: z.enum(["supervisor", "person"]).optional() })]),
234
+ approval_timeout_s: seconds, desktop_notifications: z.boolean(), notify: z.boolean(),
235
+ ask_user: z.enum(["auto", "always", "never"]),
236
+ child_web: z.enum(["inherit", "ask"]),
237
+ codex_backend: z.enum(["app-server", "exec"]),
238
+ allow_temp_home: z.boolean(),
239
+ child_settings: z.enum(["isolated", "inherit"]),
240
+ child_auth: z.enum(["login", "any"]),
241
+ child_env: childEnvSchema,
242
+ trust_git_filters: z.boolean(),
243
+ claude_managed_settings: z.enum(["refuse", "accept"]),
244
+ claude_settings_env: z.enum(["refuse", "accept"]),
245
+ codex_endpoint_override: z.enum(["refuse", "accept"]),
246
+ allow_untested: z.boolean(),
247
+ same_family: z.enum(["refuse", "allow"]),
248
+ keep_records_days: z.number().positive().nullable(),
249
+ log_max_mb: z.number().positive().nullable(),
250
+ default_model: side, default_effort: side, bin: side,
251
+ targets: z.object({ ...byTarget(targetSchema).shape, codex: codexTargetSchema.optional() }).strict(),
252
+ default_target: z.object({ ...byTarget(z.enum(TARGET_IDS)).shape, unknown: z.enum(TARGET_IDS).optional() }).strict().partial(),
253
+ }).strict().partial().superRefine((cfg, ctx) => {
254
+ for (const problem of configConflicts(cfg))
255
+ ctx.addIssue({ code: "custom", path: problem.path, message: problem.message });
256
+ });
257
+ /** What a config sets twice (an earlier per-target key and targets.<id>), or a default target that crosses no family. */
258
+ function configConflicts(cfg) {
259
+ const out = [];
260
+ // Root entries apply to every destination; target entries are checked against that target.
261
+ const guardConfig = { child_auth: cfg.child_auth ?? "login", targets: cfg.targets ?? {} };
262
+ const checkEnv = (setting, ids, prefix) => {
263
+ if (!setting)
264
+ return;
265
+ for (const key of ["pass", "request"])
266
+ for (const name of setting[key] ?? []) {
267
+ // A root entry is an error only where no target could ever receive it (GH_TOKEN at the root
268
+ // serves gh in Claude and Codex jobs; Copilot's login guard still keeps it from Copilot, at
269
+ // selection, and doctor names that reason). A target's own entry must be selectable for it.
270
+ const reasons = ids.map((id) => mandatoryEnvironmentReason(id, guardConfig, name));
271
+ if (reasons.every(Boolean)) {
272
+ out.push({ path: [...prefix, key], message: `${name} cannot be selected for ${ids.length === 1 ? ids[0] : "any target"}: ${reasons[0]}` });
273
+ }
274
+ }
275
+ for (const name of setting.drop ?? [])
276
+ if (backendOwnedEnvironmentName(name))
277
+ out.push({ path: [...prefix, "drop"], message: `${name} cannot be dropped: backend-owned control` });
278
+ };
279
+ checkEnv(cfg.child_env, TARGET_IDS, ["child_env"]);
280
+ for (const id of TARGET_IDS)
281
+ checkEnv(cfg.targets?.[id]?.child_env, [id], ["targets", id, "child_env"]);
282
+ for (const [legacy, field] of Object.entries(LEGACY)) {
283
+ for (const id of Object.keys(cfg[legacy] ?? {})) {
284
+ if (cfg.targets?.[id]?.[field] !== undefined)
285
+ out.push({ path: [legacy, id], message: `set both here and as targets.${id}.${field}; keep one` });
286
+ }
287
+ }
288
+ if (cfg.notify !== undefined && cfg.desktop_notifications !== undefined)
289
+ out.push({ path: ["notify"], message: "set both here and as desktop_notifications, its new name; keep desktop_notifications" });
290
+ for (const [from, to] of Object.entries(cfg.default_target ?? {})) {
291
+ if (from !== "unknown" && vendorOf(from) !== null && vendorOf(from) === vendorOf(to))
292
+ out.push({ path: ["default_target", from], message: `${to} is the same family as ${from}, which relay never reaches from it` });
293
+ }
294
+ // A speed the target has not got, or not for its default model, would refuse every call that names neither.
295
+ for (const [id, t] of Object.entries(cfg.targets ?? {})) {
296
+ if (!t?.speed || t.speed === "standard" || !TARGET_IDS.includes(id))
297
+ continue;
298
+ const def = targetDef(id);
299
+ const option = def.speeds?.[t.speed];
300
+ const model = t.default_model ?? cfg.default_model?.[id];
301
+ if (!option) {
302
+ const has = SPEEDS.filter((s) => s === "standard" || def.speeds?.[s]);
303
+ out.push({ path: ["targets", id, "speed"], message: `${def.name} has no ${t.speed} speed in relay; it runs at ${has.join(" or ")}` });
304
+ }
305
+ else if (option.models && model && option.models.has(model) === false) {
306
+ out.push({ path: ["targets", id, "speed"], message: `${def.name}'s ${t.speed} speed is for ${option.models.names} only, and its default model is ${JSON.stringify(model)}` });
307
+ }
308
+ }
309
+ out.push(...extensionConflicts(cfg));
310
+ return out;
311
+ }
312
+ /** The name of an entry of targets.<id>.mcp_servers. */
313
+ export const serverOf = (e) => (typeof e === "string" ? e : e.name);
314
+ /** Whether a target's entry gives it any extension at all. */
315
+ export const hasExtensions = (t) => Boolean((t?.skills !== undefined && t.skills !== "none") || t?.mcp_servers?.length);
316
+ /**
317
+ * What a config cannot hold together with extensions (docs/extensions.md): a target that cannot
318
+ * take them; the legacy inheritance settings, which load the person's own servers, hooks or
319
+ * settings ungated (review C17); for MCP servers, network for every job or full access, which
320
+ * would let an agent use credentials it can read past relay's gate (review C2/X1); any extension
321
+ * without approval requests, which the person's consent is; any extension for Codex under the exec
322
+ * backend, which has no way to give skills or to check which skills it loads (a turn given MCP
323
+ * servers alone is checked for skills too).
324
+ */
325
+ function extensionConflicts(cfg) {
326
+ const out = [];
327
+ const setting = (k) => cfg[k] ?? DEFAULT_CONFIG[k];
328
+ for (const id of Object.keys(cfg.targets ?? {})) {
329
+ const t = cfg.targets[id];
330
+ if (!hasExtensions(t))
331
+ continue;
332
+ const keys = [...(t.skills !== undefined && t.skills !== "none" ? ["skills"] : []), ...(t.mcp_servers?.length ? ["mcp_servers"] : [])];
333
+ const at = (key) => ["targets", id, key];
334
+ if (!targetDef(id).capabilities.extensions) {
335
+ for (const key of keys)
336
+ out.push({ path: at(key), message: `relay gives extensions only to Claude and Codex agents; ${targetDef(id).name} runs inside relay's own sandbox, which a skill or server from outside would cross. Remove it` });
337
+ continue;
338
+ }
339
+ const first = keys[0];
340
+ // child_settings is about Claude Code's settings files alone, so it waives nothing for a Codex agent.
341
+ for (const [legacy, waives, what] of [
342
+ ["child_mcp", setting("child_mcp") === "inherit", 'child_mcp "inherit" loads every MCP server of yours in every launched agent'],
343
+ ["child_hooks", setting("child_hooks"), "child_hooks true runs your hooks in every launched agent"],
344
+ ["child_settings", id === "claude" && setting("child_settings") === "inherit", 'child_settings "inherit" loads your Claude Code settings, plugins and skills among them, in every launched Claude agent'],
345
+ ]) {
346
+ if (waives)
347
+ out.push({ path: at(first), message: `extensions cannot be combined with ${legacy}: ${what}, ungated, which would make the allowlist meaningless. Use one or the other` });
348
+ }
349
+ if (!escalationEnabled({ escalation: setting("escalation") }))
350
+ out.push({ path: at(first), message: "extensions need the user's consent, which relay asks for as an approval request, and escalation is false" });
351
+ if (t.mcp_servers?.length) {
352
+ if (setting("child_network"))
353
+ out.push({ path: at("mcp_servers"), message: "MCP servers cannot be combined with child_network: an agent with the network could use credentials it can read to reach a server's service directly, past relay's gate" });
354
+ if (setting("allow_dangerous"))
355
+ out.push({ path: at("mcp_servers"), message: "MCP servers cannot be combined with allow_dangerous: a write job with full access could reach a server's service directly, past relay's gate" });
356
+ const seen = new Set();
357
+ for (const e of t.mcp_servers) {
358
+ const name = serverOf(e);
359
+ if (seen.has(name))
360
+ out.push({ path: at("mcp_servers"), message: `${name} is named more than once` });
361
+ seen.add(name);
362
+ }
363
+ }
364
+ if (id === "codex" && setting("codex_backend") === "exec") {
365
+ out.push({ path: at(first), message: '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, which a session given MCP servers alone is checked for too' });
366
+ }
367
+ }
368
+ return out;
369
+ }
370
+ /** Checks a parsed config file. Returns the settings it gives, or throws naming every problem. */
371
+ export function validateConfig(raw, where) {
372
+ // Without zod's compiled fast path (jitless, its documented switch for that): a config is a small
373
+ // object checked a few times per call, where compiling a parser for its every object, which the
374
+ // first check would do, costs more than it saves. The checks themselves are the same.
375
+ const r = ConfigSchema.safeParse(raw, { jitless: true });
376
+ if (r.success)
377
+ return r.data;
378
+ const problems = r.error.issues.map((i) => `${i.path.join(".") || "(top level)"}: ${i.message}`).join("; ");
379
+ throw new Error(`relay config at ${where} is not valid, so relay will not start with it. ${problems}`);
380
+ }
381
+ /** Deprecated spellings stay readable throughout 1.x. Never include config values in diagnostics. */
382
+ export function configDeprecations(user) {
383
+ const replacements = { bin: "targets.<id>.bin", default_model: "targets.<id>.default_model", default_effort: "targets.<id>.default_effort", notify: "desktop_notifications" };
384
+ const warnings = Object.entries(replacements).filter(([key]) => user[key] !== undefined)
385
+ .map(([key, replacement]) => `config key ${key} is deprecated; use ${replacement}. ${key} remains accepted throughout relay 1.x.`);
386
+ for (const removal of user.never?.override_builtin ?? [])
387
+ warnings.push(NEVER_RETIRED_BUILTIN_IDS.includes(removal.id)
388
+ ? `never.override_builtin names ${removal.id}, which is no longer a built-in never entry (relay 1.2.1), so it removes nothing. Delete it; list any port you want kept from jobs under never.ports with destinations "this-machine". It remains accepted throughout relay 1.x.`
389
+ : `NEVER PROTECTION REMOVED: ${removal.id}. ${removal.acknowledge}. Reason: ${removal.reason}. Removal grants nothing and cannot shrink an existing run's never floor.`);
390
+ if (user.child_auth === "any")
391
+ warnings.push('global child_auth "any" no longer forwards other vendors\' credentials in relay 1.0; use targets.<id>.child_auth "any" and exact child_env.pass entries for that target\'s own auth inputs');
392
+ const config = { child_env: user.child_env, targets: user.targets ?? {} };
393
+ const legacy = TARGET_IDS.filter((id) => effectiveChildEnv(config, id).policy === "legacy");
394
+ if (legacy.length)
395
+ warnings.push(`child_env.policy legacy inherits unknown environment variables for ${legacy.join(", ")}; use allowlist and exact pass/request names. Legacy never disables mandatory target guards`);
396
+ return warnings;
397
+ }
398
+ /**
399
+ * Loads the user's config. Only a root instance calls this; the result is snapshotted into the
400
+ * run row so that every process in a run works under the same limits.
401
+ */
402
+ export function loadConfig(warn = (message) => process.stderr.write(`relay: WARNING: ${message}\n`)) {
403
+ const file = configPath();
404
+ let user = {};
405
+ if (fs.existsSync(file)) {
406
+ let raw;
407
+ try {
408
+ raw = JSON.parse(fs.readFileSync(file, "utf8"));
409
+ }
410
+ catch (err) {
411
+ throw new Error(`relay config at ${file} is not valid JSON: ${err.message}`);
412
+ }
413
+ user = validateConfig(raw, file);
414
+ }
415
+ configDeprecations(user).forEach(warn);
416
+ return withDefaults(user);
417
+ }
418
+ /**
419
+ * A config with every setting present, and every target's entry, the earlier per-target keys
420
+ * moved into them. Also used for a run's stored config, which may predate a setting or be in the
421
+ * earlier form.
422
+ */
423
+ export function withDefaults(user) {
424
+ const conflicts = configConflicts(user);
425
+ if (conflicts.length)
426
+ throw new Error(`relay config is not valid: ${conflicts.map((c) => `${c.path.join(".")}: ${c.message}`).join("; ")}`);
427
+ const { bin, default_model, default_effort, targets, notify, ...rest } = user;
428
+ const legacy = { bin, default_model, default_effort };
429
+ const entries = TARGET_IDS.map((id) => {
430
+ const entry = { ...targetDefaults(id), ...(targets?.[id] ?? {}) };
431
+ for (const [key, field] of Object.entries(LEGACY)) {
432
+ const v = legacy[key]?.[id];
433
+ if (v !== undefined)
434
+ entry[field] = v;
435
+ }
436
+ return [id, entry];
437
+ });
438
+ return {
439
+ ...DEFAULT_CONFIG, ...rest, ...(notify !== undefined && rest.desktop_notifications === undefined ? { desktop_notifications: notify } : {}), targets: Object.fromEntries(entries), default_target: { ...(user.default_target ?? {}) }
440
+ };
441
+ }
442
+ /** Legacy booleans keep their meaning; the object form owns the single port-0 policy key. */
443
+ export const escalationEnabled = (cfg) => typeof cfg.escalation === "boolean" ? cfg.escalation : cfg.escalation.enabled !== false;
444
+ /** How a target signs in: its own child_auth, or the global one. */
445
+ export const authFor = (cfg, id) => cfg.targets[id]?.child_auth ?? cfg.child_auth;
446
+ export function runDir(runId) {
447
+ return path.join(relayHome(), "runs", runId);
448
+ }
449
+ export function nodeDir(runId, nodeId) {
450
+ const dir = path.join(runDir(runId), "nodes", nodeId);
451
+ fs.mkdirSync(dir, { recursive: true });
452
+ return dir;
453
+ }
@@ -0,0 +1,186 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { ancestors, getNode, getRun } from "./db.js";
5
+ import { writing } from "./storage.js";
6
+ export const CONTEXT_DIR = ".relay";
7
+ export const CONTEXT_FILE = "context.json";
8
+ /** Far more than a context file ever holds. A bigger one is not relay's. */
9
+ const CONTEXT_MAX_BYTES = 4096;
10
+ /**
11
+ * The contents of a small regular file, read without following a link at its name and without
12
+ * blocking on a FIFO or device left in its place: relay reads some files from directories an agent
13
+ * can write (a worktree's `.relay/context.json` and `.git`). Throws, saying why, for anything that
14
+ * is not a regular file of at most `maxBytes` bytes. Checked before opening and again on the open
15
+ * file, so a swap in between is caught too.
16
+ */
17
+ export function readRegularFile(file, maxBytes) {
18
+ const st = fs.lstatSync(file);
19
+ if (st.isSymbolicLink())
20
+ throw new Error("it is a symbolic link");
21
+ if (!st.isFile())
22
+ throw new Error("it is not a regular file");
23
+ if (st.size > maxBytes)
24
+ throw new Error(`it is larger than ${maxBytes} bytes`);
25
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
26
+ try {
27
+ const open = fs.fstatSync(fd);
28
+ if (!open.isFile() || open.ino !== st.ino || open.dev !== st.dev)
29
+ throw new Error("it was replaced while relay read it");
30
+ const buf = Buffer.alloc(maxBytes + 1);
31
+ let n = 0;
32
+ while (n < buf.length) {
33
+ const got = fs.readSync(fd, buf, n, buf.length - n, n);
34
+ if (got === 0)
35
+ break;
36
+ n += got;
37
+ }
38
+ if (n > maxBytes)
39
+ throw new Error(`it is larger than ${maxBytes} bytes`);
40
+ return buf.subarray(0, n).toString("utf8");
41
+ }
42
+ finally {
43
+ fs.closeSync(fd);
44
+ }
45
+ }
46
+ function readContextFile(file) {
47
+ // In a worktree the agent can write both: a link at `.relay` would have relay read a file elsewhere.
48
+ const dir = fs.lstatSync(path.dirname(file));
49
+ if (!dir.isDirectory())
50
+ throw new Error(`${path.dirname(file)} is not a directory`);
51
+ const raw = JSON.parse(readRegularFile(file, CONTEXT_MAX_BYTES));
52
+ if (typeof raw?.run_id !== "string" || typeof raw.node_id !== "string" || typeof raw.depth !== "number") {
53
+ throw new Error("missing run_id, node_id or depth");
54
+ }
55
+ return raw;
56
+ }
57
+ /** Whether anything is at `p`, a dangling link included: something there that is not a context file counts against. */
58
+ function present(p) {
59
+ try {
60
+ fs.lstatSync(p);
61
+ return true;
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ }
67
+ function findUp(start) {
68
+ let dir = path.resolve(start);
69
+ for (;;) {
70
+ const candidate = path.join(dir, CONTEXT_DIR, CONTEXT_FILE);
71
+ if (present(candidate))
72
+ return candidate;
73
+ const parent = path.dirname(dir);
74
+ if (parent === dir)
75
+ return null;
76
+ dir = parent;
77
+ }
78
+ }
79
+ const isAncestorOrSelf = (ancestorId, node) => ancestors(node, { self: true }).some((a) => a.id === ancestorId);
80
+ /**
81
+ * Decides whether this instance is a root, a child, or poisoned.
82
+ *
83
+ * Channels: explicit env in the injected server entry, the --context argument, and
84
+ * .relay/context.json found from cwd upward. If no channel is present this is a root. If any is
85
+ * present, everything present must load and agree with the registry; otherwise the instance is
86
+ * poisoned and refuses to start anything. A child can never fall back to being a root.
87
+ */
88
+ export function loadContext(argv, env, cwd) {
89
+ const argIdx = argv.indexOf("--context");
90
+ const argFile = argIdx >= 0 ? argv[argIdx + 1] : undefined;
91
+ const envKeys = ["RELAY_RUN_ID", "RELAY_NODE_ID", "RELAY_DEPTH", "RELAY_INJECTED"].filter((k) => env[k] !== undefined);
92
+ const cwdFile = findUp(cwd);
93
+ if (argIdx < 0 && envKeys.length === 0 && !cwdFile)
94
+ return { kind: "root" };
95
+ const poisoned = (reason) => ({ kind: "poisoned", reason });
96
+ try {
97
+ if (env.RELAY_INJECTED !== "1") {
98
+ return poisoned("this relay server was not started by relay, but the session is a relay child (duplicate server)");
99
+ }
100
+ if (!argFile)
101
+ return poisoned("the --context argument is missing");
102
+ for (const k of ["RELAY_RUN_ID", "RELAY_NODE_ID", "RELAY_DEPTH"]) {
103
+ if (!env[k])
104
+ return poisoned(`${k} is missing from the environment`);
105
+ }
106
+ let fromArg;
107
+ try {
108
+ fromArg = readContextFile(argFile);
109
+ }
110
+ catch (err) {
111
+ return poisoned(`context file ${argFile} could not be read: ${err.message}`);
112
+ }
113
+ const fromEnv = { run_id: env.RELAY_RUN_ID, node_id: env.RELAY_NODE_ID, depth: Number(env.RELAY_DEPTH) };
114
+ if (fromArg.run_id !== fromEnv.run_id || fromArg.node_id !== fromEnv.node_id || fromArg.depth !== fromEnv.depth) {
115
+ return poisoned("the environment and the context file disagree");
116
+ }
117
+ const run = getRun(fromArg.run_id);
118
+ const node = getNode(fromArg.node_id);
119
+ if (!run || !node)
120
+ return poisoned("the run or node is not in the registry");
121
+ if (node.run_id !== run.id || node.depth !== fromArg.depth)
122
+ return poisoned("the registry disagrees with the context");
123
+ if (cwdFile) {
124
+ // A worktree's file names the job that owns the worktree. An in-place child working inside
125
+ // that worktree is a descendant of that job, so ancestor-or-self is the consistency rule.
126
+ let fromCwd;
127
+ try {
128
+ fromCwd = readContextFile(cwdFile);
129
+ }
130
+ catch (err) {
131
+ return poisoned(`${cwdFile} could not be read: ${err.message}`);
132
+ }
133
+ if (fromCwd.run_id !== run.id || !isAncestorOrSelf(fromCwd.node_id, node)) {
134
+ return poisoned(`${cwdFile} belongs to a different agent`);
135
+ }
136
+ }
137
+ if (typeof fromArg.turn_id !== "number" || (fromArg.access !== "read" && fromArg.access !== "write")) {
138
+ return poisoned("the context file carries no turn policy");
139
+ }
140
+ if (fromArg.extensions !== undefined && typeof fromArg.extensions !== "string")
141
+ return poisoned("the context file's extensions are not a path");
142
+ return {
143
+ kind: "child", runId: run.id, nodeId: node.id, depth: node.depth,
144
+ turnId: fromArg.turn_id, access: fromArg.access, mayDelegate: fromArg.may_delegate === true, mayAsk: fromArg.may_ask === true,
145
+ ...(fromArg.extensions ? { extensions: fromArg.extensions } : {}),
146
+ };
147
+ }
148
+ catch (err) {
149
+ return poisoned(`context check failed: ${err.message}`);
150
+ }
151
+ }
152
+ /** Writes a context file into a directory of relay's own (a node's directory under relay's control directory): what it throws is a write's (storage.ts writing). */
153
+ export function writeContextFile(file, ctx) {
154
+ writing(() => {
155
+ fs.mkdirSync(path.dirname(file), { recursive: true });
156
+ fs.writeFileSync(file, JSON.stringify(ctx, null, 2));
157
+ });
158
+ }
159
+ /** For tests only: called with relay's build directory after it is made and before the file is written. */
160
+ export const contextWriteHooks = {};
161
+ /**
162
+ * Writes a job's identity file into its worktree, which the job's agent can write. Relay writes it
163
+ * outside any sandbox, so nothing the agent left there may steer the write. The file is built in a
164
+ * fresh directory relay makes beside the worktree, in the worktree's parent (relay's own run
165
+ * directory, which no agent can write, on the same filesystem), so nothing the agent does can reach
166
+ * it between its creation and the write. It is then renamed onto `.relay`: rename replaces whatever
167
+ * name is there (a stale directory removed first; a symlink or file overwritten, never followed),
168
+ * so no write goes through a link the agent put there, and nothing is left in the tree. Anything that
169
+ * stops relay's directory landing there (a non-empty directory reappearing, say) makes this throw.
170
+ */
171
+ export function writeWorktreeContext(worktree, ctx) {
172
+ const dir = path.join(worktree, CONTEXT_DIR);
173
+ const build = path.join(path.dirname(worktree), `.${path.basename(worktree)}${CONTEXT_DIR}.${crypto.randomBytes(8).toString("hex")}`);
174
+ // mkdirSync (no recursive) fails if the name is taken; the name is random, so it is relay's own.
175
+ fs.mkdirSync(build, { mode: 0o700 });
176
+ try {
177
+ contextWriteHooks.afterBuildDir?.(build);
178
+ fs.writeFileSync(path.join(build, CONTEXT_FILE), JSON.stringify(ctx, null, 2), { flag: "wx" });
179
+ fs.rmSync(dir, { recursive: true, force: true });
180
+ fs.renameSync(build, dir);
181
+ }
182
+ catch (err) {
183
+ fs.rmSync(build, { recursive: true, force: true });
184
+ throw err;
185
+ }
186
+ }