@jbkjr/relay 0.0.0-stage → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +393 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1539 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +345 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +641 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +345 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +635 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1518 -0
  186. package/docs/pinned-codex.md +333 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
package/dist/cli.js ADDED
@@ -0,0 +1,344 @@
1
+ #!/usr/bin/env node
2
+ // Each command loads what it uses when it runs, by a literal specifier: a worker, the MCP server,
3
+ // a confined agent's bridge and --version start without the registry, the views, install or
4
+ // doctor, unless they use them. A module that fails to load fails its command, as main's catch
5
+ // reports any other error.
6
+ import fs from "node:fs";
7
+ import readline from "node:readline";
8
+ import { relayVersion, usageError } from "./install/basics.js";
9
+ import { HOST_IDS } from "./hosts/types.js";
10
+ async function usage() {
11
+ const { TARGETS, targetLabel } = await import("./targets/index.js");
12
+ return `relay — delegation, consultation, discussion and review across families of coding agent
13
+ (targets: ${TARGETS.map((t) => targetLabel(t, t.id)).join(", ")}; hosts: ${HOST_IDS.join(", ")})
14
+
15
+ relay mcp [--host <target>] [--desktop] [--context <file>]
16
+ run the stdio MCP server (hosts start this, as install
17
+ registers it): --host names the family of the host's
18
+ sessions, --desktop marks the Claude desktop app's shared entry
19
+ relay bridge <socket> a confined agent's MCP server: forwards stdio to its turn's socket
20
+ relay gemini-tools <dir> --list|<tool>
21
+ a confined Gemini agent's relay tools, through its tool discovery
22
+ relay tree [run_id] [--watch] jobs, threads, discussions and reviews as one tree
23
+ relay chat <discussion_id> tail a discussion; type a line to send it to both participants
24
+ [--say "message"] [--print] one-shot forms: inject a message / print the transcript and exit
25
+ relay approvals approval requests waiting for a decision
26
+ relay adopt <id> --to <fingerprint> explicitly authorize takeover by the connection named in status
27
+ relay approve <request_id> [--job] [note] let a launched agent do what it asked: needs an
28
+ interactive terminal and a one-time code you type back, and
29
+ refuses inside relay-launched process trees it can detect (not a
30
+ security boundary; see README). --job: for the rest of that job.
31
+ Not a request marked person_only, which only you can allow in your session
32
+ relay deny <request_id> [reason] refuse it (from anywhere)
33
+ relay cancel <id | run_id> cancel an item and everything under it, or a whole run
34
+ relay clean [run_id] remove finished runs' worktrees and merged relay/* branches
35
+ (all finished runs if no id; unmerged branches are kept),
36
+ relay's leftover temporary directories, and, if
37
+ keep_records_days is set, records of runs with no
38
+ activity for that many days
39
+ relay clean --forget <run_id> [--write]
40
+ forget a finished run kept because its repository is gone:
41
+ its records and relay's own files for it; prints what it
42
+ would do, and changes nothing without --write
43
+ relay install <${HOST_IDS.join("|")}> [--write] [--force] [--no-link]
44
+ register relay with a host; prints what it would do, and
45
+ changes nothing without --write
46
+ relay uninstall <${HOST_IDS.join("|")}> [--write] [--force] [--remove-link]
47
+ take relay's own entries out of a host again
48
+ relay doctor check this machine against what relay needs
49
+ relay qualify-codex [--version X.Y.Z] [--force]
50
+ qualify a Codex release and make it the pin relay runs
51
+ (relay refuses Codex without one), from your desktop
52
+ login; it takes about an hour and a half. Without
53
+ --version, npm's latest. A release that ships a pin needs
54
+ this only for other versions: install codex puts it in place
55
+ relay qualify-codex --shipped switch to this release's shipped pin from one qualified here
56
+ relay --version
57
+ `;
58
+ }
59
+ async function tree(args) {
60
+ const { ACTIVE, getRun, latestRun, runNodes, sleep } = await import("./core/db.js");
61
+ const { renderTree } = await import("./core/views.js");
62
+ const watch = args.includes("--watch");
63
+ const id = args.find((a) => !a.startsWith("--")) ?? latestRun()?.id;
64
+ if (!id || !getRun(id))
65
+ return void console.log(id ? `unknown run ${id}` : "no runs yet");
66
+ if (!watch)
67
+ return void console.log(renderTree(id));
68
+ for (;;) {
69
+ process.stdout.write("\x1b[2J\x1b[H" + renderTree(id) + "\n");
70
+ if (!runNodes(id).some((n) => ACTIVE.includes(n.status)))
71
+ return;
72
+ await sleep(1000);
73
+ }
74
+ }
75
+ async function chat(args) {
76
+ const { getNode, sleep } = await import("./core/db.js");
77
+ const { inject } = await import("./core/ops.js");
78
+ const id = args.find((a) => !a.startsWith("--"));
79
+ const found = id ? getNode(id) : undefined;
80
+ if (!found || found.kind !== "discussion" || !found.transcript_path) {
81
+ console.error(`${id ?? "(no id)"} is not a discussion`);
82
+ process.exitCode = 1;
83
+ return;
84
+ }
85
+ const node = found;
86
+ const file = found.transcript_path;
87
+ // --print only reads the transcript, so it runs anywhere. Both ways of injecting a message —
88
+ // --say and typing a line interactively — speak as the person to both agents, so they refuse
89
+ // inside a launched agent's tree (no TTY or code: a message is not an approval). C4/X2.
90
+ const sayIdx = args.indexOf("--say");
91
+ if (sayIdx >= 0) {
92
+ if (await launchedAgentTerminal("chat --say"))
93
+ return;
94
+ return void console.log(JSON.stringify(inject(node.id, args[sayIdx + 1] ?? ""), null, 2));
95
+ }
96
+ if (args.includes("--print"))
97
+ return void console.log(fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "(no transcript yet)");
98
+ if (await launchedAgentTerminal("chat"))
99
+ return;
100
+ let offset = 0;
101
+ const flush = () => {
102
+ if (!fs.existsSync(file))
103
+ return;
104
+ const size = fs.statSync(file).size;
105
+ if (size <= offset)
106
+ return;
107
+ const fd = fs.openSync(file, "r");
108
+ const buf = Buffer.alloc(size - offset);
109
+ fs.readSync(fd, buf, 0, buf.length, offset);
110
+ fs.closeSync(fd);
111
+ offset = size;
112
+ process.stdout.write(buf.toString());
113
+ };
114
+ const rl = readline.createInterface({ input: process.stdin });
115
+ rl.on("line", (line) => {
116
+ if (!line.trim())
117
+ return;
118
+ const r = inject(node.id, line.trim());
119
+ console.log(r.error ? `(not sent: ${r.error})` : "(sent: the other agent sees it on its next turn, the calling agent on its next call)");
120
+ });
121
+ for (;;) {
122
+ flush();
123
+ if (getNode(node.id).status !== "open") {
124
+ await sleep(300);
125
+ flush();
126
+ rl.close();
127
+ return;
128
+ }
129
+ await sleep(500);
130
+ }
131
+ }
132
+ async function clean(args) {
133
+ // Any spelling of --forget is the forget, which refuses the ones it does not take: a slip must
134
+ // not turn one run's preview into a clean of every run.
135
+ if (args.some((a) => a.startsWith("--forget")))
136
+ return forget(args);
137
+ const ids = args.filter((a) => !a.startsWith("-"));
138
+ if (ids.length > 1 || ids.length < args.length)
139
+ return usageError("usage: relay clean [run_id]\n relay clean --forget <run_id> [--write]");
140
+ const { clean: cleanRuns } = await import("./core/ops.js");
141
+ console.log(JSON.stringify(await cleanRuns(ids[0]), null, 2));
142
+ }
143
+ /** relay clean --forget <run_id> [--write]: the person's own say that a run's repository is gone for good. */
144
+ async function forget(args) {
145
+ if (await launchedAgentTerminal("clean --forget"))
146
+ return;
147
+ const ids = args.filter((a) => !a.startsWith("-"));
148
+ if (ids.length !== 1 || args.some((a) => a.startsWith("-") && a !== "--forget" && a !== "--write")) {
149
+ return usageError("usage: relay clean --forget <run_id> [--write]");
150
+ }
151
+ const { forgetRun } = await import("./core/retention.js");
152
+ const r = forgetRun(ids[0], { write: args.includes("--write") });
153
+ console.log(JSON.stringify(r, null, 2));
154
+ if (r.error || r.refused)
155
+ process.exitCode = 1;
156
+ }
157
+ /** Refuses (usage error) when this command runs in a launched agent's environment or process tree (core/presence.ts). */
158
+ async function launchedAgentTerminal(command) {
159
+ const { launchedTree } = await import("./core/presence.js");
160
+ const why = launchedTree();
161
+ if (!why)
162
+ return false;
163
+ usageError(`relay ${command} cannot run in a launched agent's environment. Run it from the person's own terminal. (${why[0].toUpperCase()}${why.slice(1)}.)`);
164
+ return true;
165
+ }
166
+ /**
167
+ * relay approve: allowed only for a person at an interactive terminal who types back a code relay
168
+ * prints for this one request, outside every launched agent's process tree (docs/approve-boundary.md).
169
+ */
170
+ /** Prints a command's JSON result; one that is an error (unknown id, already decided, …) exits 1. */
171
+ function printResult(result) {
172
+ if (result && typeof result === "object" && "error" in result)
173
+ process.exitCode = 1;
174
+ console.log(JSON.stringify(result, null, 2));
175
+ }
176
+ async function approveAtTerminal(args) {
177
+ if (await launchedAgentTerminal("approve"))
178
+ return;
179
+ if (!args[0])
180
+ return usageError("usage: relay approve <request_id> [--job] [note]");
181
+ const { decide, getRequest, requestUnchanged, requestView } = await import("./core/approvals.js");
182
+ const { commandRefusal } = await import("./core/extensions.js");
183
+ const { personTypesCode, terminalProblem } = await import("./core/presence.js");
184
+ const { escalationDecisionAuthentication } = await import("./core/escalation-authority.js");
185
+ const id = args[0];
186
+ const refuse = (reason) => { process.exitCode = 1; console.log(JSON.stringify({ refused: true, reason }, null, 2)); };
187
+ const r = getRequest(id);
188
+ if (!r)
189
+ return printResult({ error: `unknown request ${id}` });
190
+ // A request only the person may allow (docs/extensions.md) is never allowed by a command. It can be denied from here.
191
+ const personal = commandRefusal(r);
192
+ if (personal)
193
+ return refuse(personal);
194
+ if (r.status !== "pending")
195
+ return printResult({ error: `request ${id} is already ${r.status}` });
196
+ const tty = terminalProblem();
197
+ if (tty) {
198
+ return refuse(`relay approve allows a request only for a person at an interactive terminal, and ${tty}. ` +
199
+ `Run relay approve ${id} in your own terminal and type the code it shows. relay deny ${id} works from anywhere.`);
200
+ }
201
+ const scope = args.includes("--job") ? "job" : "once";
202
+ const view = requestView(r);
203
+ const review = [
204
+ `Request ${id} from ${r.node_id}`,
205
+ ` kind: ${JSON.stringify(view.kind)}`,
206
+ ` effect: ${JSON.stringify(view.effect)}`,
207
+ ` in directory: ${JSON.stringify(view.in_directory)}`,
208
+ ` wants: ${JSON.stringify(r.summary)}`,
209
+ ` allowing it: ${scope === "job" ? "for the rest of that job" : "this once"}`,
210
+ ];
211
+ if (!(await personTypesCode(id, review)))
212
+ return refuse(`the code was not typed back, so ${id} was not allowed; it is still pending.`);
213
+ // What was shown is what is allowed: the request must still be the same pending request.
214
+ const now = getRequest(id);
215
+ if (!requestUnchanged(r, now)) {
216
+ return printResult({ error: `request ${id} changed or was decided while you were asked (${now?.status ?? "gone"}); nothing was allowed` });
217
+ }
218
+ const rest = args.slice(1).filter((a) => a !== "--job");
219
+ printResult(decide(id, true, "terminal", rest.join(" ") || undefined, scope, escalationDecisionAuthentication(r, "person-terminal")));
220
+ }
221
+ async function main() {
222
+ const [cmd, ...args] = process.argv.slice(2);
223
+ switch (cmd) {
224
+ case "mcp": {
225
+ // What the host profile reads of ps is asked first, so that those processes run while the server's modules load.
226
+ const { startEvidence } = await import("./mcp/host.js");
227
+ const evidence = startEvidence(args, process.env);
228
+ const { serve } = await import("./mcp/server.js");
229
+ return serve(args, evidence);
230
+ }
231
+ case "bridge": {
232
+ // Runs inside a confined agent's sandbox, where the registry is unreadable; it never opens it.
233
+ if (!args[0])
234
+ return usageError("usage: relay bridge <socket>");
235
+ const { bridge } = await import("./confine/bridge.js");
236
+ return bridge(args[0]);
237
+ }
238
+ case "gemini-tools": {
239
+ // Runs inside a confined Gemini agent's sandbox, as Gemini's tool discovery runs it (backends/gemini.ts geminiTools).
240
+ const { geminiTools } = await import("./confine/gemini-tools.js");
241
+ process.exitCode = await geminiTools(args[0], args.slice(1));
242
+ return;
243
+ }
244
+ case "worker": {
245
+ const { runWorker } = await import("./worker.js");
246
+ return runWorker(args[0]);
247
+ }
248
+ case "tree":
249
+ return tree(args);
250
+ case "chat":
251
+ return chat(args);
252
+ case "cancel": {
253
+ if (await launchedAgentTerminal(cmd))
254
+ return;
255
+ if (!args[0])
256
+ return usageError("usage: relay cancel <id | run_id>");
257
+ const { cancel } = await import("./core/ops.js");
258
+ return printResult(await cancel(null, { id: args[0] }));
259
+ }
260
+ case "clean":
261
+ return clean(args);
262
+ case "approvals": {
263
+ const { pendingRequests, requestView } = await import("./core/approvals.js");
264
+ const open = pendingRequests();
265
+ return void console.log(open.length ? JSON.stringify(open.map(requestView), null, 2) : "no approval requests waiting");
266
+ }
267
+ case "adopt": {
268
+ if (await launchedAgentTerminal(cmd))
269
+ return;
270
+ if (!process.stdin.isTTY)
271
+ return usageError("Adoption requires an interactive terminal (TTY); piped stdin cannot authorize a transfer.");
272
+ const id = args[0], to = args[args.indexOf("--to") + 1];
273
+ if (!id || !args.includes("--to") || !/^[0-9a-f]{24}$/.test(to ?? ""))
274
+ return usageError("usage: relay adopt <id> --to <status-session-fingerprint>");
275
+ const { adoptionRun, authorizeAdoption } = await import("./core/adoption.js");
276
+ const { pendingRequests, requestView } = await import("./core/approvals.js");
277
+ const { unseenEvents } = await import("./core/events.js");
278
+ const { renderTree } = await import("./core/views.js");
279
+ const run = adoptionRun(id);
280
+ if (!run)
281
+ return usageError("Item unavailable.");
282
+ const runId = run.id;
283
+ console.log(`Take over run ${runId} into connection ${to}: all its jobs, approval requests and events, with supervision rights. Pending events will be delivered there. The old owner must have exited.`);
284
+ console.log(`Directory: ${JSON.stringify(run.root_cwd)}`);
285
+ console.log(`Items: ${JSON.stringify(renderTree(runId))}`);
286
+ console.log(`Pending approvals: ${JSON.stringify(pendingRequests(runId).map(requestView))}`);
287
+ console.log(`Pending events: ${JSON.stringify(unseenEvents([runId]).map((e) => ({ event_id: e.id, kind: e.kind, item: e.item_id })))}`);
288
+ const exact = `adopt ${runId} into ${to}`;
289
+ console.log(`Type exactly ${JSON.stringify(exact)} to authorize this transfer:`);
290
+ const input = readline.createInterface({ input: process.stdin });
291
+ let answer = "";
292
+ for await (const line of input) {
293
+ answer = line;
294
+ input.close();
295
+ break;
296
+ }
297
+ if (answer !== exact)
298
+ return usageError("Transfer not confirmed; no authority changed.");
299
+ const result = authorizeAdoption(runId, to);
300
+ console.log(JSON.stringify(result, null, 2));
301
+ if (!result.authorized)
302
+ process.exitCode = 1;
303
+ return;
304
+ }
305
+ case "approve":
306
+ return approveAtTerminal(args);
307
+ case "deny": {
308
+ // Denying needs no person: it only ever narrows what an agent may do.
309
+ if (!args[0])
310
+ return usageError("usage: relay deny <request_id> [reason]");
311
+ const rest = args.slice(1).filter((a) => a !== "--job");
312
+ const { decide, getRequest } = await import("./core/approvals.js");
313
+ const { escalationDecisionAuthentication } = await import("./core/escalation-authority.js");
314
+ const request = getRequest(args[0]);
315
+ return printResult(decide(args[0], false, "terminal", rest.join(" ") || undefined, args.includes("--job") ? "job" : "once", request ? escalationDecisionAuthentication(request, "terminal-deny") : undefined));
316
+ }
317
+ case "install":
318
+ return (await import("./install.js")).install(args);
319
+ case "uninstall":
320
+ return (await import("./install.js")).uninstall(args);
321
+ case "doctor":
322
+ return (await import("./install/doctor.js")).doctor();
323
+ case "qualify-codex":
324
+ process.exitCode = await (await import("./install/qualify-codex.js")).qualifyCodex(args);
325
+ return;
326
+ case "--version":
327
+ case "-v":
328
+ case "version":
329
+ return void console.log(`relay ${relayVersion()}`);
330
+ case "help":
331
+ case "--help":
332
+ case "-h":
333
+ return void console.log(await usage());
334
+ default:
335
+ // No command, or one relay does not have, is a mistake in how it was called.
336
+ return usageError(`${cmd ? `relay: unknown command ${cmd}\n\n` : ""}${await usage()}`);
337
+ }
338
+ }
339
+ // A config typo or another error relay reports in words is a message, not a stack trace;
340
+ // RELAY_DEBUG=1 shows the stack, for a bug report.
341
+ main().catch((err) => {
342
+ console.error(err instanceof Error ? (process.env.RELAY_DEBUG ? err.stack : `relay: ${err.message}`) : err);
343
+ process.exit(1);
344
+ });
@@ -0,0 +1,113 @@
1
+ import net from "node:net";
2
+ /**
3
+ * `relay bridge <socket>`: the MCP server a confined agent is given. It forwards newline-delimited
4
+ * JSON-RPC between its stdio and the turn's broker socket and holds nothing else: no registry, no
5
+ * context, no environment. It runs inside the agent's sandbox, whose profile allows that one socket.
6
+ *
7
+ * When the broker cannot be reached (the turn has ended, or the socket was never there), every
8
+ * request, including those already sent and not yet answered, gets a JSON-RPC error at once, so
9
+ * the agent is told rather than left waiting. Its only environment is the turn's secret, which it
10
+ * presents first. Deliberately free of imports beyond node:net.
11
+ */
12
+ /** JSON-RPC error code for "relay is not reachable from here". */
13
+ export const UNREACHABLE = -32002;
14
+ function requestId(line) {
15
+ try {
16
+ const m = JSON.parse(line);
17
+ return m && typeof m === "object" && typeof m.method === "string" && (typeof m.id === "string" || typeof m.id === "number") ? m.id : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ function responseId(line) {
24
+ try {
25
+ const m = JSON.parse(line);
26
+ return m && typeof m === "object" && m.method === undefined && (typeof m.id === "string" || typeof m.id === "number") ? m.id : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ /** Splits a stream into lines, calling `each` for every complete one. */
33
+ function lines(stream, each) {
34
+ let buf = "";
35
+ stream.setEncoding("utf8");
36
+ stream.on("data", (chunk) => {
37
+ buf += chunk;
38
+ for (let i = buf.indexOf("\n"); i >= 0; i = buf.indexOf("\n")) {
39
+ const line = buf.slice(0, i).replace(/\r$/, "");
40
+ buf = buf.slice(i + 1);
41
+ if (line)
42
+ each(line);
43
+ }
44
+ });
45
+ }
46
+ /**
47
+ * `secret`: the turn's bridge secret, from the environment the harness started the bridge with
48
+ * (RELAY_BRIDGE_SECRET, broker.ts); sent as the connection's first line, before anything of the
49
+ * agent's, since the broker serves nothing until it has it.
50
+ */
51
+ export function bridge(socketPath, input = process.stdin, output = process.stdout, secret = process.env.RELAY_BRIDGE_SECRET ?? "") {
52
+ return new Promise((resolve) => {
53
+ output.on("error", () => { });
54
+ let connected = false;
55
+ let down = null;
56
+ let inputEnded = false;
57
+ const waiting = [];
58
+ const pending = new Set();
59
+ const refuse = (id) => output.write(JSON.stringify({ jsonrpc: "2.0", id, error: { code: UNREACHABLE, message: `relay is not reachable from this agent: ${down}. Continue without relay.` } }) + "\n");
60
+ const sock = net.connect(socketPath);
61
+ const lost = (reason) => {
62
+ if (down)
63
+ return;
64
+ down = reason;
65
+ connected = false;
66
+ for (const id of pending)
67
+ refuse(id);
68
+ pending.clear();
69
+ for (const line of waiting.splice(0))
70
+ toRelay(line);
71
+ if (inputEnded)
72
+ resolve();
73
+ };
74
+ const toRelay = (line) => {
75
+ const id = requestId(line);
76
+ if (down) {
77
+ if (id !== null)
78
+ refuse(id);
79
+ return;
80
+ }
81
+ if (!connected)
82
+ return void waiting.push(line);
83
+ if (id !== null)
84
+ pending.add(id);
85
+ sock.write(line + "\n");
86
+ };
87
+ sock.on("connect", () => {
88
+ sock.write(JSON.stringify({ relay_bridge_secret: secret }) + "\n");
89
+ connected = true;
90
+ for (const line of waiting.splice(0))
91
+ toRelay(line);
92
+ if (inputEnded)
93
+ sock.end();
94
+ });
95
+ lines(sock, (line) => {
96
+ const id = responseId(line);
97
+ if (id !== null)
98
+ pending.delete(id);
99
+ output.write(line + "\n");
100
+ });
101
+ sock.on("error", (err) => lost(`the turn it was started for has ended, or its connection could not be opened (${err.code ?? err.message})`));
102
+ // The bridge stays up after that, answering with errors, until the agent closes its side.
103
+ sock.on("close", () => lost("relay closed the connection; the turn this agent was started for has ended"));
104
+ lines(input, toRelay);
105
+ input.on("end", () => {
106
+ inputEnded = true;
107
+ if (down)
108
+ return resolve();
109
+ if (connected)
110
+ sock.end();
111
+ });
112
+ });
113
+ }
@@ -0,0 +1,76 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
3
+ import { newInstance } from "../core/caller.js";
4
+ import { ancestors, getNode, getRun, getTurn, workCwd } from "../core/db.js";
5
+ import { relayServer } from "../mcp/server.js";
6
+ import { overlayTurnProblem } from "../core/restart-overlay.js";
7
+ import { escalationTurnClosing } from "../core/escalations.js";
8
+ export const TURN_ENDED = -32001;
9
+ /** As on the stdio front, one message is bounded to 8 MiB. */
10
+ export const MAX_MESSAGE = 8 * 1024 * 1024;
11
+ export function turnRefusal(turn) {
12
+ const t = getTurn(turn.turnId);
13
+ if (!t || t.node_id !== turn.nodeId)
14
+ return "this agent's turn is not in the relay registry.";
15
+ if (t.status !== "running")
16
+ return `the relay turn this agent was started for has ended (${t.status}). Continue without relay.`;
17
+ if (escalationTurnClosing(turn.nodeId, turn.turnId))
18
+ return "this turn is closing for an approved escalation; no further work is admitted.";
19
+ const node = getNode(turn.nodeId);
20
+ if (!node || getRun(node.run_id)?.status === "cancelled")
21
+ return "this agent's run has been cancelled.";
22
+ if (ancestors(node, { self: true }).some((n) => n.status === "cancelled"))
23
+ return "this agent's work has been cancelled.";
24
+ return overlayTurnProblem(turn.nodeId, turn.turnId);
25
+ }
26
+ /** Authority comes from the registry, never a context supplied over the connection. */
27
+ export function turnContext(turn) {
28
+ const t = getTurn(turn.turnId);
29
+ const node = getNode(turn.nodeId);
30
+ if (!t || !node || t.node_id !== node.id)
31
+ throw new Error(`turn ${turn.turnId} of ${turn.nodeId} is not in the registry`);
32
+ if (t.access !== "read" && t.access !== "write")
33
+ throw new Error(`turn ${turn.turnId} has no access mode`);
34
+ return {
35
+ kind: "child", runId: node.run_id, nodeId: node.id, depth: node.depth,
36
+ turnId: t.id, access: t.access, mayDelegate: turn.mayDelegate, mayAsk: turn.mayAsk, cwd: workCwd(node),
37
+ };
38
+ }
39
+ /** Same MCP server, fresh owner token per Unix connection or HTTP MCP session. */
40
+ export function brokerCore(turn, opts = {}) {
41
+ const { cwd, ...ctx } = turnContext(turn);
42
+ const refusal = () => turnRefusal(turn);
43
+ const why = refusal();
44
+ if (why)
45
+ throw new Error(`no broker for a turn that is not live: ${why}`);
46
+ const serve = () => relayServer(newInstance(ctx, cwd), opts);
47
+ return {
48
+ refusal, serve,
49
+ async listTools() {
50
+ const why = refusal();
51
+ if (why)
52
+ throw new Error(`relay cannot list this turn's tools: ${why}`);
53
+ const [near, far] = InMemoryTransport.createLinkedPair();
54
+ const mcp = serve();
55
+ const client = new Client({ name: "relay-tool-list", version: "1" });
56
+ try {
57
+ await mcp.connect(far);
58
+ await client.connect(near);
59
+ if (!client.getServerCapabilities()?.tools)
60
+ return [];
61
+ const tools = [];
62
+ let cursor;
63
+ do {
64
+ const page = await client.listTools(cursor ? { cursor } : {});
65
+ tools.push(...page.tools);
66
+ cursor = page.nextCursor;
67
+ } while (cursor);
68
+ return tools;
69
+ }
70
+ finally {
71
+ await client.close().catch(() => { });
72
+ await mcp.close().catch(() => { });
73
+ }
74
+ },
75
+ };
76
+ }