@jbkjr/relay 0.0.0-stage → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +386 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1525 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +320 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +637 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +329 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +629 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1502 -0
  186. package/docs/pinned-codex.md +321 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
@@ -0,0 +1,740 @@
1
+ import { escalationEnabled } from "./config.js";
2
+ import { spawn } from "node:child_process";
3
+ import path from "node:path";
4
+ import { configProtection, overlapsPart, pathOverlaps, relayInstallation, relayPathDirs, relayCodexProtected } from "./protected-config.js";
5
+ import { keyAuthority } from "./api-keys.js";
6
+ import { RAW_NETWORK_CONSENT_TEXT } from "./raw-network.js";
7
+ import { approvalKey, askableReadOnly, pathAccessOf } from "../backends/types.js";
8
+ import { isTarget, targetDef, targetLabel } from "../targets/index.js";
9
+ import { managedSettings } from "./claude-settings.js";
10
+ import { consentEffect, extensionsOf, personOnly, touchesConfig } from "./extensions.js";
11
+ import { consultHome, foldedPath, inside, insideAnyCase, relayHome, worktreesHome } from "./config.js";
12
+ import { ancestors, db, getNode, getRun, getTurn, newId, nextQueuedTurn, now, runConfig, sleep, tx, turnEnded, workCwd } from "./db.js";
13
+ import { procStart, sameProcess } from "./procs.js";
14
+ import { sessionParams } from "./params.js";
15
+ import { lendSlot } from "./slots.js";
16
+ import { registryPoll } from "./wake.js";
17
+ import { appendLog } from "./storage.js";
18
+ import { redactor } from "./secrets.js";
19
+ import { assertNeverCurrent, checkpointNever, readNeverFloor } from "./never-checkpoint.js";
20
+ import { neverFloorApplies } from "./never-coverage.js";
21
+ import { neverHostedWebDisabled, neverPathProblem } from "./never-policy.js";
22
+ import { authenticateEscalationDecision, escalationDetail, escalationRequestProblem } from "./escalation-authority.js";
23
+ import { escalationEffect } from "./escalation-policy.js";
24
+ import { allowOverlayInTransaction, getOverlay, settleOverlayRequestInTransaction } from "./restart-overlay.js";
25
+ // Environment-consent notes use the owning root turn's literal redactor while its in-memory
26
+ // claim exists. No values or redaction hashes enter the request row, including through confirm.
27
+ const environmentRequestRedactors = new Map();
28
+ /** Commands remain OS-confined: argument scanning is never execution enforcement. */
29
+ export function neverApprovalProblem(policy, kind, paths, cwd, access) {
30
+ if (kind === "raw_network" && policy.hosts.length)
31
+ return "never.hosts disables raw network in Release A; request a qualified mediated route";
32
+ if (kind === "web" && neverHostedWebDisabled(policy))
33
+ return "never.hosts withholds hosted search and web__run, including open-page; person consent cannot screen provider effects";
34
+ if (kind !== "file" && kind !== "path")
35
+ return null;
36
+ if (!Array.isArray(paths) || !paths.length || paths.some(p => typeof p !== "string" || !p || /[\0\r\n]/.test(p)))
37
+ return "never cannot screen a file request without explicit literal paths";
38
+ for (const name of paths) {
39
+ const why = neverPathProblem(policy, path.resolve(cwd, name), kind === "file" || access !== "read" ? "write" : "read", true);
40
+ if (why)
41
+ return why;
42
+ }
43
+ return null;
44
+ }
45
+ export function getRequest(id) {
46
+ return db().prepare("SELECT * FROM requests WHERE id = ?").get(id);
47
+ }
48
+ /**
49
+ * Whether the request `current` is still the pending request `shown` was: same identity and the
50
+ * same wording the person was shown. `relay approve` re-reads the request after the person types
51
+ * the code and refuses unless this holds, so a change while they were asked cannot allow something
52
+ * other than what was displayed.
53
+ */
54
+ export function requestUnchanged(shown, current) {
55
+ return !!current && current.status === "pending"
56
+ && current.summary === shown.summary && current.kind === shown.kind && current.node_id === shown.node_id
57
+ && current.detail_json === shown.detail_json && current.run_id === shown.run_id && current.turn_id === shown.turn_id;
58
+ }
59
+ export function pendingRequests(runId) {
60
+ return (runId
61
+ ? db().prepare("SELECT * FROM requests WHERE run_id = ? AND status = 'pending' ORDER BY created_at").all(runId)
62
+ : db().prepare("SELECT * FROM requests WHERE status = 'pending' ORDER BY created_at").all());
63
+ }
64
+ /** Pending requests in every run the root session holding this token owns, oldest first. */
65
+ export function ownedPending(token) {
66
+ return db().prepare("SELECT r.* FROM requests r JOIN runs u ON u.id = r.run_id WHERE u.root_token = ? AND r.status = 'pending' ORDER BY r.created_at").all(token);
67
+ }
68
+ export const hasPending = (nodeId) => Boolean(db().prepare("SELECT 1 FROM requests WHERE node_id = ? AND status = 'pending' LIMIT 1").get(nodeId));
69
+ function detailOf(r) {
70
+ try {
71
+ return JSON.parse(r.detail_json ?? "{}");
72
+ }
73
+ catch {
74
+ return {};
75
+ }
76
+ }
77
+ function detailCwd(r) {
78
+ const cwd = detailOf(r).cwd;
79
+ return typeof cwd === "string" ? cwd : undefined;
80
+ }
81
+ /**
82
+ * What allowing a request would actually let the agent do, in plain words. A command that asked
83
+ * while staying in its sandbox goes ahead sandboxed; so does a Codex command that asked for access
84
+ * added to its sandbox for it alone (`adds`: codex-app.ts commandAsk), with that added, which its
85
+ * request (wants) names. A plain Codex request to leave the sandbox (`restricted`: codex-app.ts
86
+ * commandAsk) runs in a sandbox that can write everywhere but the denied credential stores. Anything
87
+ * else is taken to run unconfined.
88
+ */
89
+ function effectOf(kind, mode, sandboxed, n, adds = false, restricted) {
90
+ const readOnly = mode === "read" ? " (the session is otherwise read-only, and this command could change files)" : "";
91
+ if (kind === "command" && sandboxed)
92
+ return "runs this one command inside its sandbox, with the same limits as its other commands";
93
+ if (kind === "command" && restricted)
94
+ return `${codexEscalatedEffect(restricted)}${readOnly}`;
95
+ if (kind === "command" && adds)
96
+ return "runs this one command inside its sandbox, with the same limits as its other commands except for the access its request asks to add (in wants), for this command alone";
97
+ if (kind === "command")
98
+ return `runs this one command outside the sandbox, with your full access${readOnly}`;
99
+ if (kind === "web")
100
+ return "reaches the web for this search or fetch";
101
+ // Where its sandbox does not let it write: outside the writable places, or (Codex, whose profile
102
+ // keeps them read-only) configuration your agents or tools load, or an existing .git, at the top
103
+ // of the worktree or a grant.
104
+ if (kind === "file")
105
+ return "changes these files outside its sandbox: outside its worktree and granted directories, or, at their top, configuration your agents or tools load (.claude/, .mcp.json and the like) or git metadata (an existing .git)";
106
+ // What the session was given decides what consenting does: skills alone change none of its limits.
107
+ if (kind === "extensions")
108
+ return consentEffect(n ?? { kind: "job" }, extensionsOf(n));
109
+ if (kind === "local_network")
110
+ return LOCAL_NETWORK_EFFECT;
111
+ if (kind === "raw_network")
112
+ return RAW_NETWORK_CONSENT_TEXT;
113
+ if (kind === "env")
114
+ return "gives all tools and native subagents in this one turn the named environment values. They can read, copy and use them. Network-off still permits disclosure through model requests, results and permitted native web tools. This does not grant network, file or extension access; a resume needs fresh consent";
115
+ if (kind === "mcp") {
116
+ return `runs this tool of an MCP server you allowed, outside the agent's sandbox, as your own process, with exactly these arguments (allowed for the rest of the ${n?.kind === "thread" ? "thread" : "job"}: this tool, with any arguments)`;
117
+ }
118
+ return "uses a tool that needs permission";
119
+ }
120
+ /**
121
+ * What allowing a Codex command to run outside its sandbox does since relay 1.0.5 (codex-app.ts
122
+ * commandAsk, codex.ts deniedCredentials): Codex keeps it in a sandbox that writes everywhere but
123
+ * the credential stores relay's profile denies, with the job's own network.
124
+ */
125
+ export function codexEscalatedEffect(network) {
126
+ // The job's network, as its turn has it (codex-app.ts commandAsk escalates_restricted): none (no
127
+ // grant, or hosted search only), strict through Codex's proxy, or local.
128
+ const net = network === "strict" ? "and the job's network only through Codex's proxy (no loopback or local network)"
129
+ : network === "local" ? "and the job's network with this Mac's loopback and the local network open, directly as well as through Codex's proxy"
130
+ : network === "none" ? "and no network (the job's shell has none)"
131
+ : "and the job's own network";
132
+ return `runs this one command with write access anywhere you can write, outside its worktree too, but still unable to read or write the credential stores relay denies (~/.ssh, ~/.aws, ~/.gnupg, ~/.netrc, Codex's login), ${net}. This is not full access, but writing anywhere in your home directory (LaunchAgents, shell startup files, other repositories, relay's own state) still acts with your authority`;
133
+ }
134
+ /** What consenting to a Codex job's local network does (grant.local_network; session.ts localNetworkConsent). */
135
+ export const LOCAL_NETWORK_EFFECT = "lets this job's shell reach every service listening on this Mac's loopback and on the local network (LAN), sshd and screen sharing included, with your account's reach, loopback directly as well as through Codex's network proxy; and lets it listen on every interface, so devices on your local network or tailnet can connect to servers it starts; for the rest of the job. Without it the job keeps internet access through the proxy, and nothing local";
136
+ /**
137
+ * What allowing a harness's own check of a path does (kind "path", Copilot's "Access paths outside
138
+ * trusted directories"): the agent goes on with what it asked for, reading or writing there as far
139
+ * as relay can tell, and relay's sandbox, unchanged, decides whether that succeeds. Reads are broad
140
+ * in that sandbox (src/confine/seatbelt.ts), so an allowed read outside relay's own places happens,
141
+ * and the effect says so plainly (review r_a74ec0a8 C1); writes stay where the turn may write. The
142
+ * path itself is the request's `wants` and its `in_directory` (the directory holding them all, for several).
143
+ */
144
+ function pathEffect(detail, n) {
145
+ const access = pathAccessOf({ detail });
146
+ const name = n?.target && isTarget(n.target) ? targetDef(n.target).name : "the agent";
147
+ const reads = "relay's sandbox allows reads everywhere except relay's own directories, its config and install files, and its API key files, so the read succeeds anywhere else";
148
+ const writes = "a write outside the job's worktree, its granted directories and its temporary directory still fails";
149
+ if (access === "read")
150
+ return `lets ${name} proceed to read the path it names; ${reads}, and allowing this does not widen the sandbox`;
151
+ if (access === "write")
152
+ return `lets ${name} proceed to write the path it names; relay's sandbox still decides what it can touch, and allowing this does not widen it: ${writes}`;
153
+ return `lets ${name} proceed to read or write the path it names (relay cannot tell which, and takes it as writing); ${reads}, ${writes}, and allowing this does not widen the sandbox`;
154
+ }
155
+ /**
156
+ * Whether a request can be allowed for this one action only, never for the rest of the job:
157
+ * environment consent (this turn only), and a Codex command asking for access added to its sandbox
158
+ * (codex-app.ts commandAsk).
159
+ */
160
+ export function onceOnly(r) {
161
+ return r.kind === "env" || r.kind === "escalation" || detailOf(r).once_only === true;
162
+ }
163
+ /** Whether the request comes from an agent inside relay's own sandbox, where allowing it lifts nothing. */
164
+ export function insideRelaySandbox(r) {
165
+ return detailOf(r).confined === true;
166
+ }
167
+ /**
168
+ * Whether a command that asked while in its sandbox would stay there if allowed: only under relay's
169
+ * own settings, and only where no organisation-managed Claude Code settings were found. With the
170
+ * user's settings loaded (child_settings "inherit"), or managed ones (which outrank relay's), their
171
+ * sandbox exclusions could let it run outside.
172
+ */
173
+ export function staysSandboxed(askedSandboxed, childSettings, managed) {
174
+ return askedSandboxed === true && childSettings === "isolated" && managed === null;
175
+ }
176
+ /**
177
+ * What a Claude agent is told when relay refuses its command request under the never floor
178
+ * (requestApproval): Claude command approvals are not available there at all, whatever the request
179
+ * says about its sandbox.
180
+ */
181
+ export const CLAUDE_COMMAND_REFUSAL = "never: Claude command approvals are unavailable under the never floor, so this request was refused and nobody was asked. " +
182
+ "Continue with the work your sandbox permits, report what you needed (under Open issues, or in your final message), or have the root session or the person arrange the work another supported way.";
183
+ export function requestView(r) {
184
+ const n = getNode(r.node_id);
185
+ const detail = detailOf(r);
186
+ // The access of the turn that asked, which can be narrower than the session's.
187
+ const access = typeof detail.access === "string" ? detail.access : n?.mode;
188
+ const sandboxed = Boolean(n) && staysSandboxed(detail.sandboxed, runConfig(n.run_id).child_settings, managedSettings());
189
+ // An agent inside relay's own sandbox asks for something within it: allowing it lifts nothing.
190
+ const escalation = r.kind === "escalation" ? escalationDetail(r.detail_json) : null;
191
+ const effect = escalation ? escalationEffect(escalation.escalation)
192
+ : r.kind === "env" ? `${effectOf(r.kind, access, sandboxed, n)}. Execution and standing passes (names only): ${JSON.stringify(detail)}`
193
+ : r.kind === "path" ? pathEffect(detail, n)
194
+ : insideRelaySandbox(r) ? "lets it go ahead inside relay's sandbox, which stays on whatever you decide" : effectOf(r.kind, access, sandboxed, n, detail.adds_to_sandbox === true, detail.escalates_restricted || undefined);
195
+ return {
196
+ request_id: r.id, from: r.node_id, agent: n?.target, depth: n?.depth, session: access, task: r.kind === "env" ? "see the caller-supplied purpose in wants (untrusted)" : n?.task.replace(/\s+/g, " ").slice(0, 100),
197
+ ...(n?.target && !targetDef(n.target).qualified ? { agent_label: targetLabel(targetDef(n.target)) } : {}),
198
+ wants: r.summary, in_directory: detailCwd(r) ?? (n ? workCwd(n) : undefined), kind: r.kind, effect, ...(r.reason ? { reason: r.reason } : {}),
199
+ // Only the person may allow it (docs/extensions.md); the root agent may deny it.
200
+ ...(personOnly(r) ? { person_only: true } : {}),
201
+ ...(r.kind !== "env" && onceOnly(r) ? { once_only: r.kind === "escalation" ? "one replacement turn only; never a standing grant" : "allowed for this one command only, never for the rest of the job" } : {}),
202
+ waiting_s: Math.round((now() - r.created_at) / 1000),
203
+ ...(r.kind === "env" ? { environment: detail } : {}),
204
+ ...(escalation ? { required_decider: escalation.escalation.required_decider, request_digest: escalation.request_digest, escalation: escalation.escalation, ...(escalation.decision ? { decision_provenance: escalation.decision } : {}) } : {}),
205
+ ...(detail.never_hash ? { never_policy: { hash: detail.never_hash, version: detail.never_version, removed_builtins: detail.never_removed ?? [] } } : {}),
206
+ };
207
+ }
208
+ /**
209
+ * True once a job's web searches and fetches need not ask: it was granted the network up front,
210
+ * or a web request of its was allowed for the rest of the job. That approval covers the web tools
211
+ * only (WebSearch, WebFetch), never the sandbox's network for shell commands.
212
+ */
213
+ export function webGranted(nodeId) {
214
+ const n = getNode(nodeId);
215
+ if (!n)
216
+ return false;
217
+ if (sessionParams(n).grant?.network)
218
+ return true;
219
+ // Not for an agent in relay's own sandbox, for which relay holds each approval for the same request only (heldForJob).
220
+ if (n.target && isTarget(n.target) && !targetDef(n.target).capabilities.escalation)
221
+ return false;
222
+ return Boolean(db().prepare("SELECT 1 FROM requests WHERE node_id = ? AND kind = 'web' AND status = 'allowed' AND scope = 'job' LIMIT 1").get(nodeId));
223
+ }
224
+ /**
225
+ * Why the turn that asked can no longer be answered, or null while it is live: the turn is running,
226
+ * so is its session, and neither the run nor anything above the session has been cancelled. Read
227
+ * inside the transaction that files a request or applies a decision, so that nothing is filed or
228
+ * allowed for a turn that has ended.
229
+ */
230
+ export function turnGone(nodeId, turnId) {
231
+ if (turnId === null)
232
+ return "the request does not record which turn asked";
233
+ const ended = turnEnded(nodeId, turnId);
234
+ if (ended)
235
+ return ended;
236
+ return cancelledOver(getNode(nodeId));
237
+ }
238
+ function cancelledOver(n) {
239
+ if (getRun(n.run_id)?.status === "cancelled")
240
+ return "its run has been cancelled";
241
+ if (ancestors(n, { self: true }).some((a) => a.status === "cancelled"))
242
+ return "its work has been cancelled";
243
+ return null;
244
+ }
245
+ /**
246
+ * As turnGone, for a turn whose environment is being claimed (W9), which is live while it is still
247
+ * queued too: its worker claims the environment, with the person's consent to a one-turn request,
248
+ * as it picks the turn up, before the turn waits for a concurrency slot. A queued turn is live only
249
+ * while it is its session's next turn and the session is queued for it, as its worker leaves it.
250
+ */
251
+ export function claimGone(nodeId, turnId) {
252
+ if (turnId === null)
253
+ return "the request does not record which turn asked";
254
+ const t = getTurn(turnId);
255
+ if (t?.node_id !== nodeId || t.status !== "queued")
256
+ return turnGone(nodeId, turnId);
257
+ const n = getNode(nodeId);
258
+ if (n?.status !== "queued")
259
+ return `turn ${turnId} of ${nodeId} is not about to start (its session is ${n?.status ?? "gone"})`;
260
+ if (nextQueuedTurn(nodeId)?.id !== turnId)
261
+ return `turn ${turnId} of ${nodeId} is not its session's next turn`;
262
+ return cancelledOver(n);
263
+ }
264
+ /** The liveness a request of this kind needs: an environment claim's turn may still be queued (claimGone). */
265
+ const goneFor = (kind) => (kind === "env" ? claimGone : turnGone);
266
+ /**
267
+ * Why a file request touches what no job may change, or null: relay's control directory, its
268
+ * config files, its install record and backups (protected-config.ts, as the sandboxes protect
269
+ * them), another job's worktree, and what decides which API key relay hands a key-only target.
270
+ * The same places for a harness's own check of a path (`what` "reach"), which nobody is asked
271
+ * about, and for it also any directory holding relay's control directory or the worktrees' directory.
272
+ */
273
+ /**
274
+ * Whether `p` is in the consult directory of the thread asking (caller.ts newConsultDir), not in the
275
+ * parent all of them share. It lets a path in, so compared exactly (inside, not insideAnyCase): on a
276
+ * disk that tells case apart, a sibling named in another case is not the thread's own.
277
+ */
278
+ function ownConsult(node, p) {
279
+ const cwd = workCwd(node);
280
+ return insideAnyCase(cwd, consultHome()) && foldedPath(cwd) !== foldedPath(consultHome()) && inside(p, cwd);
281
+ }
282
+ export function offLimits(node, paths, what = "change") {
283
+ const which = what === "change" ? "no job may change" : "no approval lets a job reach";
284
+ const own = node.worktree;
285
+ const installed = configProtection().paths;
286
+ const codex = relayCodexProtected(node.run_id ? runConfig(node.run_id) : undefined);
287
+ for (const p of paths.map((x) => path.resolve(workCwd(node), x))) {
288
+ const protectedCodex = [...codex.homes, ...codex.stores].find((x) => overlapsPart(p, x.path));
289
+ if (protectedCodex)
290
+ return `${p} overlaps ${protectedCodex.what} (${protectedCodex.path}), which ${which}`;
291
+ const config = touchesConfig(p);
292
+ if (config)
293
+ return `${p} ${foldedPath(p) === foldedPath(config) ? "is" : "holds"} relay's own config file ${config}, which ${which}`;
294
+ const record = installed.find((c) => pathOverlaps(p, c) || insideAnyCase(p, c) || insideAnyCase(c, p));
295
+ if (record)
296
+ return `${p} overlaps relay's config or install files (${record}), which ${which}`;
297
+ // What relay runs outside every sandbox (caller.ts grantPathProblem, review r_0c11d860 X1): never
298
+ // a job's to change. Reading it stays possible: a read job may look at relay's own code.
299
+ const part = what === "change" ? relayInstallation().find((x) => overlapsPart(p, x.path)) : undefined;
300
+ if (part)
301
+ return `${p} overlaps ${part.what} (${part.path}), which relay runs outside any sandbox, and which ${which}`;
302
+ // Nor a directory on relay's PATH, or anything in one: a program put there would be run outside any sandbox.
303
+ const onPath = what === "change" ? relayPathDirs().find((d) => insideAnyCase(p, d) || insideAnyCase(d, p)) : undefined;
304
+ if (onPath)
305
+ return `${p} is on or holds ${onPath}, a directory on relay's PATH, where a program put there would be run outside any sandbox, and which ${which}`;
306
+ // The consults' directories too, but for the asking thread's own: what is changed there is where
307
+ // a later consult of any conversation could look (review r_f1c46bd4 X2).
308
+ if (insideAnyCase(p, relayHome()) || (insideAnyCase(p, consultHome()) && !ownConsult(node, p)) || (insideAnyCase(p, worktreesHome()) && !(own && insideAnyCase(p, own))))
309
+ return `${p} is inside relay's own directories, which ${which}`;
310
+ // A path check reaches what lies below the path too: a directory holding relay's control
311
+ // directory or the worktrees' directory (and so other jobs' worktrees) is refused as they are
312
+ // (review r_a74ec0a8 C2). The config, install and key checks look both ways already.
313
+ const holds = what === "reach" ? [relayHome(), worktreesHome(), consultHome()].find((d) => insideAnyCase(d, p)) : undefined;
314
+ if (holds)
315
+ return `${p} holds relay's own directories (${holds}), which ${which}`;
316
+ }
317
+ // Nor what decides which API key relay hands a key-only target (core/api-keys.ts keyAuthority),
318
+ // as no grant may cover it; and while relay cannot tell where that is, nothing outside the job's own.
319
+ const asked = paths.map((x) => path.resolve(workCwd(node), x));
320
+ const keys = keyAuthority();
321
+ for (const p of asked) {
322
+ const key = keys.dirs.find(([, d]) => pathOverlaps(p, d) || insideAnyCase(p, d) || insideAnyCase(d, p));
323
+ if (key)
324
+ return `${p} overlaps ${key[0]} (${key[1]}), which ${which}`;
325
+ }
326
+ const outside = asked.find((p) => !(own && insideAnyCase(p, own)));
327
+ if (keys.problem && outside)
328
+ return `relay cannot load its local config, so it cannot tell which directories decide its API keys, and lets no ${what === "change" ? "job change" : "approval reach"} ${outside} until that is fixed: ${keys.problem}`;
329
+ return null;
330
+ }
331
+ export function deciderOf(decidedBy) {
332
+ if (decidedBy === "user")
333
+ return "user-dialog";
334
+ if (decidedBy?.startsWith("user, through the host's permission prompt"))
335
+ return "user-confirm";
336
+ if (decidedBy === "terminal")
337
+ return "terminal";
338
+ if (decidedBy?.startsWith("root session"))
339
+ return decidedBy.includes("confirmed") ? "root-confirmed" : "root";
340
+ return "other";
341
+ }
342
+ const FOR_AGENT = {
343
+ "user-dialog": "by the user in relay's approval dialog",
344
+ "user-confirm": "by the user, in the root session's permission prompt",
345
+ terminal: "from a terminal (relay approve or relay deny)",
346
+ root: "by the root session supervising this run, not by the user",
347
+ "root-confirmed": "by the root session supervising this run, which says the user confirmed it",
348
+ };
349
+ /**
350
+ * Who decided a request, in words for the agent that asked (relay's note to it). Codex tells its
351
+ * agent that the user rejected or approved whoever decided, so relay says who did. Given the
352
+ * decision, a terminal's is named by its command: an allow is relay approve's, a denial relay
353
+ * deny's (relay approve allows no person-only request, so only relay deny can refuse one there).
354
+ */
355
+ export const deciderForAgent = (decidedBy, allowed) => deciderOf(decidedBy) === "terminal" && allowed !== undefined ? `from a terminal (${allowed ? "relay approve" : "relay deny"})` : FOR_AGENT[deciderOf(decidedBy)];
356
+ /**
357
+ * Files an approval request for a launched agent and waits for the root session's decision.
358
+ * The agent is blocked meanwhile, so its concurrency slot is lent. No answer within the timeout
359
+ * counts as a denial.
360
+ */
361
+ export async function requestApproval(nodeId, turnId, ask, shouldAbort = () => false, onTick) {
362
+ const node = getNode(nodeId);
363
+ if (!node)
364
+ return { allow: false, note: "unknown agent" };
365
+ const cfg = runConfig(node.run_id);
366
+ // Keep relay's established, person-facing reason for its own protected resources.
367
+ // The cumulative never floor below additionally covers historical/configured resources.
368
+ if (ask.kind === "file" || ask.kind === "path") {
369
+ const off = offLimits(node, ask.paths ?? [], ask.kind === "path" ? "reach" : "change");
370
+ if (off)
371
+ return { allow: false, note: off };
372
+ }
373
+ let never;
374
+ try {
375
+ never = checkpointNever(node.run_id, "approval");
376
+ // Every Claude command request is refused under the floor, one that would stay in its sandbox
377
+ // (detail.sandboxed) as well as one asking to leave it, so the note claims neither, and offers
378
+ // no restart overlay (those are Codex-only, restart-overlay.ts).
379
+ if (node.target === "claude" && ask.kind === "command" && neverFloorApplies("claude", cfg))
380
+ return { allow: false, note: CLAUDE_COMMAND_REFUSAL };
381
+ const why = neverApprovalProblem(never, ask.kind, ask.paths ?? [], workCwd(node), pathAccessOf(ask));
382
+ if (why)
383
+ return { allow: false, note: why };
384
+ }
385
+ catch (err) {
386
+ return { allow: false, note: err.message };
387
+ }
388
+ if (!escalationEnabled(cfg))
389
+ return { allow: false, note: "approval requests are turned off; report what you needed under Open issues" };
390
+ // Only a job or consult in the middle of a turn can ask. This also stops an agent from parking
391
+ // itself in a pending request to hold a slot or stall its own timeout. The exception is the owning
392
+ // root's broker asking the person to release environment values to a turn its worker is picking
393
+ // up, before the turn waits for a slot (claimGone): no agent runs then, and it holds no slot to lend.
394
+ const turnOver = goneFor(ask.kind);
395
+ const turn = getTurn(turnId);
396
+ const started = turn?.status === "running" || (ask.kind === "env" && turn?.status === "queued");
397
+ if (!turn || turn.node_id !== nodeId || !started)
398
+ return { allow: false, note: "only an agent in the middle of a turn can ask for approval" };
399
+ // A read-only session may ask to reach the web or to run a command, never to change files.
400
+ // What decides is the turn's access, not the session's: a discussion turn on a write job's session is read-only.
401
+ // Consent to extensions and a call of an extension's tool are not changes to files either; a
402
+ // harness's own check of a path is asked only for a path it would read (askableReadOnly).
403
+ if (turn.access === "read" && !askableReadOnly(ask))
404
+ return { allow: false, note: ask.kind === "path" ? `this turn is read-only, and ${pathAccessOf(ask) === "write" ? "the agent would write there" : "relay cannot tell that the agent would only read there"}` : "this turn is read-only" };
405
+ // Relay's control directory and other jobs' worktrees are never a job's to change, so such a
406
+ // request is refused here and nobody is asked. (An approved command is another matter: it runs
407
+ // unconfined, which is why approving one means trusting it.)
408
+ // Relay's own config files too, by either name of a linked one, and any directory holding one:
409
+ // its config.json and mcp.json say what agents may be given and which servers run outside their
410
+ // sandboxes; its install record and backups (DM8) too. On macOS a name in another case is the
411
+ // same file (insideAnyCase).
412
+ // A harness's own check of a path (kind "path") is refused for the same places, read or write:
413
+ // allowing it would not open them (relay's sandbox decides), but nobody is asked about them.
414
+ if (ask.kind === "file" || ask.kind === "path") {
415
+ const off = offLimits(node, ask.paths ?? [], ask.kind === "path" ? "reach" : "change");
416
+ if (off)
417
+ return { allow: false, note: off };
418
+ }
419
+ // One request at a time per agent. An agent can issue several tool calls at once (parallel web
420
+ // fetches, say); the later ones wait their turn, and are answered at once if an earlier
421
+ // "rest of the job" approval has meanwhile covered them.
422
+ // A request waiting its turn is filed only while the turn that asked is still live, checked in
423
+ // the same transaction, so that nothing is filed after the turn has ended and been cleaned up;
424
+ // and only while the call that asks is there: one cancelled, or whose connection has closed,
425
+ // files nothing, also when the request ahead of it has closed meanwhile (review X1/C28, audit A9).
426
+ const detail = ask.detail;
427
+ const covered = () => ask.kind === "web" ? webGranted(nodeId)
428
+ : ask.kind === "mcp" && typeof detail?.server === "string" && typeof detail?.tool === "string"
429
+ && mcpHeldForJob(nodeId, detail.server, detail.tool);
430
+ const escalation = ask.kind === "escalation" ? escalationDetail(JSON.stringify(ask.detail)) : null;
431
+ if (ask.kind === "escalation" && !escalation)
432
+ return { allow: false, note: "missing canonical escalation request" };
433
+ const id = escalation?.escalation.request_id ?? newId("request");
434
+ const queuedAt = now();
435
+ for (;;) {
436
+ if (shouldAbort())
437
+ return { allow: false, note: "the call that asked was cancelled or its turn is over" };
438
+ if (!hasPending(nodeId)) {
439
+ try {
440
+ never = checkpointNever(node.run_id, "approval");
441
+ }
442
+ catch (err) {
443
+ return { allow: false, note: err.message };
444
+ }
445
+ }
446
+ const filed = tx(() => {
447
+ const gone = turnOver(nodeId, turnId);
448
+ if (gone)
449
+ return gone;
450
+ // Another process may have grown the floor while this request waited in the queue.
451
+ never = readNeverFloor(node.run_id) ?? never;
452
+ const no = neverApprovalProblem(never, ask.kind, ask.paths ?? [], workCwd(node), pathAccessOf(ask));
453
+ if (no)
454
+ return no;
455
+ if (escalation) {
456
+ const why = escalationRequestProblem(escalation, { id, run_id: node.run_id, node_id: nodeId, turn_id: turnId, summary: ask.summary }, never);
457
+ if (why)
458
+ return why;
459
+ }
460
+ if (covered())
461
+ return "covered";
462
+ if (hasPending(nodeId))
463
+ return false;
464
+ db().prepare("INSERT INTO requests (id, run_id, node_id, turn_id, kind, summary, reason, detail_json, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)")
465
+ .run(id, node.run_id, nodeId, turnId, ask.kind, ask.summary, ask.reason ?? null, JSON.stringify({ cwd: workCwd(node), access: turn.access, ...(ask.paths?.length ? { paths: ask.paths } : {}), ...(ask.detail ?? {}), never_hash: never.hash, never_version: never.version, never_removed: never.removed }), now());
466
+ return true;
467
+ });
468
+ if (filed === "covered")
469
+ return { allow: true };
470
+ if (filed === true)
471
+ break;
472
+ if (filed)
473
+ return { allow: false, note: `the turn that asked is over (${filed})` };
474
+ if (now() - queuedAt > cfg.approval_timeout_s * 1000)
475
+ return { allow: false, note: "an earlier request from you was never answered" };
476
+ await sleep(250);
477
+ }
478
+ if (cfg.desktop_notifications && process.platform === "darwin") {
479
+ const text = `${node.target ? targetLabel(targetDef(node.target), node.target) : "agent"} ${nodeId} wants: ${ask.summary}`.replace(/\s+/g, " ").replace(/["\\]/g, "'").slice(0, 200);
480
+ // relay approve refuses a person-only request (commandRefusal), so the notification does not offer it.
481
+ const how = personOnly({ kind: ask.kind, node_id: nodeId, detail_json: getRequest(id)?.detail_json }) ? `only you can allow ${id}: relay's question, or confirm` : `relay approve ${id}`;
482
+ try {
483
+ spawn("/usr/bin/osascript", ["-e", `display notification "${text}" with title "relay: approval needed" subtitle "${how}"`], { detached: true, stdio: "ignore" }).unref();
484
+ }
485
+ catch {
486
+ // A missing notifier must not affect the request.
487
+ }
488
+ }
489
+ const giveBack = lendSlot(nodeId);
490
+ if (ask.kind === "env")
491
+ environmentRequestRedactors.set(id, redactor());
492
+ const start = now();
493
+ const deadline = Math.min(start + cfg.approval_timeout_s * 1000, escalation?.escalation.approval_deadline_ms ?? Infinity);
494
+ let lastTick = start;
495
+ const poll = registryPoll();
496
+ try {
497
+ for (;;) {
498
+ if (onTick && now() - lastTick >= 15000) {
499
+ lastTick = now();
500
+ onTick(now() - start);
501
+ }
502
+ const r = getRequest(id);
503
+ // Cancellation/expiry must win even if an allow raced the call's disappearance.
504
+ if (escalation && (shouldAbort() || now() >= deadline)) {
505
+ db().prepare("UPDATE requests SET status = 'expired', decided_at = ? WHERE id = ? AND status = 'pending'").run(now(), id);
506
+ return { allow: false, note: "escalation call cancelled or approval deadline expired" };
507
+ }
508
+ if (r.status === "allowed") {
509
+ try {
510
+ const effective = checkpointNever(node.run_id, "approval");
511
+ const why = neverApprovalProblem(effective, ask.kind, ask.paths ?? [], workCwd(node), pathAccessOf(ask));
512
+ if (why)
513
+ return { allow: false, note: why };
514
+ if (effective.hash !== never.hash)
515
+ return { allow: false, note: "never policy changed after the decision; ask again against the current floor" };
516
+ }
517
+ catch (err) {
518
+ return { allow: false, note: err.message };
519
+ }
520
+ return { allow: true, note: r.note ?? undefined, forJob: r.scope === "job", deciderNote: r.note ?? undefined, decider: deciderForAgent(r.decided_by, true) };
521
+ }
522
+ if (r.status === "denied")
523
+ return { allow: false, note: r.note ?? "denied", deciderNote: r.note ?? undefined, decider: deciderForAgent(r.decided_by, false) };
524
+ if (r.status === "expired")
525
+ return { allow: false, note: "the request was closed without an answer" };
526
+ // The turn is checked on every look, not only when the request was filed: once it has ended
527
+ // nobody may answer for it, and the request is closed.
528
+ const gone = shouldAbort() ? "the job was cancelled or its turn is over" : turnOver(nodeId, turnId);
529
+ if (gone || now() > deadline) {
530
+ db().prepare("UPDATE requests SET status = 'expired', decided_at = ? WHERE id = ? AND status = 'pending'").run(now(), id);
531
+ return { allow: false, note: gone ?? `nobody answered within ${cfg.approval_timeout_s}s` };
532
+ }
533
+ // The next look within 250 ms. A decision is recorded by another process (the root's server, a
534
+ // terminal), whose commit to the registry brings a quick look at the request alone; once it is
535
+ // no longer pending, the full look above takes it at once.
536
+ const next = now() + 250;
537
+ while (await poll.nap(next - now()))
538
+ if (getRequest(id)?.status !== "pending")
539
+ break;
540
+ }
541
+ }
542
+ finally {
543
+ environmentRequestRedactors.delete(id);
544
+ giveBack();
545
+ }
546
+ }
547
+ /**
548
+ * Whether the root allowed this same request (approvalKey: kind, command, directory, files) for the
549
+ * rest of the job, earlier in this job. For agents with no job-scoped approval of their own, whose
550
+ * every later matching request relay then answers itself, allow-once.
551
+ */
552
+ export function heldForJob(nodeId, ask) {
553
+ const node = getNode(nodeId);
554
+ if (!node)
555
+ return false;
556
+ try {
557
+ const never = checkpointNever(node.run_id, "approval");
558
+ if (neverApprovalProblem(never, ask.kind, ask.paths ?? [], workCwd(node), pathAccessOf(ask)))
559
+ return false;
560
+ }
561
+ catch {
562
+ return false;
563
+ }
564
+ const want = approvalKey(ask, workCwd(node));
565
+ const rows = db().prepare("SELECT summary, detail_json FROM requests WHERE node_id = ? AND status = 'allowed' AND scope = 'job' AND kind = ?")
566
+ .all(nodeId, ask.kind);
567
+ return rows.some((r) => {
568
+ try {
569
+ const detail = JSON.parse(r.detail_json ?? "{}");
570
+ return approvalKey({ kind: ask.kind, summary: r.summary, paths: detail.paths, detail }, workCwd(node)) === want;
571
+ }
572
+ catch {
573
+ return false;
574
+ }
575
+ });
576
+ }
577
+ /**
578
+ * Whether the person allowed a call of this tool of this extension server for the rest of the job,
579
+ * earlier in it: then later calls of the same tool go ahead without asking, whatever their
580
+ * arguments (the effect the person was shown says so).
581
+ */
582
+ export function mcpHeldForJob(nodeId, server, tool) {
583
+ const rows = db().prepare("SELECT detail_json FROM requests WHERE node_id = ? AND kind = 'mcp' AND status = 'allowed' AND scope = 'job'").all(nodeId);
584
+ return rows.some((r) => {
585
+ try {
586
+ const d = JSON.parse(r.detail_json ?? "{}");
587
+ return d.server === server && d.tool === tool;
588
+ }
589
+ catch {
590
+ return false;
591
+ }
592
+ });
593
+ }
594
+ /** Closes requests nobody can act on any more: the asking turn has ended or its job is no longer running. */
595
+ export function expireRequests(nodeId) {
596
+ db().prepare("UPDATE requests SET status = 'expired', decided_at = ? WHERE node_id = ? AND status = 'pending'").run(now(), nodeId);
597
+ }
598
+ export function decide(id, allow, by, note, scope = "once", authentication) {
599
+ // Persist additions independently: a rejected/stale decision must never roll back the floor.
600
+ let never;
601
+ if (allow) {
602
+ const pending = getRequest(id);
603
+ if (pending) {
604
+ try {
605
+ never = checkpointNever(pending.run_id, "decision");
606
+ }
607
+ catch (err) {
608
+ return { error: err.message };
609
+ }
610
+ }
611
+ }
612
+ // Claiming the pending request and applying what follows from it happen together. A decision
613
+ // that loses the race to another one changes nothing and says so.
614
+ return tx(() => {
615
+ const r = getRequest(id);
616
+ if (!r)
617
+ return { error: `unknown request ${id}` };
618
+ if (r.status !== "pending")
619
+ return { error: `request ${id} is already ${r.status}` };
620
+ const escalation = r.kind === "escalation" ? escalationDetail(r.detail_json) : null;
621
+ if (r.kind === "escalation") {
622
+ if (!escalation)
623
+ return { error: "missing canonical escalation request" };
624
+ const problem = escalationRequestProblem(escalation, r, allow ? never : undefined)
625
+ ?? authenticateEscalationDecision(escalation, authentication, allow);
626
+ if (problem)
627
+ return { error: problem };
628
+ if (scope !== "once")
629
+ return { error: "escalation consent covers one replacement turn only; it cannot create a standing grant" };
630
+ }
631
+ if (allow && never) {
632
+ try {
633
+ assertNeverCurrent(r.run_id, never.hash);
634
+ }
635
+ catch (err) {
636
+ return { error: err.message };
637
+ }
638
+ const detail = JSON.parse(r.detail_json ?? "{}");
639
+ const node = getNode(r.node_id);
640
+ const why = neverApprovalProblem(never, r.kind, detail.paths ?? [], node ? workCwd(node) : detail.cwd, detail.path_access);
641
+ if (why)
642
+ return { error: why };
643
+ if (detail.never_hash && detail.never_hash !== never.hash) {
644
+ db().prepare("UPDATE requests SET status = 'expired', decided_at = ? WHERE id = ? AND status = 'pending'").run(now(), id);
645
+ return { error: `request ${id} has a stale never policy hash; nothing was allowed. Ask again against the current cumulative floor.` };
646
+ }
647
+ }
648
+ if (allow && personOnly(r) && !["user-dialog", "user-confirm"].includes(deciderOf(by)))
649
+ return { error: "only the user through a qualified dialog or confirm can allow this person-only request" };
650
+ if (scope !== "once" && onceOnly(r))
651
+ return { error: r.kind === "env" ? "environment consent covers this turn only" : `request ${id} can be allowed for this one command only: a Codex command asking for access added to its sandbox is never allowed for the rest of the job. Nothing was decided; allow it once or deny it.` };
652
+ // Only the turn that asked can be answered. A request left pending after it ended (filed in
653
+ // the moment before cleanup, or by a handler that outlived its connection) is closed, and
654
+ // nothing follows from it: a "rest of the job" approval must not reach the job's later turns.
655
+ const gone = goneFor(r.kind)(r.node_id, r.turn_id);
656
+ if (gone) {
657
+ db().prepare("UPDATE requests SET status = 'expired', decided_at = ? WHERE id = ? AND status = 'pending'").run(now(), id);
658
+ return { error: `request ${id} can no longer be decided: ${gone}. Nothing was allowed; the agent can ask again in a later turn.` };
659
+ }
660
+ const at = now();
661
+ const savedNote = note === undefined ? null : (environmentRequestRedactors.get(id)?.(note) ?? (escalation ? redactor()(note) : note));
662
+ if (escalation?.overlay) {
663
+ const b = escalation.overlay;
664
+ const overlay = getOverlay(r.run_id, b.id);
665
+ if (overlay.request.escalation?.requestId !== id || overlay.request.escalation.digest !== escalation.request_digest)
666
+ throw new Error("overlay approval binding changed");
667
+ const decision = { decisionId: id, decidedBy: authentication.route === "owning-run-root" ? escalation.escalation.root.session_identity : by,
668
+ route: authentication.route === "owning-run-root" ? "supervisor" : "person", at, ...(savedNote === null ? {} : { note: savedNote }) };
669
+ if (allow)
670
+ allowOverlayInTransaction(r.run_id, b.id, b.digest, decision);
671
+ else
672
+ settleOverlayRequestInTransaction(r.run_id, b.id, b.digest, "denied", decision);
673
+ }
674
+ const claimed = db().prepare("UPDATE requests SET status = ?, decided_by = ?, note = ?, scope = ?, decided_at = ? WHERE id = ? AND status = 'pending'")
675
+ .run(allow ? "allowed" : "denied", by, savedNote, allow ? scope : null, at, id);
676
+ if (Number(claimed.changes) !== 1)
677
+ return { error: `request ${id} was decided by someone else at the same moment` };
678
+ if (escalation) {
679
+ // Actual authenticated route, not the free-text by label. One transaction owns both.
680
+ escalation.decision = { route: authentication.route, root: escalation.escalation.root, decided_by: by, at, note: savedNote, request_digest: escalation.request_digest };
681
+ db().prepare("UPDATE requests SET detail_json = ? WHERE id = ?").run(JSON.stringify(escalation), id);
682
+ }
683
+ // "For the rest of the job" on a web request is held here, in the request's scope: the job's
684
+ // later web searches and fetches are allowed without asking (webGranted), and its grant is not
685
+ // widened, so its shell commands get no network from it. An agent in relay's own sandbox has
686
+ // relay answer each later request that is the same instead (heldForJob).
687
+ return { request_id: id, decision: allow ? "allowed" : "denied", decided_by: by, ...(allow && scope === "job" ? { scope: "rest of the job" } : {}), from: r.node_id, wants: r.summary };
688
+ });
689
+ }
690
+ const elicitation = (requestId) => db().prepare("SELECT * FROM elicitations WHERE request_id = ?").get(requestId);
691
+ /**
692
+ * Takes the right to put a request to the user, for the relay server holding `token`. Refused when
693
+ * the user already answered or closed the question, or a live server is asking now. A question
694
+ * left open by a server that has gone, or one that failed or was withdrawn under another server,
695
+ * may be asked again.
696
+ */
697
+ export function claimElicitation(requestId, token) {
698
+ return tx(() => {
699
+ const row = elicitation(requestId);
700
+ const mine = () => db().prepare("INSERT OR REPLACE INTO elicitations (request_id, token, pid, pid_start, asked_at) VALUES (?, ?, ?, ?, ?)")
701
+ .run(requestId, token, process.pid, procStart(process.pid), now());
702
+ if (!row) {
703
+ mine();
704
+ return true;
705
+ }
706
+ if (row.token === token)
707
+ return false;
708
+ const abandoned = row.outcome === null && !sameProcess(row.pid, row.pid_start);
709
+ if (abandoned || row.reading === "error" || row.reading === "withdrawn") {
710
+ mine();
711
+ return true;
712
+ }
713
+ return false;
714
+ });
715
+ }
716
+ export function endElicitation(requestId, token, outcome, reading) {
717
+ db().prepare("UPDATE elicitations SET outcome = ?, reading = ?, ended_at = ? WHERE request_id = ? AND token = ?").run(outcome, reading, now(), requestId, token);
718
+ }
719
+ /**
720
+ * "asking": the question is on the user's screen now. "dismissed": they closed it without
721
+ * answering (only where that is known to be a person: Esc in interactive Claude Code).
722
+ * "unattributed": the host answered with something that decides nothing and that relay cannot
723
+ * attribute to a person (a Codex decline or cancel, an answer that does not fit the form); `host`
724
+ * is what it answered.
725
+ */
726
+ export function elicitationState(requestId) {
727
+ const row = elicitation(requestId);
728
+ if (!row)
729
+ return null;
730
+ if (row.outcome === null)
731
+ return sameProcess(row.pid, row.pid_start) ? "asking" : null;
732
+ if (row.reading === "unattributed")
733
+ return { unattributed: row.outcome };
734
+ return row.reading === "dismissed" ? "dismissed" : null;
735
+ }
736
+ /** Kept for diagnosis in the control directory: what each host answered, how fast, and how relay read it. */
737
+ export function logElicitation(entry) {
738
+ // Diagnostics only: a failed write is not the request's failure. Rotated at log_max_mb.
739
+ appendLog(path.join(relayHome(), "elicitation.log"), JSON.stringify({ at: new Date().toISOString(), ...entry }) + "\n");
740
+ }