@jbkjr/relay 0.0.0-stage → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +393 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1539 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +345 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +641 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +345 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +635 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1518 -0
  186. package/docs/pinned-codex.md +333 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
@@ -0,0 +1,546 @@
1
+ // Processes: telling a process relay recorded from one that got its number since (pid and start
2
+ // time), finding what an agent started (by parentage, while it runs), and stopping it all. Nothing
3
+ // here reads relay's registry: what to spare, relay's own servers and workers, is passed in
4
+ // (db.ts relayProcs), and read at each look.
5
+ import { execFile, spawnSync } from "node:child_process";
6
+ const now = () => Date.now();
7
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
8
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
9
+ /**
10
+ * Waits until `gone` holds or `ms` have passed. It looks often at first and then every `most` ms: a
11
+ * process just killed is gone within a millisecond or two, once its parent has reaped it (a zombie
12
+ * still counts as alive, and Node reaps its own children only while its event loop runs), so a fixed
13
+ * interval would mostly measure itself.
14
+ */
15
+ async function waitGone(gone, ms, most = 50) {
16
+ const deadline = now() + ms;
17
+ for (let step = 1; !gone() && now() < deadline; step = Math.min(step * 2, most))
18
+ await sleep(step);
19
+ }
20
+ export function pidAlive(pid) {
21
+ if (!pid || pid <= 0)
22
+ return false;
23
+ try {
24
+ process.kill(pid, 0);
25
+ return true;
26
+ }
27
+ catch (err) {
28
+ return err.code === "EPERM";
29
+ }
30
+ }
31
+ /**
32
+ * The process groups that hold this process or one of the processes that started it, read fresh.
33
+ * An agent's MCP server can itself be below an agent being reaped. Such a target needs a recorded,
34
+ * freshly checked leader identity. Empty when ps cannot be read (reported, but best effort).
35
+ */
36
+ let warnedAncestorRead = false;
37
+ function ancestorGroups() {
38
+ const r = ps(["-axo", "pid=,ppid=,pgid="]);
39
+ const rows = new Map();
40
+ for (const line of r.status === 0 ? r.stdout.split("\n") : []) {
41
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)/.exec(line);
42
+ if (m)
43
+ rows.set(Number(m[1]), { ppid: Number(m[2]), pgid: Number(m[3]) });
44
+ }
45
+ if ((r.error || r.status !== 0 || !rows.has(process.pid)) && !warnedAncestorRead) {
46
+ warnedAncestorRead = true;
47
+ process.stderr.write(`relay could not read process ancestry for group-signal guard; continuing without ancestry protection: ${r.error?.message ?? (r.stderr?.trim() || `ps status ${r.status}, missing current process`)}\n`);
48
+ }
49
+ const groups = new Set();
50
+ for (let pid = process.pid, i = 0; pid > 1 && i < 64; i++) {
51
+ const row = rows.get(pid);
52
+ if (!row)
53
+ break;
54
+ groups.add(row.pgid);
55
+ pid = row.ppid;
56
+ }
57
+ return groups;
58
+ }
59
+ /**
60
+ * A refusal is not ESRCH: callers must abandon cleanup derived from this target, including pid
61
+ * fallbacks and descendant kills. An absent group can still have detached descendants to clean.
62
+ */
63
+ export function isGroupSignalRefusal(err) {
64
+ return err?.code === "EPROTECTEDPGID";
65
+ }
66
+ /**
67
+ * Checks a target without signalling it (also used by scripts with an injected signal sender).
68
+ * The only ancestry exception is a recorded group leader's pid/start, never a boolean bypass.
69
+ * The identity must match the group and is checked fresh here, immediately before use.
70
+ */
71
+ export function assertGroupSignalAllowed(pgid, leader) {
72
+ if (!Number.isInteger(pgid) || pgid <= 1)
73
+ throw Object.assign(new Error(`relay refused invalid process group ${pgid}`), { code: "EPROTECTEDPGID" });
74
+ if (ancestorGroups().has(pgid) && !(leader?.pid === pgid && leader.start && sameProcess(pgid, leader.start, { fresh: true }))) {
75
+ const err = Object.assign(new Error(`relay refused process group ${pgid}: it holds relay (pid ${process.pid}) or a process that started it, without a verified leader`), { code: "EPROTECTEDPGID" });
76
+ process.stderr.write(`${err.stack}\n`);
77
+ throw err;
78
+ }
79
+ }
80
+ /** Every group signal goes through the guard; see assertGroupSignalAllowed for the narrow exception. */
81
+ export function sendGroupSignal(pgid, sig, leader) {
82
+ assertGroupSignalAllowed(pgid, leader);
83
+ process.kill(-pgid, sig);
84
+ }
85
+ const startCache = new Map();
86
+ /**
87
+ * Runs ps in the C locale. Relay identifies a process by its pid and start time, and reads the
88
+ * start time as five fields; in other locales ps prints it differently (four fields in Japanese,
89
+ * seven in Korean), and nothing would match.
90
+ */
91
+ function ps(args) {
92
+ // By its full path: a "ps" earlier on PATH is not asked how relay's host was started.
93
+ return spawnSync("/bin/ps", args, psOptions());
94
+ }
95
+ const psOptions = () => ({ encoding: "utf8", maxBuffer: 32 * 1024 * 1024, env: { ...process.env, LC_ALL: "C", LANG: "C" } });
96
+ /** ps without blocking: its exit status (null where it did not run to an exit) and output, as ps() gives them. */
97
+ function psLater(args) {
98
+ return new Promise((resolve) => {
99
+ execFile("/bin/ps", args, psOptions(), (err, stdout) => {
100
+ const code = err?.code;
101
+ resolve({ status: err ? (typeof code === "number" ? code : null) : 0, stdout: String(stdout ?? "") });
102
+ });
103
+ });
104
+ }
105
+ /**
106
+ * The command lines of the processes that started this one, its parent first, up to `levels` of
107
+ * them. Read only to tell how the host was started (src/mcp/host.ts). Null where ps cannot say for
108
+ * a process that is there, so that what relay could not inspect is not taken for a plain start.
109
+ */
110
+ export function ancestorCommandLines(levels) {
111
+ const out = [];
112
+ let pid = process.ppid;
113
+ for (let i = 0; i < levels && pid > 1; i++) {
114
+ const m = ancestorRow(ps(ancestorArgs(pid)));
115
+ if (!m)
116
+ return null;
117
+ out.push(m[2]);
118
+ pid = Number(m[1]);
119
+ }
120
+ return out;
121
+ }
122
+ /**
123
+ * ancestorCommandLines without blocking, the same ps for each process and the same answer, so that
124
+ * a server can ask while its modules load. Each ps waits for the one before (it names the next pid),
125
+ * and its answer is taken only when the process's event loop next runs.
126
+ */
127
+ export async function ancestorCommandLinesLater(levels) {
128
+ const out = [];
129
+ let pid = process.ppid;
130
+ for (let i = 0; i < levels && pid > 1; i++) {
131
+ const m = ancestorRow(await psLater(ancestorArgs(pid)));
132
+ if (!m)
133
+ return null;
134
+ out.push(m[2]);
135
+ pid = Number(m[1]);
136
+ }
137
+ return out;
138
+ }
139
+ const ancestorArgs = (pid) => ["-ww", "-o", "ppid=,args=", "-p", String(pid)];
140
+ /** A process's parent pid and command line from ps's answer for it; null where ps could not say. */
141
+ const ancestorRow = (r) => /^\s*(\d+)\s+([\s\S]*)$/.exec(r.status === 0 ? r.stdout.trim() : "");
142
+ /**
143
+ * When a process started, as reported by ps. Stored next to every pid relay records, so that a
144
+ * number the system has since given to another process is never mistaken for the original.
145
+ */
146
+ export function procStart(pid, opts = {}) {
147
+ if (!pid || pid <= 1)
148
+ return null;
149
+ const hit = startCache.get(pid);
150
+ if (!opts.fresh && hit && now() - hit.at < 2000)
151
+ return hit.start;
152
+ const r = ps(["-o", "lstart=", "-p", String(pid)]);
153
+ const start = r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
154
+ startCache.set(pid, { at: now(), start });
155
+ return start;
156
+ }
157
+ /** True when the pid is alive and is still the process relay recorded (same start time, where one was recorded). */
158
+ export function sameProcess(pid, start, opts = {}) {
159
+ if (!pidAlive(pid))
160
+ return false;
161
+ return start ? sameStart(procStart(pid, opts) ?? "", start) : true;
162
+ }
163
+ /**
164
+ * True only when the process relay recorded is known to be gone: its pid is not alive, or ps says a
165
+ * process that started at another time has it now. Where ps cannot read the start time at the
166
+ * moment (a fork that fails on a loaded machine), it is not known to be gone, unlike sameProcess,
167
+ * for which a process that cannot be vouched for is not the one recorded.
168
+ */
169
+ export function processGone(pid, start) {
170
+ if (!pidAlive(pid))
171
+ return true;
172
+ const now_ = start ? procStart(pid) : null;
173
+ return now_ !== null && !sameStart(now_, start);
174
+ }
175
+ const sameStart = (a, b) => a.replace(/\s+/g, " ") === b.replace(/\s+/g, " ");
176
+ /** True while any process remains in the group. Children can outlive the leader. */
177
+ export function groupAlive(pgid) {
178
+ if (!pgid || pgid <= 1)
179
+ return false;
180
+ try {
181
+ process.kill(-pgid, 0);
182
+ return true;
183
+ }
184
+ catch (err) {
185
+ return err.code === "EPERM";
186
+ }
187
+ }
188
+ /**
189
+ * Authentication, rather than best-effort cleanup: both endpoints must have known, fresh start
190
+ * times. Walk a single process-table snapshot, then recheck every identity on the chain. Never
191
+ * use the start-time cache here, nor procTree's command-line heuristic for sparing relay workers.
192
+ * A missing/dead/reused harness or peer, a zombie, or an unreadable table refuses the connection.
193
+ */
194
+ export function inProcessTree(root, peer) {
195
+ if (!root.start || !peer.start || !sameProcess(root.pid, root.start, { fresh: true }) || !sameProcess(peer.pid, peer.start, { fresh: true }))
196
+ return false;
197
+ const r = ps(["-axo", "pid=,ppid=,stat=,lstart="]);
198
+ if (r.status !== 0)
199
+ return false;
200
+ const table = new Map();
201
+ for (const line of r.stdout.split("\n")) {
202
+ const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
203
+ if (m)
204
+ table.set(Number(m[1]), { pid: Number(m[1]), parent: Number(m[2]), zombie: m[3].startsWith("Z"), start: m[4].replace(/\s+/g, " ") });
205
+ }
206
+ const chain = [];
207
+ const seen = new Set();
208
+ let pid = peer.pid;
209
+ while (pid > 1 && !seen.has(pid)) {
210
+ seen.add(pid);
211
+ const p = table.get(pid);
212
+ if (!p || p.zombie)
213
+ return false;
214
+ chain.push(p);
215
+ if (pid === root.pid) {
216
+ const normalized = (start) => start.replace(/\s+/g, " ");
217
+ return normalized(p.start) === normalized(root.start)
218
+ && normalized(chain[0].start) === normalized(peer.start)
219
+ && chain.every((entry) => sameProcess(entry.pid, entry.start, { fresh: true }));
220
+ }
221
+ pid = p.parent;
222
+ }
223
+ return false;
224
+ }
225
+ /**
226
+ * One look at the process table: whether the given process is alive, and everything descended
227
+ * from it, found by parentage. Relay's own servers and workers are left out: they belong to jobs
228
+ * of their own. `spared` says which they are, read at every look (db.ts relayProcs: a process
229
+ * that registers after a watch has begun is spared from the next look on; review C5). A process
230
+ * that has exited no longer has its children, so when alive is false the list says nothing about
231
+ * what it started.
232
+ *
233
+ * The table is read without command lines, which are most of ps's work over a whole table (twice
234
+ * the time with them, a thousand processes in); only the descendants not spared as registered
235
+ * have theirs read, for the command-line net. A command line counts only for the process the
236
+ * table showed (same pid, same start time), so it is never taken from a process that has since
237
+ * been given the pid. When those cannot be read, the table is read once more whole, command lines
238
+ * included. That read only adds: command lines for what the first read found, by pid and start
239
+ * time, and what the agent has started since. It takes nothing away from what the first read
240
+ * found, since a descendant let go of here can outlive the agent's group unrecorded: one that has
241
+ * been cut loose since is no longer under the agent in the second read, and one that has exited has
242
+ * no command line there, so it is kept (killProcs signals only the process it was). When that
243
+ * cannot be read either, nothing is learned, as when the first table cannot be read: relay's own
244
+ * processes may be among the descendants with only their command lines to spare them (one that
245
+ * could not read its own start time could not register), and ps failing is when that happens.
246
+ */
247
+ export function procTree(pid, spared) {
248
+ if (!pid || pid <= 1)
249
+ return { alive: false, procs: [] };
250
+ const table = processTable(pid, false);
251
+ if (!table)
252
+ return { alive: false, procs: [] };
253
+ const own = registered(spared());
254
+ const unregistered = descendants(pid, table.kids, own);
255
+ if (!unregistered.length)
256
+ return { alive: table.alive, procs: [] };
257
+ const commands = commandLines(unregistered);
258
+ if (commands)
259
+ return { alive: table.alive, procs: descendants(pid, table.kids, (p) => own(p) || RELAY_COMMAND.test(commands.get(p.pid) ?? "")) };
260
+ const full = processTable(pid, true);
261
+ // As when the first table cannot be read: nothing learned.
262
+ if (!full)
263
+ return { alive: false, procs: [] };
264
+ // Relay's registered processes read after this table too, as `own` was after the first: one
265
+ // registered in either read is relay's.
266
+ const ownLater = registered(spared());
267
+ const ours = (p) => own(p) || ownLater(p);
268
+ const listed = new Map([...full.kids.values()].flat().map((p) => [p.pid, p]));
269
+ const relayThen = (p) => {
270
+ const l = listed.get(p.pid);
271
+ return l?.start === p.start && RELAY_COMMAND.test(l.command ?? "");
272
+ };
273
+ // What the first read found under the agent, then what the second has under it as well, each
274
+ // process once (by pid and start time).
275
+ const first = descendants(pid, table.kids, (p) => ours(p) || relayThen(p));
276
+ const since = descendants(pid, full.kids, (p) => ours(p) || RELAY_COMMAND.test(p.command ?? ""));
277
+ const found = new Map([...first, ...since].map((p) => [`${p.pid} ${p.start}`, p]));
278
+ return { alive: table.alive, procs: [...found.values()] };
279
+ }
280
+ /** Whether a process is one of relay's registered ones: the same pid with the same start time. */
281
+ const registered = (own) => (p) => own.get(p.pid) === p.start;
282
+ /** A relay server or worker, by its command line. */
283
+ const RELAY_COMMAND = /\/(cli\.js|bin\/relay) (mcp|worker)\b/;
284
+ /**
285
+ * One read of the whole process table: each process's children by parent, with their command lines
286
+ * when `commands`, and whether `pid` is alive. Null when ps cannot be read.
287
+ */
288
+ function processTable(pid, commands) {
289
+ // lstart is five fields: weekday, month, day, time, year.
290
+ const r = ps(["-axo", commands ? "pid=,ppid=,stat=,lstart=,command=" : "pid=,ppid=,stat=,lstart="]);
291
+ if (r.status !== 0)
292
+ return null;
293
+ const line = commands ? /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(.*)$/ : /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)(?:\s|$)/;
294
+ const kids = new Map();
295
+ let alive = false;
296
+ for (const l of r.stdout.split("\n")) {
297
+ const m = line.exec(l);
298
+ if (!m)
299
+ continue;
300
+ // A zombie is still listed, but its children have already been handed to launchd.
301
+ if (Number(m[1]) === pid)
302
+ alive = !m[3].startsWith("Z");
303
+ const parent = Number(m[2]);
304
+ if (!kids.has(parent))
305
+ kids.set(parent, []);
306
+ kids.get(parent).push({ pid: Number(m[1]), start: m[4].replace(/\s+/g, " "), ...(commands ? { command: m[5] } : {}) });
307
+ }
308
+ return { alive, kids };
309
+ }
310
+ /**
311
+ * The descendants of `pid` by parentage, less relay's own (`relays`) and what they started. Relay's
312
+ * own are its registered processes, matched by pid and start time, and those whose command line
313
+ * names a relay server or worker: a second net for one that has not finished registering, which
314
+ * can only cause something to be spared.
315
+ */
316
+ function descendants(pid, kids, relays) {
317
+ const procs = [];
318
+ const stack = [pid];
319
+ while (stack.length) {
320
+ for (const k of kids.get(stack.pop()) ?? []) {
321
+ if (relays(k))
322
+ continue;
323
+ procs.push({ pid: k.pid, start: k.start });
324
+ stack.push(k.pid);
325
+ }
326
+ }
327
+ return procs;
328
+ }
329
+ /**
330
+ * The command lines of these processes, by pid, of each that is still the process given (the same
331
+ * start time), or null when ps cannot be read. One that has gone, or whose pid another process has
332
+ * since taken, has none, as ps itself shows none for a process gone before it reads its arguments.
333
+ */
334
+ function commandLines(procs) {
335
+ const started = new Map(procs.map((p) => [p.pid, p.start]));
336
+ const out = new Map();
337
+ // ps reads one pid on its own in about a millisecond, but goes through the whole table for a
338
+ // list of them: a few are read one at a time.
339
+ for (const batch of procs.length <= 6 ? procs.map((p) => [p]) : [procs]) {
340
+ const r = ps(["-o", "pid=,lstart=,command=", "-p", batch.map((p) => p.pid).join(",")]);
341
+ // ps exits 1, printing nothing, when none of them is there any more.
342
+ if (r.error || (r.status !== 0 && (r.status !== 1 || r.stdout.trim())))
343
+ return null;
344
+ for (const line of r.stdout.split("\n")) {
345
+ const m = /^\s*(\d+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(.*)$/.exec(line);
346
+ if (m && started.get(Number(m[1])) === m[2].replace(/\s+/g, " "))
347
+ out.set(Number(m[1]), m[3]);
348
+ }
349
+ }
350
+ return out;
351
+ }
352
+ /** Kills each process that is still the one that was noted: same pid, same start time. */
353
+ export function killProcs(procs) {
354
+ for (const p of procs) {
355
+ const r = ps(["-o", "lstart=", "-p", String(p.pid)]);
356
+ if (r.status !== 0 || r.stdout.trim().replace(/\s+/g, " ") !== p.start)
357
+ continue;
358
+ try {
359
+ process.kill(p.pid, "SIGKILL");
360
+ }
361
+ catch {
362
+ // Already gone.
363
+ }
364
+ }
365
+ }
366
+ /**
367
+ * Keeps a record of the processes an agent starts, by looking at its descendants while it runs:
368
+ * four times a second at first, when an agent that fails tends to fail, then once a second. The
369
+ * agents put tool processes in groups or sessions of their own, so once an agent is gone this
370
+ * record is the only way to find them.
371
+ *
372
+ * It is best effort, and macOS offers nothing better without root. A process is found only while
373
+ * it is still attached to the agent, and only if a look happens then. Two things escape:
374
+ * - A process cut loose from its parent (`nohup … &` from a shell that then exits) belongs to
375
+ * launchd at once, while the agent is still running. Unless a look caught it first, it is
376
+ * never seen. Nothing can be done about this from here: ps hides the environment of system
377
+ * binaries, so such processes cannot be tagged and found afterwards either. Agents are told to
378
+ * stop what they start.
379
+ * - Whatever an agent started since the last look, if it then dies. The callers take one more
380
+ * look at the moment the agent stops starting things (its last word, or the request to stop);
381
+ * if the agent was not alive for it (it crashed, or was gone too quickly), that gap is known,
382
+ * and reported as TurnResult.unseenMs.
383
+ * So the absence of a warning is not a claim that nothing is left.
384
+ */
385
+ export function watchProcess(pid, spared) {
386
+ const seen = new Map();
387
+ const began = Date.now();
388
+ let last = began;
389
+ let timer;
390
+ const look = () => {
391
+ const at = Date.now();
392
+ const tree = procTree(pid, spared);
393
+ for (const p of tree.procs)
394
+ seen.set(p.pid, p);
395
+ if (tree.alive)
396
+ last = at;
397
+ return tree.alive;
398
+ };
399
+ const tick = () => {
400
+ look();
401
+ timer = setTimeout(tick, Date.now() - began < 5000 ? 250 : 1000);
402
+ timer.unref();
403
+ };
404
+ timer = setTimeout(tick, 150);
405
+ timer.unref();
406
+ return {
407
+ look,
408
+ procs: () => [...seen.values()],
409
+ stop: () => {
410
+ clearTimeout(timer);
411
+ return Date.now() - last;
412
+ },
413
+ };
414
+ }
415
+ /** Kills the noted processes that are still the ones noted, and returns the pids of any that would not die. */
416
+ export async function stopProcs(procs) {
417
+ killProcs(procs);
418
+ const still = () => procs.filter((p) => sameProcess(p.pid, p.start));
419
+ await waitGone(() => !still().length, 1000);
420
+ return still().map((p) => p.pid);
421
+ }
422
+ /** Kills what is left and waits briefly. False means protected: callers must skip derived cleanup. */
423
+ export async function drainGroup(pgid) {
424
+ if (!groupAlive(pgid))
425
+ return true;
426
+ try {
427
+ sendGroupSignal(pgid, "SIGKILL");
428
+ }
429
+ catch (err) {
430
+ if (isGroupSignalRefusal(err))
431
+ return false;
432
+ // Already gone.
433
+ }
434
+ await waitGone(() => !groupAlive(pgid), 2000);
435
+ return true;
436
+ }
437
+ /**
438
+ * Kills a process group at once, with everything its members started (as procTree finds it), for
439
+ * an agent with no supervisor left to stop it cleanly, and waits up to a second, without yielding,
440
+ * for the group to empty. Returns whether it did; throws EPROTECTEDPGID before derived cleanup.
441
+ */
442
+ export function killGroupNow(pgid, spared, leader) {
443
+ assertGroupSignalAllowed(pgid, leader);
444
+ const tree = procTree(pgid, spared).procs;
445
+ try {
446
+ sendGroupSignal(pgid, "SIGKILL", leader);
447
+ }
448
+ catch (err) {
449
+ if (isGroupSignalRefusal(err))
450
+ throw err;
451
+ // Already gone.
452
+ }
453
+ killProcs(tree);
454
+ for (let i = 0; i < 10 && groupAlive(pgid); i++)
455
+ pause(100);
456
+ return !groupAlive(pgid);
457
+ }
458
+ /**
459
+ * The signal phase of a cancel. `workers` and `groups` are the worker pids and agent group leaders
460
+ * to stop, each with the start time recorded for it, so that a signal goes only to the same
461
+ * process; `unsupervised` are the groups with no live worker to stop them cleanly. Returns the test
462
+ * for whether a group is still the agent's, and per-group refusals. Refused targets (and their
463
+ * supervising workers, when groupWorkers is supplied) are left alone without blocking other jobs.
464
+ */
465
+ export async function stopSupervised(o) {
466
+ const { workers, groups, groupWorkers, unsupervised, graceMs, spared } = o;
467
+ const leader = (pgid) => groups.get(pgid) ? { pid: pgid, start: groups.get(pgid) } : undefined;
468
+ const refused = new Map();
469
+ const check = (pgid) => {
470
+ if (refused.has(pgid))
471
+ return false;
472
+ try {
473
+ assertGroupSignalAllowed(pgid, leader(pgid));
474
+ return true;
475
+ }
476
+ catch (err) {
477
+ if (!isGroupSignalRefusal(err))
478
+ throw err;
479
+ refused.set(pgid, err.message);
480
+ return false;
481
+ }
482
+ };
483
+ // Check each target before asking its worker to stop or collecting a descendant tree.
484
+ for (const pgid of new Set([...groups.keys(), ...unsupervised]))
485
+ check(pgid);
486
+ const workerRefused = (pid) => [...refused.keys()].some(g => groupWorkers?.get(g) === pid);
487
+ const signal = (pid, sig) => {
488
+ try {
489
+ process.kill(pid, sig);
490
+ }
491
+ catch {
492
+ // Already gone.
493
+ }
494
+ };
495
+ // Each worker is asked to stop its own agent: it knows how to do that cleanly for its backend
496
+ // (Codex's server must be asked in-band, or the tool processes it started are left running).
497
+ // Agents with no worker are signalled directly. Whatever is left after the grace period is
498
+ // killed, along with everything it started: Codex's tool processes sit outside its process group.
499
+ // A group is still ours while its leader is the process recorded, or the leader has gone and
500
+ // members remain (a group's id is not reused while the group has members).
501
+ const stillOurs = (pgid) => refused.has(pgid) || (groupAlive(pgid) && (!pidAlive(pgid) || sameProcess(pgid, groups.get(pgid))));
502
+ const trees = new Map();
503
+ for (const pgid of groups.keys())
504
+ if (!refused.has(pgid))
505
+ trees.set(pgid, procTree(pgid, spared).procs);
506
+ for (const pid of workers.keys())
507
+ if (!workerRefused(pid))
508
+ signal(pid, "SIGTERM");
509
+ const signalG = (pgid, sig) => {
510
+ if (refused.has(pgid))
511
+ return false;
512
+ try {
513
+ sendGroupSignal(pgid, sig, leader(pgid));
514
+ }
515
+ catch (err) {
516
+ if (isGroupSignalRefusal(err)) {
517
+ refused.set(pgid, err.message);
518
+ return false;
519
+ }
520
+ // Already gone.
521
+ }
522
+ return true;
523
+ };
524
+ for (const pgid of unsupervised)
525
+ signalG(pgid, "SIGINT");
526
+ const anyAlive = () => [...workers].some(([p, start]) => !workerRefused(p) && sameProcess(p, start)) || [...groups.keys()].some((g) => !refused.has(g) && stillOurs(g));
527
+ // A look is a few signals and cached start times, cheap enough to take every 10 ms, so that the
528
+ // cancel returns soon after the workers and agents have gone rather than up to a tick later.
529
+ await waitGone(() => !anyAlive(), graceMs + 1500, 10);
530
+ for (const pgid of groups.keys()) {
531
+ if (refused.has(pgid))
532
+ continue;
533
+ if (stillOurs(pgid)) {
534
+ const known = new Set(trees.get(pgid).map((p) => p.pid));
535
+ trees.set(pgid, [...trees.get(pgid), ...procTree(pgid, spared).procs.filter((p) => !known.has(p.pid))]);
536
+ if (!signalG(pgid, "SIGKILL"))
537
+ continue;
538
+ }
539
+ killProcs(trees.get(pgid));
540
+ }
541
+ for (const [pid, start] of workers)
542
+ if (!workerRefused(pid) && sameProcess(pid, start))
543
+ signal(pid, "SIGKILL");
544
+ await waitGone(() => !anyAlive(), 1000);
545
+ return { stillOurs, refused };
546
+ }