@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,42 @@
1
+ /** Durable WP3 authority/accounting checks, shared with WP2 without broker dependencies. */
2
+ import { db, getTurn, tx } from "./db.js";
3
+ import { escalationDetail, escalationDecisionProblem, escalationRequestProblem } from "./escalation-authority.js";
4
+ import { assertNeverCurrent } from "./never-checkpoint.js";
5
+ const request = (id) => db().prepare("SELECT * FROM requests WHERE id = ?").get(id);
6
+ /** WP2 checkpoints never before its consume transaction, then calls this INSIDE that
7
+ * transaction alongside destination assignment and its consume-once/deadline state change.
8
+ * This validates authority only; WP2 still owns atomic consumption, teardown and launch.
9
+ */
10
+ export function assertEscalationConsumable(requestId, digest, neverHash) {
11
+ const row = request(requestId);
12
+ const detail = row && escalationDetail(row.detail_json);
13
+ if (!row || row.status !== "allowed" || !detail?.decision || detail.request_digest !== digest || detail.decision.request_digest !== digest)
14
+ throw new Error("overlay has no matching immutable escalation decision");
15
+ const policy = assertNeverCurrent(row.run_id, neverHash);
16
+ const why = escalationRequestProblem(detail, row, policy) ?? escalationDecisionProblem(detail, row);
17
+ if (why)
18
+ throw new Error(why);
19
+ const state = JSON.parse(row.detail_json);
20
+ if (state.receipt_delivery !== "delivered" || state.handoff_state !== "pending")
21
+ throw new Error("overlay receipt was not delivered or the handoff failed; do not launch or replay it");
22
+ return { canonical: detail.escalation, digest, decision: detail.decision };
23
+ }
24
+ /** WP2 calls after durable launch/teardown. No output from an agent supplies these fields. */
25
+ export function recordEscalationOutcome(requestId, outcome) {
26
+ const change = () => {
27
+ const row = request(requestId);
28
+ const detail = row && escalationDetail(row.detail_json);
29
+ if (!row || row.status !== "allowed" || !detail?.decision)
30
+ throw new Error("cannot account an unapproved escalation");
31
+ const existing = JSON.parse(row.detail_json).overlay_outcome;
32
+ if (existing?.launched && !outcome.launched || existing?.destination_turn != null && existing.destination_turn !== outcome.destination_turn)
33
+ throw new Error("cannot erase or reassign an overlay launch");
34
+ if (outcome.launched && (outcome.destination_turn === null || getTurn(outcome.destination_turn)?.node_id !== row.node_id))
35
+ throw new Error("overlay destination is not a turn of the approved job");
36
+ db().prepare("UPDATE requests SET detail_json = json_set(detail_json, '$.overlay_outcome', json(?)) WHERE id = ?").run(JSON.stringify(outcome), requestId);
37
+ };
38
+ if (db().isTransaction)
39
+ change();
40
+ else
41
+ tx(change);
42
+ }
@@ -0,0 +1,191 @@
1
+ import { recordEscalationOutcome } from "./escalation-state.js";
2
+ import { escalationEnabled } from "./config.js";
3
+ import { db, getNode, getRun, getTurn, newId, runConfig, tx, workCwd } from "./db.js";
4
+ import { getRequest, requestApproval, turnGone } from "./approvals.js";
5
+ import { assertNeverCurrent, checkpointNever } from "./never-checkpoint.js";
6
+ import { escalationDecisionProblem, escalationDetail, escalationRequestProblem } from "./escalation-authority.js";
7
+ import { escalationPersonPathAvailable, escalationRuntime } from "./escalation-contract.js";
8
+ import { escalationCapabilityProblem, escalationDigest, escalationEffect, EscalationInputSchema, localhostConnectEffect, normalizeCapabilities, owningRootBinding, requiredDecider } from "./escalation-policy.js";
9
+ import { redactor, SESSION_TOKEN_SHAPE } from "./secrets.js";
10
+ import { holdsServers } from "./extensions.js";
11
+ const inFlight = new Set();
12
+ const failure = (error, reason) => ({ error, reason, recovery: "Continue within the current profile, or ask the owning root/person for a qualified replacement-turn capability." });
13
+ /** Durable admission gate shared by every broker session of the source turn. */
14
+ export function escalationTurnClosing(node, turn) {
15
+ return !!db().prepare("SELECT 1 FROM requests WHERE node_id = ? AND turn_id = ? AND kind = 'escalation' AND status = 'allowed' AND json_extract(detail_json, '$.handoff_state') IS NOT NULL LIMIT 1").get(node, turn);
16
+ }
17
+ export async function escalate(inst, raw, call) {
18
+ const ctx = inst.ctx;
19
+ if (ctx.kind !== "child" || !ctx.mayAsk)
20
+ return failure("capability_unavailable", "only the authenticated live owning child may request escalation");
21
+ const key = `${ctx.nodeId}:${ctx.turnId}`;
22
+ if (escalationTurnClosing(ctx.nodeId, ctx.turnId))
23
+ return failure("turn_closing", "this turn already handed off an escalation; it cannot issue more work");
24
+ if (inFlight.has(key))
25
+ return failure("escalation_pending", "this turn already has an escalation call in flight");
26
+ const node = getNode(ctx.nodeId);
27
+ const turn = getTurn(ctx.turnId);
28
+ if (!node || node.run_id !== ctx.runId || !turn || turn.access !== ctx.access || turnGone(ctx.nodeId, ctx.turnId))
29
+ return failure("turn_ended", "the source turn is no longer live");
30
+ const cfg = runConfig(ctx.runId);
31
+ if (!escalationEnabled(cfg) || cfg.allow_dangerous)
32
+ return failure("capability_unavailable", "escalation is disabled or the launch is not a checked confined turn");
33
+ const runtime = escalationRuntime(ctx.nodeId, ctx.turnId);
34
+ if (!runtime)
35
+ return failure("capability_unavailable", "this backend has no qualified restart-overlay lifecycle registered");
36
+ if (call.signal.aborted)
37
+ return failure("approval_denied", "the requesting call was cancelled");
38
+ inFlight.add(key);
39
+ let requestId;
40
+ let prepared;
41
+ let handedOff = false;
42
+ try {
43
+ const input = EscalationInputSchema.parse(raw);
44
+ const serialized = JSON.stringify(input);
45
+ if (serialized.length > 262144 || SESSION_TOKEN_SHAPE.test(serialized) || redactor()(serialized) !== serialized)
46
+ return failure("invalid_request", "the request is too large or contains a secret/bearer token; remove it");
47
+ const policy = checkpointNever(ctx.runId, "approval");
48
+ const caps = normalizeCapabilities(input, workCwd(node));
49
+ const why = escalationCapabilityProblem(caps, policy, ctx.access);
50
+ if (why)
51
+ return failure("capability_refused", why);
52
+ const unavailable = runtime.qualify(caps, policy);
53
+ if (unavailable)
54
+ return failure("capability_unavailable", unavailable);
55
+ const owner = getRun(ctx.runId)?.root_token;
56
+ if (!owner)
57
+ return failure("capability_unavailable", "the run has no authenticated owning root session");
58
+ const decider = holdsServers(node) ? "person" : requiredDecider(caps, cfg);
59
+ const snapshot = runtime.snapshot();
60
+ if (!snapshot.native_thread || !snapshot.native_turn || !snapshot.base_policy_hash || !snapshot.launch_plan || !Number.isFinite(snapshot.overlay_budget_s) || snapshot.overlay_budget_s <= 0 || snapshot.deadline_ms !== undefined && (!Number.isFinite(snapshot.deadline_ms) || snapshot.deadline_ms <= Date.now()))
61
+ return failure("capability_unavailable", "the runtime did not supply a checked identity and finite remaining deadline");
62
+ let deadline = snapshot.deadline_ms ?? Infinity;
63
+ if (cfg.job_timeout_s !== null)
64
+ deadline = Math.min(deadline, (node.started_at ?? node.created_at) + cfg.job_timeout_s * 1000);
65
+ if (cfg.turn_timeout_s !== null)
66
+ deadline = Math.min(deadline, (turn.started_at ?? turn.created_at) + cfg.turn_timeout_s * 1000);
67
+ const overlayBudget = Math.min(3600, snapshot.overlay_budget_s, (deadline - Date.now()) / 1000);
68
+ if (!(overlayBudget > 0))
69
+ return failure("approval_denied", "the source job/turn deadline expired");
70
+ requestId = newId("request");
71
+ const canonical = {
72
+ ...snapshot, version: 1, request_id: requestId, run_id: ctx.runId, node_id: ctx.nodeId, origin_turn: ctx.turnId,
73
+ mcp_session: call.sessionId ?? escalationDigest(["relay-broker-session-v1", inst.token]), mcp_call: String(call.requestId), access: ctx.access,
74
+ root: owningRootBinding(ctx.runId, owner), required_decider: decider, capabilities: caps,
75
+ reason: input.reason, continuation: input.continuation, never_hash: policy.hash,
76
+ baseline_grant_hash: escalationDigest(turn.grant_json),
77
+ overlay_budget_s: overlayBudget, approval_deadline_ms: Math.min(Date.now() + cfg.approval_timeout_s * 1000, deadline),
78
+ ...(Number.isFinite(deadline) ? { deadline_ms: deadline } : {}),
79
+ };
80
+ if (decider === "person" && !escalationPersonPathAvailable(ctx.runId))
81
+ return failure("person_path_unavailable", escalationEffect(canonical));
82
+ const digest = escalationDigest(canonical);
83
+ // MCP retries never create another approval/overlay, even on a new broker server instance.
84
+ const replay = db().prepare("SELECT id FROM requests WHERE node_id = ? AND turn_id = ? AND kind = 'escalation' AND json_extract(detail_json, '$.escalation.mcp_session') = ? AND json_extract(detail_json, '$.escalation.mcp_call') = ? LIMIT 1")
85
+ .get(node.id, turn.id, canonical.mcp_session, canonical.mcp_call);
86
+ if (replay)
87
+ return failure("request_replayed", `MCP call already recorded as ${replay.id}; it will not be reapplied`);
88
+ const overlay = runtime.prepare?.(canonical, digest, call.signal);
89
+ prepared = canonical;
90
+ const effect = escalationEffect(canonical);
91
+ const answer = await requestApproval(node.id, turn.id, { kind: "escalation", summary: effect, reason: input.reason, detail: { escalation: canonical, request_digest: digest, effect, ...(overlay ? { overlay } : {}) } }, () => call.signal.aborted || escalationRuntime(node.id, turn.id) !== runtime, call.onTick);
92
+ if (!answer.allow) {
93
+ if (getRequest(requestId)?.status === "allowed")
94
+ recordEscalationOutcome(requestId, { destination_turn: null, launched: false, outcome: "cancelled", cleanup: "not_started", effective_scope: "approved but never launched" });
95
+ return failure("approval_denied", answer.note ?? "the escalation was denied or expired");
96
+ }
97
+ const effective = checkpointNever(ctx.runId, "decision");
98
+ const approved = tx(() => {
99
+ assertNeverCurrent(ctx.runId, effective.hash);
100
+ const row = getRequest(requestId);
101
+ const detail = row && escalationDetail(row.detail_json);
102
+ if (!row || row.status !== "allowed" || !detail?.decision || detail.request_digest !== digest)
103
+ throw new Error("no matching authenticated approval was recorded");
104
+ // WP2's atomic allow deliberately closes this origin to all OTHER work. The owning
105
+ // escalation must still deliver its receipt; test registry liveness without that gate.
106
+ const no = escalationRequestProblem(detail, row, effective) ?? escalationDecisionProblem(detail, row)
107
+ ?? (getTurn(turn.id)?.status !== "running" || getNode(node.id)?.status !== "running" ? "the source turn is no longer live" : null);
108
+ if (no || call.signal.aborted || escalationRuntime(node.id, turn.id) !== runtime)
109
+ throw new Error(no ?? "the originating call/lifecycle was lost before handoff");
110
+ const current = runtime.snapshot();
111
+ if (current.base_policy_hash !== canonical.base_policy_hash || current.native_thread !== canonical.native_thread || current.native_turn !== canonical.native_turn || current.launch_plan !== canonical.launch_plan || current.deadline_ms !== snapshot.deadline_ms)
112
+ throw new Error("the effective source policy/identity/deadline changed after approval");
113
+ db().prepare("UPDATE requests SET detail_json = json_set(detail_json, '$.handoff_state', 'pending') WHERE id = ?").run(row.id);
114
+ return { canonical: detail.escalation, digest: detail.request_digest, decision: detail.decision };
115
+ });
116
+ // Request only: WP2 stores the consume-once continuation and closes the turn. The broker
117
+ // returns now; it never waits for the destination, whose old app server must die first.
118
+ const receipt = await runtime.request(approved, call.signal);
119
+ if (call.signal.aborted)
120
+ throw new Error("requesting call cancelled during handoff; runtime must invalidate pending state");
121
+ handedOff = true;
122
+ return { ...receipt, request_id: requestId, request_digest: digest, capabilities: caps, required_decider: decider, decision_provenance: approved.decision, overlay_budget_s: canonical.overlay_budget_s, approval_deadline_ms: canonical.approval_deadline_ms, effect: escalationEffect(canonical) };
123
+ }
124
+ catch (err) {
125
+ if (requestId && getRequest(requestId)?.status === "allowed") {
126
+ db().prepare("UPDATE requests SET detail_json = json_set(detail_json, '$.handoff_state', 'failed-before-launch') WHERE id = ?").run(requestId);
127
+ recordEscalationOutcome(requestId, { destination_turn: null, launched: false, outcome: "failed", cleanup: "not_started", effective_scope: "approved but never launched" });
128
+ }
129
+ return failure("escalation_failed", err.message);
130
+ }
131
+ finally {
132
+ if (prepared && !handedOff)
133
+ runtime.abandon?.(prepared);
134
+ inFlight.delete(key);
135
+ }
136
+ }
137
+ /** Bind transport delivery to the exact pending handoff; repeated writes cannot replay it. */
138
+ export function escalationReceiptDelivery(requestId, digest, signal) {
139
+ const row = getRequest(requestId);
140
+ const runtime = row?.turn_id == null ? undefined : escalationRuntime(row.node_id, row.turn_id);
141
+ let settled = false;
142
+ return async (delivered) => {
143
+ if (settled)
144
+ return;
145
+ settled = true;
146
+ const ok = delivered && !signal.aborted;
147
+ const approved = tx(() => {
148
+ const row = getRequest(requestId);
149
+ const detail = row && escalationDetail(row.detail_json);
150
+ if (!row || row.status !== "allowed" || !detail?.decision || detail.request_digest !== digest)
151
+ throw new Error("receipt has no matching approved escalation");
152
+ const changed = db().prepare("UPDATE requests SET detail_json = json_set(detail_json, '$.receipt_delivery', ?) WHERE id = ? AND json_extract(detail_json, '$.receipt_delivery') IS NULL")
153
+ .run(ok ? "delivered" : "failed", requestId);
154
+ if (Number(changed.changes) !== 1)
155
+ return null;
156
+ return { canonical: detail.escalation, digest, decision: detail.decision };
157
+ });
158
+ if (!approved)
159
+ return;
160
+ try {
161
+ if (!runtime)
162
+ throw new Error("overlay runtime lost before receipt delivery");
163
+ await runtime.receipt(approved, ok);
164
+ }
165
+ catch (err) {
166
+ db().prepare("UPDATE requests SET detail_json = json_set(detail_json, '$.receipt_delivery', 'failed', '$.handoff_state', 'failed-before-launch') WHERE id = ?").run(requestId);
167
+ recordEscalationOutcome(requestId, { destination_turn: null, launched: false, outcome: "failed", cleanup: "not_started", effective_scope: "approved but never launched" });
168
+ throw err;
169
+ }
170
+ };
171
+ }
172
+ export { assertEscalationConsumable, recordEscalationOutcome } from "./escalation-state.js";
173
+ /** Results/status derive scope from authoritative requests, including failures/cancellations. */
174
+ export function escalationAccounting(nodeId) {
175
+ const rows = db().prepare("SELECT id, detail_json FROM requests WHERE node_id = ? AND kind = 'escalation' AND status = 'allowed' ORDER BY created_at, id").all(nodeId);
176
+ return rows.map(row => {
177
+ const d = escalationDetail(row.detail_json);
178
+ if (!d)
179
+ return { request_id: row.id, enforcement: "unknown", cleanup: "uncertain", error: "malformed escalation accounting" };
180
+ const outcome = JSON.parse(row.detail_json).overlay_outcome;
181
+ const launched = outcome?.launched === true;
182
+ const lan = d.escalation.capabilities.some(c => c.kind === "port0" || c.kind === "localhost" && c.operation === "listen");
183
+ return { request_id: row.id, request_digest: d.request_digest, origin_turn: d.escalation.origin_turn, destination_turn: outcome?.destination_turn ?? null, capabilities: d.escalation.capabilities, required_decider: d.escalation.required_decider, decision_provenance: d.decision,
184
+ lifetime: "one replacement turn", enforcement: "baseline plus explicit approved capability; no baseline-only confinement claim", ...outcome,
185
+ launch: outcome ? launched ? "launched" : "allowed but never launched" : "allowed; not yet launched or launch outcome unreported",
186
+ cleanup: outcome?.cleanup ?? "uncertain",
187
+ ...(lan ? { lan_disclosure: launched ? "This turn allowed listeners to bind 0.0.0.0, so they could be on the LAN." : "Allowed listeners to bind 0.0.0.0, so they could be on the LAN; never launched or launch outcome unreported." } : {}),
188
+ ...(d.escalation.capabilities.some(c => c.kind === "localhost" && c.operation === "connect") ? { connect_disclosure: `${launched ? "This turn allowed" : "Approved; never launched or launch outcome unreported:"} ${d.escalation.capabilities.flatMap(c => c.kind === "localhost" && c.operation === "connect" ? [localhostConnectEffect(c.port)] : []).join(" ")}` } : {}),
189
+ };
190
+ });
191
+ }
@@ -0,0 +1,235 @@
1
+ // Events: what a root session should hear about in its runs (an item settled, an approval request
2
+ // was handed to it, a discussion reply arrived), each recorded once with an id. They reach the
3
+ // session at least once: in the `events` field of its next relay tool result, and, in Claude Code,
4
+ // as a notice posted to the session's inbox socket when no call of the session is waiting on them.
5
+ // A notice is a pointer (the item, what happened, what to call); never the other agent's words.
6
+ import net from "node:net";
7
+ import path from "node:path";
8
+ import { relayHome } from "./config.js";
9
+ import { db, getNode, now } from "./db.js";
10
+ import { deciderOf } from "./approvals.js";
11
+ import { personOnly } from "./extensions.js";
12
+ import { clipped } from "./shown.js";
13
+ import { appendLog } from "./storage.js";
14
+ /** Statuses that end an item on its own: "blocked" finished too, refused something on the way (db.ts NodeStatus). */
15
+ const ENDED = ["done", "blocked", "refused", "failed", "timeout", "lost"];
16
+ /**
17
+ * The root-level discussion a turn of this session was written for, when the session was borrowed
18
+ * for it (it existed before the discussion, so the discussion is not its parent); otherwise undefined.
19
+ */
20
+ function borrowedFor(n, source) {
21
+ if (!source.startsWith("discussion:"))
22
+ return undefined;
23
+ const from = getNode(source.slice("discussion:".length));
24
+ return from?.kind === "discussion" && !from.parent_id && from.id !== n.parent_id ? from : undefined;
25
+ }
26
+ /**
27
+ * What the root session is to hear when a node settles, each with the key it is recorded under:
28
+ * its own jobs and threads finishing; the reviewer of its review; the participant of its discussion
29
+ * (a reply). What jobs start themselves is theirs to follow. Cancelled items are left out: a cancel
30
+ * comes from the session or the terminal, which know.
31
+ *
32
+ * What settled is read from the session's executed turns (done or failed), latest first by when
33
+ * they ended, not from its newest turn row: that may be a queued turn cancelled since, which never ran.
34
+ */
35
+ function pointersOf(n, executed) {
36
+ if (!ENDED.includes(n.status))
37
+ return [];
38
+ // Keyed on the executed turn the event is about, so that a session settling again without a new
39
+ // turn (one requeued for a turn cancelled before it ran) records nothing twice. Only a session
40
+ // with no executed turn at all is keyed on when it ended.
41
+ const keyOf = (t) => (t ? `settled:${n.id}:turn:${t.id}` : `settled:${n.id}:${n.ended_at}`);
42
+ const nodeKey = keyOf(executed[0]);
43
+ const rootSession = !n.parent_id && (n.kind === "job" || n.kind === "thread");
44
+ // Each executed turn with the root-level discussion it was written for, when the session was
45
+ // borrowed for one (looked up once per source).
46
+ const lent = new Map();
47
+ const turns = executed.map((t) => {
48
+ if (!lent.has(t.source))
49
+ lent.set(t.source, borrowedFor(n, t.source));
50
+ return { t, from: lent.get(t.source) };
51
+ });
52
+ // A root-level job or thread finishing its own work is keyed on its own latest turn, so that it
53
+ // is announced once whether or not a discussion turn followed before the session settled.
54
+ const own = turns.find((x) => !x.from)?.t;
55
+ // Blocked is the case where the session most needs to act (resume with a grant), so it says why.
56
+ const why = n.status === "blocked" ? ": its agent was refused something it tried" : "";
57
+ const finished = (key) => ({ key, item: n, text: `${n.kind} ${n.id} finished (${n.status})${why}. Call result ${n.id}.` });
58
+ // A session the root session borrowed for a discussion settles after each reply it writes there:
59
+ // that is the discussion's news (while it is open), keyed on the latest turn it wrote there. Not
60
+ // only when that turn is its newest: its own queued turn may have run at once after the reply, so
61
+ // that no look saw the session settled with the reply alone. Its own work, settled with it or
62
+ // after it, is announced too. (A review's reconciliation is the review's news, below.)
63
+ const replies = [];
64
+ const answered = new Set();
65
+ for (const { t, from } of turns) {
66
+ if (!from || answered.has(from.id))
67
+ continue;
68
+ answered.add(from.id);
69
+ if (from.status === "open")
70
+ replies.push({ key: keyOf(t), item: from, text: `discussion ${from.id} has a reply. Call status ${from.id}.` });
71
+ }
72
+ if (turns[0]?.from)
73
+ return rootSession && own ? [...replies, finished(keyOf(own))] : replies;
74
+ if (!n.parent_id)
75
+ return rootSession ? [...replies, finished(keyOf(own))] : replies;
76
+ const parent = getNode(n.parent_id);
77
+ if (!parent || parent.parent_id)
78
+ return replies;
79
+ if (parent.kind === "review" && n.kind === "job") {
80
+ // Once the review is being reconciled, the reviewer's turns are its replies in that discussion.
81
+ const d = JSON.parse(parent.params_json ?? "{}").discussion;
82
+ if (d && d !== "opening")
83
+ return [...replies, { key: nodeKey, item: parent, text: `review ${parent.id} has a reply in its discussion ${d}. Call status ${d}.` }];
84
+ return [...replies, { key: nodeKey, item: parent, text: `the reviewer of review ${parent.id} finished (${n.status}). Call status ${parent.id}.` }];
85
+ }
86
+ if (parent.kind === "discussion" && parent.status === "open")
87
+ return [...replies, { key: nodeKey, item: parent, text: `discussion ${parent.id} has a reply. Call status ${parent.id}.` }];
88
+ return replies;
89
+ }
90
+ /** Who decided a request, in words for the root agent, when it was a person and not the root agent itself. */
91
+ const BY_PERSON = {
92
+ "user-dialog": "by the user in relay's approval dialog",
93
+ "user-confirm": "by the user in your host's permission prompt (confirm)",
94
+ // Whoever ran the command: relay cannot tell.
95
+ terminal: "from a terminal (relay approve or relay deny)",
96
+ };
97
+ const byPerson = (decidedBy) => BY_PERSON[deciderOf(decidedBy)] ?? null;
98
+ /**
99
+ * Records the events of the runs this root session owns, from `since[run]` on (each run's
100
+ * creation, also for a run taken over, so that what settled while no session owned it is not
101
+ * lost): settled items, approval requests that are pending and not being put to the user directly
102
+ * (`asking`), and requests a person decided rather than the root agent. Each is recorded once,
103
+ * keyed on what it is about, so looking again over the same span records nothing twice.
104
+ */
105
+ export function recordEvents(since, asking) {
106
+ // Most looks find nothing new, and an ignored insert would still use up an id of the AUTOINCREMENT
107
+ // key. So nothing is inserted where the key is there already, and event ids stay dense.
108
+ const add = db().prepare("INSERT INTO events (run_id, key, kind, item_id, subject, text, created_at) SELECT ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM events WHERE key = ?)");
109
+ // An insert takes the registry's write lock even when it inserts nothing, and every tool result
110
+ // looks again at everything since each run began: an event already recorded is found by a read
111
+ // first. The insert keeps its own condition, so two looks at once still record it once.
112
+ const recorded = db().prepare("SELECT 1 FROM events WHERE key = ?");
113
+ const insert = { run: (runId, key, kind, item, subject, text, at) => recorded.get(key) ? undefined : add.run(runId, key, kind, item, subject, text, at, key) };
114
+ for (const [runId, from] of since) {
115
+ const nodes = db().prepare("SELECT * FROM nodes WHERE run_id = ? AND ended_at >= ?").all(runId, from);
116
+ // Each node's executed turns, latest first by when they ended (pointersOf), read for all of them
117
+ // at once, for exactly the nodes just read, by id. Asking again which nodes have ended would
118
+ // leave out one whose next turn another process started in between, and with it the turns that
119
+ // say what it settled with. An executed turn's status is final, so this read finds every turn
120
+ // that had executed when its node was read, as a read per node would.
121
+ const executed = new Map();
122
+ const ids = JSON.stringify(nodes.map((n) => n.id));
123
+ for (const t of db().prepare("SELECT node_id, id, source FROM turns WHERE status IN ('done', 'failed', 'refused') AND node_id IN (SELECT value FROM json_each(?)) ORDER BY ended_at DESC, id DESC").all(ids)) {
124
+ const list = executed.get(t.node_id);
125
+ if (list)
126
+ list.push({ id: t.id, source: t.source });
127
+ else
128
+ executed.set(t.node_id, [{ id: t.id, source: t.source }]);
129
+ }
130
+ for (const n of nodes) {
131
+ for (const p of pointersOf(n, executed.get(n.id) ?? []))
132
+ insert.run(runId, p.key, "settled", p.item.id, n.id, p.text, now());
133
+ }
134
+ const requests = db().prepare("SELECT id, node_id, kind, detail_json FROM requests WHERE run_id = ? AND status = 'pending' AND created_at >= ?").all(runId, from);
135
+ for (const r of requests) {
136
+ if (asking(r.id))
137
+ continue;
138
+ const n = getNode(r.node_id);
139
+ // What it wants is the launched agent's own text, so it stays in tool results and out of the
140
+ // session's turn: the notice says only who asks and where to look. A request only the person
141
+ // may allow (docs/extensions.md) is said to be one.
142
+ const text = personOnly(r)
143
+ ? `${n?.kind ?? "item"} ${r.node_id} needs approval ${r.id}, which only the user can allow. Call status ${r.node_id}, then leave it to them (relay's question, or confirm where you have it) or deny it.`
144
+ : `${n?.kind ?? "item"} ${r.node_id} needs approval ${r.id}. Call status ${r.node_id}, then approve or deny it.`;
145
+ insert.run(runId, `approval:${r.id}`, "approval", r.node_id, r.id, text, now());
146
+ }
147
+ // A person's decision, so that the root agent knows one was made and by whom. What the request
148
+ // wanted is the launched agent's text; these events go only into tool results, never notices.
149
+ const decided = db().prepare("SELECT id, node_id, status, summary, decided_by FROM requests WHERE run_id = ? AND status IN ('allowed', 'denied') AND decided_at >= ?")
150
+ .all(runId, from);
151
+ for (const r of decided) {
152
+ const how = byPerson(r.decided_by);
153
+ if (!how)
154
+ continue;
155
+ const n = getNode(r.node_id);
156
+ const text = `approval ${r.id} (${n?.kind ?? "item"} ${r.node_id}: ${clipped(r.summary, 120)}) was ${r.status} ${how}. Nothing to call.`;
157
+ insert.run(runId, `decided:${r.id}`, "decided", r.node_id, r.id, text, now());
158
+ }
159
+ }
160
+ }
161
+ /** Who decided a request, in words for the root agent, whoever it was. */
162
+ export function decidedBy(r) {
163
+ if (r.status === "expired")
164
+ return "closed without an answer (its turn ended, the asking agent stopped waiting, or nobody answered in time)";
165
+ const who = deciderOf(r.decided_by);
166
+ const how = BY_PERSON[who];
167
+ if (how)
168
+ return `${r.status} ${how}`;
169
+ if (who === "root" || who === "root-confirmed")
170
+ return `${r.status} by you (the root session${who === "root-confirmed" ? ", stating that the user confirmed" : ""})`;
171
+ return `${r.status} by ${r.decided_by ?? "someone else"}`;
172
+ }
173
+ /**
174
+ * Records that a question about a request was answered after it had been decided elsewhere: a
175
+ * host that keeps a withdrawn form on screen (Codex) lets the person answer it, and an answer can
176
+ * also cross a decision made elsewhere in the moment before relay withdraws the form. The answer
177
+ * changes nothing; the event is so that the root agent can tell them so. `by` says whose answer it
178
+ * is: "user" for one the form lets only a person give, "host" for one relay cannot attribute to
179
+ * the user (a Codex decline). Once per request.
180
+ */
181
+ export function recordLateAnswer(r, said, by) {
182
+ const text = by === "user"
183
+ ? `the user answered approval ${r.id} ("${said}") in relay's approval form after it had already been ${decidedBy(r)}. Their answer changed nothing; tell them so.`
184
+ : `relay's approval form for approval ${r.id} was answered ("${said}") by the host after it had already been ${decidedBy(r)}; relay cannot tell whether the user gave it or the host answered on its own. It changed nothing; if the user did answer, tell them so.`;
185
+ db().prepare("INSERT INTO events (run_id, key, kind, item_id, subject, text, created_at) SELECT ?, ?, 'late', ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM events WHERE key = ?)")
186
+ .run(r.run_id, `late:${r.id}`, r.node_id, r.id, text, now(), `late:${r.id}`);
187
+ }
188
+ /**
189
+ * The unsigned pointer in tool-result events and verified-event replies. Inbox notices add a
190
+ * live-server tag (notices.ts); the event id still identifies one event across both channels.
191
+ */
192
+ export const noticeText = (e) => `relay (event ${e.id}): ${e.text}`;
193
+ /** Events of these runs the session has not been given yet, oldest first. */
194
+ export function unseenEvents(runIds) {
195
+ if (!runIds.length)
196
+ return [];
197
+ return db().prepare(`SELECT * FROM events WHERE seen_at IS NULL AND run_id IN (${runIds.map(() => "?").join(", ")}) ORDER BY id`).all(...runIds);
198
+ }
199
+ export function markSeen(ids) {
200
+ const stmt = db().prepare("UPDATE events SET seen_at = ? WHERE id = ? AND seen_at IS NULL");
201
+ for (const id of ids)
202
+ stmt.run(now(), id);
203
+ }
204
+ /** Claims the posting of an event's notice; false when it has been posted already. */
205
+ export function claimNotice(id) {
206
+ return Number(db().prepare("UPDATE events SET noticed_at = ? WHERE id = ? AND noticed_at IS NULL").run(now(), id).changes) === 1;
207
+ }
208
+ /**
209
+ * Posts a notice to the Claude Code session whose inbox socket this is: an auth line with its
210
+ * token, then the message as a user turn. Claude Code labels it as a message from another session
211
+ * that cannot approve anything; it starts a turn in an idle session, and in a busy one is read when
212
+ * the current tool call returns. Resolves when written or failed; the outcome goes to notices.log.
213
+ */
214
+ export function postNotice(socket, token, text, eventId) {
215
+ return new Promise((resolve) => {
216
+ let done = false;
217
+ const finish = (outcome) => {
218
+ if (done)
219
+ return;
220
+ done = true;
221
+ // Diagnostics only: a failed write is not the notice's failure. Rotated at log_max_mb.
222
+ appendLog(path.join(relayHome(), "notices.log"), JSON.stringify({ at: new Date().toISOString(), event: eventId, outcome }) + "\n");
223
+ resolve();
224
+ };
225
+ const c = net.createConnection(socket, () => {
226
+ const lines = [...(token ? [JSON.stringify({ type: "auth", token })] : []), JSON.stringify({ type: "user", message: { role: "user", content: text } })];
227
+ c.end(lines.join("\n") + "\n", () => finish("posted"));
228
+ });
229
+ c.setTimeout(5000, () => {
230
+ c.destroy();
231
+ finish("timed out");
232
+ });
233
+ c.on("error", (err) => finish(`error: ${err.message}`));
234
+ });
235
+ }
@@ -0,0 +1,147 @@
1
+ // Every program relay runs outside a sandbox is run by an absolute path (review r_0c11d860 X1
2
+ // follow-up): macOS's own tools by their fixed paths in the sealed system volume (/bin, /sbin,
3
+ // /usr/bin, /usr/sbin, which SIP protects), everything else (git, the target CLIs) found on PATH
4
+ // here and run by the absolute name found. Nothing is left to a lookup when the program starts.
5
+ // What is found is protected: no grant may cover the name, the file it leads to or its
6
+ // installation (protected-config.ts relayInstallation), nor a directory on relay's PATH, either way
7
+ // round (relayPathDirs); relay's sandboxes deny writing all of them; and a turn whose own PATH
8
+ // leads a target CLI into a granted directory is refused (targetLaunchProblem).
9
+ // test/executables.test.ts fails on a spawn of a bare name in src/, bin/relay or the build scripts.
10
+ import { spawnSync } from "node:child_process";
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ const runnable = (p) => {
15
+ try {
16
+ fs.accessSync(p, fs.constants.X_OK);
17
+ return fs.statSync(p).isFile();
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ };
23
+ /** What relay says when a program it would run is not there. */
24
+ export const notFound = (bin) => `\`${bin}\` was not found${bin.includes("/") ? "" : " on PATH"}, or is not runnable`;
25
+ /**
26
+ * The absolute path relay runs `bin` by: a path as given (resolved), a bare name the first runnable
27
+ * match in `searchPath`'s absolute directories (relative entries are skipped). It is the name found
28
+ * there, on purpose not the file a link leads to: Claude Code updates itself by repointing its
29
+ * link, and the next start must follow it. The name, the file it leads to and the installation
30
+ * holding it are all protected alike (protected-config.ts executableParts). Null when there is none.
31
+ */
32
+ export function findExecutable(bin, searchPath = process.env.PATH ?? "") {
33
+ if (!bin)
34
+ return null;
35
+ if (bin.includes("/"))
36
+ return runnable(path.resolve(bin)) ? path.resolve(bin) : null;
37
+ for (const dir of searchPath.split(path.delimiter)) {
38
+ if (dir && path.isAbsolute(dir) && runnable(path.join(dir, bin)))
39
+ return path.join(dir, bin);
40
+ }
41
+ return null;
42
+ }
43
+ /**
44
+ * The path a spawn of `bin` is given: a path as given, resolved (absolute, so nothing is looked up,
45
+ * and a missing or unrunnable file fails at the spawn itself, with the spawn's own error, as
46
+ * before); a bare name as findExecutable finds it on `searchPath`, or, when there is none, an error
47
+ * with code ENOENT and notFound's message, for a start that cannot go on without it.
48
+ */
49
+ export function executable(bin, searchPath = process.env.PATH ?? "") {
50
+ if (bin.includes("/"))
51
+ return path.resolve(bin);
52
+ const found = findExecutable(bin, searchPath);
53
+ if (!found)
54
+ throw Object.assign(new Error(notFound(bin)), { code: "ENOENT" });
55
+ return found;
56
+ }
57
+ /**
58
+ * Runs `bin` by its absolute path (executable's), synchronously. A path as given is run as it is,
59
+ * so a missing one gives the spawn's own result (spawnSync … ENOENT); a bare name not found on
60
+ * `searchPath` gives the same shape (error ENOENT, with notFound's message), so callers handle both alike.
61
+ */
62
+ export function spawnFound(bin, args, options, searchPath = process.env.PATH ?? "") {
63
+ const exe = bin.includes("/") ? path.resolve(bin) : findExecutable(bin, searchPath);
64
+ if (exe)
65
+ return spawnSync(exe, args, options);
66
+ const error = Object.assign(new Error(notFound(bin)), { code: "ENOENT" });
67
+ return { pid: 0, output: [], stdout: "", stderr: "", status: null, signal: null, error };
68
+ }
69
+ /**
70
+ * Whether relay is running inside its own test suite: Node's test runner sets NODE_TEST_CONTEXT in
71
+ * each test file's process, and the processes it starts inherit it. Nothing that starts relay for
72
+ * real (a host, the launcher, a terminal) sets it, and a job cannot set relay's environment.
73
+ */
74
+ const underNodeTest = () => typeof process.env.NODE_TEST_CONTEXT === "string" && process.env.NODE_TEST_CONTEXT.startsWith("child");
75
+ /**
76
+ * The directory of stand-ins the tests of the terminal commands (install, uninstall, doctor) give
77
+ * for macOS tools, or null. Those tests run relay as a separate process, so an in-process setter
78
+ * cannot reach it. Honoured only inside relay's own test suite (underNodeTest), for a directory of
79
+ * this user's under a system temp directory; elsewhere it is ignored, and the fixed path is run.
80
+ */
81
+ export function testSystemTools() {
82
+ const dir = process.env.RELAY_TEST_SYSTEM_TOOLS;
83
+ if (!dir || !path.isAbsolute(dir) || !underNodeTest())
84
+ return null;
85
+ try {
86
+ const real = fs.realpathSync(dir);
87
+ // The system's temp directories (a test may give relay a TMPDIR of its own beside the stand-ins).
88
+ const temps = [...new Set([fs.realpathSync(os.tmpdir()), "/private/tmp", "/private/var/folders"])];
89
+ const st = fs.statSync(real);
90
+ if (!temps.some((t) => real.startsWith(t + path.sep)) || !st.isDirectory() || (process.getuid && st.uid !== process.getuid()))
91
+ return null;
92
+ return real;
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ /**
99
+ * One of macOS's own tools, by its fixed path, as the terminal commands (install, uninstall, doctor)
100
+ * run it; a test's stand-in only inside relay's own test suite (testSystemTools). Relay's server and
101
+ * workers never take a stand-in: they name the fixed path directly.
102
+ */
103
+ export function systemTool(fixed) {
104
+ const dir = testSystemTools();
105
+ if (dir && runnable(path.join(dir, path.basename(fixed))))
106
+ return path.join(dir, path.basename(fixed));
107
+ return fixed;
108
+ }
109
+ let git = null;
110
+ /**
111
+ * The git relay runs, found on PATH once per process and kept: every git command relay runs, in
112
+ * this process, runs that one file by its absolute name (findExecutable's, a link's name). Null
113
+ * when there is none.
114
+ */
115
+ export function gitExecutable() {
116
+ git ??= { path: findExecutable("git") };
117
+ return git.path;
118
+ }
119
+ /** /usr/bin/git and the developer tools' other entry points are xcrun shims: they run the active developer directory's tools. */
120
+ export const XCRUN_SHIMS = new Set(["/usr/bin/git"]);
121
+ let developer = null;
122
+ /**
123
+ * The developer directories a shim may run git from: DEVELOPER_DIR when set, and the one
124
+ * `xcode-select -s` chose, read from its link without running it (once per process). Usually
125
+ * /Applications/Xcode.app/Contents/Developer or /Library/Developer/CommandLineTools, both root's,
126
+ * but a DEVELOPER_DIR or `xcode-select -s` may point anywhere.
127
+ */
128
+ export function developerDirs() {
129
+ if (developer)
130
+ return developer.dirs;
131
+ const dirs = [];
132
+ if (process.env.DEVELOPER_DIR && path.isAbsolute(process.env.DEVELOPER_DIR))
133
+ dirs.push(process.env.DEVELOPER_DIR);
134
+ try {
135
+ // A plain read of what xcode-select records, without running it: its link in /var/db.
136
+ const link = "/var/db/xcode_select_link";
137
+ if (fs.existsSync(link))
138
+ dirs.push(fs.realpathSync(link));
139
+ else if (fs.existsSync("/Library/Developer/CommandLineTools"))
140
+ dirs.push("/Library/Developer/CommandLineTools");
141
+ }
142
+ catch {
143
+ // None recorded.
144
+ }
145
+ developer = { dirs: [...new Set(dirs)] };
146
+ return developer.dirs;
147
+ }