@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,182 @@
1
+ // Root-owned selection. Diagnostic text contains names and fixed reasons only.
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { relayCodexHome } from "./config.js";
5
+ import { TARGETS, targetDef, targetLabel } from "../targets/index.js";
6
+ import { recognizedSecretShape } from "./secrets.js";
7
+ export const ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
8
+ /** Changes after startup confer no launch authority. Workers receive a root-selected environment. */
9
+ export const capturedRootEnvironment = Object.freeze({ ...process.env });
10
+ // USER, LOGNAME and SHELL are who and how, not secrets. Claude Code 2.1.303 needs USER to find its
11
+ // keychain login (`claude auth status` reports loggedIn: false without it; checked live 2026-10-21).
12
+ export const RUNTIME_NAMES = ["PATH", "USER", "LOGNAME", "SHELL", "LANG", "LANGUAGE", "LC_ALL", "LC_CTYPE", "LC_COLLATE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "TZ", "TERM", "COLORTERM", "NO_COLOR", "CLICOLOR", "CLICOLOR_FORCE"];
13
+ export const PROXY_NAMES = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"];
14
+ const HOST_MARKERS = ["CLAUDE_CODE_DESKTOP_APP_VERSION", "CLAUDE_AGENT_SDK_VERSION"];
15
+ export const BACKEND_OWNED_NAMES = ["HOME", "TMPDIR", "TMP", "TEMP", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "XDG_CONFIG_HOME", "pnpm_config_package_import_method", "NODE_OPTIONS", "LD_PRELOAD", "SEATBELT_PROFILE", "BUILD_SANDBOX"];
16
+ export function backendOwnedEnvironmentName(name) {
17
+ return name.startsWith("RELAY_") || name.startsWith("DYLD_") || name.startsWith("LD_") || name.startsWith("XDG_") || name === "NODE_USE_ENV_PROXY" || BACKEND_OWNED_NAMES.includes(name);
18
+ }
19
+ /** Machine-readable backend guards, reused by config and the selection path. */
20
+ export const BACKEND_ENVIRONMENT_SCRUBS = {
21
+ claude: /^(?:CLAUDECODE|CLAUDE_AUTO_BACKGROUND_TASKS|CLAUDE_AGENT_SDK_VERSION)$|^CLAUDE_CODE_(?!(?:USE_|OAUTH_TOKEN|SKIP_))/,
22
+ codex: /(?!)/,
23
+ copilot: /^(?:COPILOT_(?!GITHUB_TOKEN$)|GITHUB_COPILOT_)/,
24
+ gemini: /^(GEMINI_|OTEL_|CLOUDSDK_|OAUTH_CALLBACK_|GOOGLE_CLOUD_|GOOGLE_GENAI_USE_)|^(GOOGLE_API_KEY|GOOGLE_APPLICATION_CREDENTIALS|CLOUD_SHELL|SANDBOX|SEATBELT_PROFILE|BUILD_SANDBOX|DEBUG|DEBUG_MODE|NO_BROWSER)$/,
25
+ grok: /^(GROK_|XAI_|OTEL_)|^SENTRY_DSN$/,
26
+ };
27
+ export function effectiveChildEnv(config, target) {
28
+ const root = config.child_env ?? {};
29
+ const own = config.targets[target]?.child_env ?? {};
30
+ const union = (key) => [...new Set([...(root[key] ?? []), ...(own[key] ?? [])])];
31
+ return { policy: own.policy ?? root.policy ?? "allowlist", pass: union("pass"), drop: union("drop"), request: union("request") };
32
+ }
33
+ export function mandatoryEnvironmentReason(target, config, name, rootEnv = {}) {
34
+ if (backendOwnedEnvironmentName(name))
35
+ return "backend-owned control";
36
+ if (HOST_MARKERS.includes(name) || name === "CODEX_INTERNAL_ORIGINATOR_OVERRIDE" || name === "CLAUDE_CODE_MESSAGING_SOCKET" || name === "CLAUDE_CODE_MESSAGING_TOKEN")
37
+ return "host-session identity";
38
+ const def = targetDef(target);
39
+ const auth = config.targets[target]?.child_auth ?? config.child_auth;
40
+ for (const other of TARGETS) {
41
+ if (!other.credentialEnv.test(name))
42
+ continue;
43
+ if (auth === "login" || other.id !== target && (other.vendor === null || def.vendor === null || other.vendor !== def.vendor))
44
+ return "mandatory vendor authentication guard";
45
+ }
46
+ if (auth === "login" && def.loginEnv?.test(name))
47
+ return "mandatory login authentication guard";
48
+ if (HOST_MARKERS.some((m) => Boolean(rootEnv[m])) && (config.targets.claude?.child_auth ?? config.child_auth) === "login" && targetDef("claude").endpointEnv.test(name))
49
+ return "host-session endpoint";
50
+ if (target !== "claude" && (name === "CLAUDECODE" || name.startsWith("CLAUDE_CODE_")))
51
+ return "foreign harness session control";
52
+ if (BACKEND_ENVIRONMENT_SCRUBS[target].test(name))
53
+ return "mandatory backend guard";
54
+ return null;
55
+ }
56
+ export function validatedProxy(name, value) {
57
+ if (/^no_proxy$/i.test(name)) {
58
+ if (!value.trim())
59
+ return true;
60
+ return value.split(",").every((entry) => {
61
+ const host = entry.trim();
62
+ const match = /^(?:\.?[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*|\[[0-9a-fA-F:]+\])(?::(\d{1,5}))?$/.exec(host);
63
+ return host === "*" || Boolean(match && (match[1] === undefined || Number(match[1]) > 0 && Number(match[1]) <= 65535));
64
+ });
65
+ }
66
+ try {
67
+ const u = new URL(value);
68
+ return ["http:", "https:", "socks:", "socks4:", "socks4a:", "socks5:", "socks5h:"].includes(u.protocol) && Boolean(u.hostname) && !u.username && !u.password && !u.search && !u.hash && (!u.pathname || u.pathname === "/") && (!u.port || Number(u.port) > 0 && Number(u.port) <= 65535);
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ export function requestEnvironmentProblem(target, config, rootEnv, names) {
75
+ const policy = effectiveChildEnv(config, target);
76
+ for (const name of names) {
77
+ if (!ENVIRONMENT_NAME.test(name))
78
+ return "grant.env requires exact environment variable names";
79
+ if (!policy.request.includes(name))
80
+ return `grant.env ${name} is not in targets.${target}.child_env.request or child_env.request; ask the person to configure it`;
81
+ const mandatory = mandatoryEnvironmentReason(target, config, name, rootEnv);
82
+ if (mandatory)
83
+ return `grant.env ${name} is forbidden (${mandatory})`;
84
+ if (policy.drop.includes(name))
85
+ return `grant.env ${name} is dropped by child_env.drop`;
86
+ if (rootEnv[name] === undefined)
87
+ return `grant.env ${name} is absent from the root's captured environment; restart the root after setting it`;
88
+ }
89
+ return null;
90
+ }
91
+ export function selectEnvironment(target, config, rootEnv, requestedNames = []) {
92
+ // Preserve the person's endpoint intent before any allowlist, drop or backend scrub. Only
93
+ // a desktop/SDK host's own endpoint under login is removed instead of refusing the launch.
94
+ const def = targetDef(target);
95
+ const endpoints = Object.keys(rootEnv).filter((name) => rootEnv[name] !== undefined && def.endpointEnv.test(name)
96
+ && mandatoryEnvironmentReason(target, config, name, rootEnv) !== "host-session endpoint").sort();
97
+ if (endpoints.length)
98
+ throw new Error(`the environment relay runs in sets ${endpoints.join(", ")}, which sends ${def.product} to another endpoint than its vendor's, where relay cannot tell which family of model answers. ` +
99
+ `Relay reaches other families only, so it does not launch ${targetLabel(def)} this way. ` +
100
+ ((config.targets[target]?.child_auth ?? config.child_auth) === "any"
101
+ ? 'With "child_auth": "any", filtering out that endpoint could send a credential meant for it to the vendor instead. ' : "") +
102
+ (endpoints.every((name) => mandatoryEnvironmentReason(target, { ...config, targets: { ...config.targets, claude: { ...config.targets.claude, child_auth: "login" } } }, name, rootEnv) === "host-session endpoint")
103
+ ? 'Under this desktop/SDK host, setting targets.claude to "child_auth": "login" lets relay remove the host-session endpoint and credentials and verify the account login. ' : "") +
104
+ "Unset those variables in the root environment and restart relay.");
105
+ const problem = requestEnvironmentProblem(target, config, rootEnv, requestedNames);
106
+ if (problem)
107
+ throw new Error(problem);
108
+ const policy = effectiveChildEnv(config, target);
109
+ const env = {};
110
+ const diagnostics = [];
111
+ const releasedNames = [];
112
+ for (const name of Object.keys(rootEnv).sort()) {
113
+ const value = rootEnv[name];
114
+ if (value === undefined)
115
+ continue;
116
+ const explicit = policy.pass.includes(name) || requestedNames.includes(name);
117
+ let reason = mandatoryEnvironmentReason(target, config, name, rootEnv);
118
+ let included = false;
119
+ if (!reason) {
120
+ if (policy.drop.includes(name))
121
+ reason = "configured drop";
122
+ else if (explicit) {
123
+ included = true;
124
+ reason = requestedNames.includes(name) ? "person-approved turn request" : "standing pass";
125
+ }
126
+ else if (policy.policy === "legacy") {
127
+ included = true;
128
+ reason = "legacy inheritance";
129
+ }
130
+ else if (RUNTIME_NAMES.includes(name)) {
131
+ included = !recognizedSecretShape(value);
132
+ reason = included ? "runtime baseline" : "recognized secret shape requires explicit selection";
133
+ }
134
+ else if (PROXY_NAMES.includes(name)) {
135
+ included = validatedProxy(name, value) && !recognizedSecretShape(value);
136
+ reason = included ? "validated proxy" : "proxy requires explicit selection";
137
+ }
138
+ else
139
+ reason = "outside allowlist";
140
+ }
141
+ if (included) {
142
+ env[name] = value;
143
+ if (explicit)
144
+ releasedNames.push(name);
145
+ }
146
+ diagnostics.push({ name, included, reason });
147
+ }
148
+ Object.assign(env, backendEnvironmentRoots(target, rootEnv));
149
+ if (target === "codex")
150
+ env.CODEX_HOME = relayCodexHome(config);
151
+ return { env, diagnostics, policy, releasedNames };
152
+ }
153
+ /** No standing passes or one-turn disclosures in worker/bridge environments. */
154
+ export function runtimeEnvironment(rootEnv = capturedRootEnvironment) {
155
+ const env = {};
156
+ for (const name of RUNTIME_NAMES)
157
+ if (rootEnv[name] !== undefined && !recognizedSecretShape(rootEnv[name]))
158
+ env[name] = rootEnv[name];
159
+ for (const name of ["HOME", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "GROK_HOME", "GROK_AUTH_PATH", "RELAY_HOME", "RELAY_WORKTREES", "RELAY_CONFIG", "RELAY_ENV_SOCKET", "RELAY_DEV_MODEL_STUB"])
160
+ if (rootEnv[name] !== undefined)
161
+ env[name] = rootEnv[name];
162
+ // Only the extension consent tests opt in. Preserve their bounded decoy catalog through
163
+ // trusted workers and child relay registrations; never admit an ordinary environment flag.
164
+ if (rootEnv.RELAY_TEST_NEVER_ADAPTERS === "1" && rootEnv.NODE_TEST_CONTEXT?.startsWith("child")) {
165
+ env.RELAY_TEST_NEVER_ADAPTERS = "1";
166
+ env.NODE_TEST_CONTEXT = rootEnv.NODE_TEST_CONTEXT;
167
+ }
168
+ return env;
169
+ }
170
+ export function backendEnvironmentRoots(target, rootEnv = capturedRootEnvironment) {
171
+ const home = rootEnv.HOME || os.homedir();
172
+ const env = { HOME: home };
173
+ // A nested Claude turn needs the person's deny-rule location as well, but only the person's own
174
+ // setting: Claude Code 2.1.303 keys its keychain login to CLAUDE_CONFIG_DIR being set at all, so
175
+ // setting it even to the default ~/.claude makes `claude auth status` report loggedIn: false
176
+ // (checked live, 2026-10-21). Unset, every reader here falls back to ~/.claude as Claude does.
177
+ if (rootEnv.CLAUDE_CONFIG_DIR)
178
+ env.CLAUDE_CONFIG_DIR = path.resolve(rootEnv.CLAUDE_CONFIG_DIR);
179
+ if (target === "codex")
180
+ env.CODEX_HOME = path.resolve(rootEnv.CODEX_HOME || path.join(home, ".codex"));
181
+ return env;
182
+ }
@@ -0,0 +1,76 @@
1
+ import { ancestors, getNode, getRun, getTurn, runConfig } from "./db.js";
2
+ import { escalationCapabilityProblem, escalationDigest, escalationEffect, owningRootBinding, requiredDecider } from "./escalation-policy.js";
3
+ export function escalationDetail(raw) {
4
+ try {
5
+ const d = JSON.parse(raw ?? "{}");
6
+ return d.escalation && typeof d.request_digest === "string" ? d : null;
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
12
+ export function escalationDecisionAuthentication(row, route, instance) {
13
+ const d = row.kind === "escalation" ? escalationDetail(row.detail_json) : null;
14
+ return d ? { route, instance, requestDigest: d.request_digest } : undefined;
15
+ }
16
+ export function escalationRequestProblem(d, row, policy) {
17
+ const c = d.escalation;
18
+ const run = getRun(row.run_id);
19
+ const turn = getTurn(c.origin_turn);
20
+ const node = getNode(row.node_id);
21
+ if (!node || run?.status !== "active" || ancestors(node, { self: true }).some(n => n.status === "cancelled"))
22
+ return "escalation's owning run/job was cancelled or is unavailable";
23
+ if (c.version !== 1 || c.request_id !== row.id || c.run_id !== row.run_id || c.node_id !== row.node_id || c.origin_turn !== row.turn_id || turn?.node_id !== row.node_id)
24
+ return "escalation request identity changed";
25
+ if (escalationDigest(c) !== d.request_digest || row.summary !== escalationEffect(c))
26
+ return "escalation canonical request digest or approval text changed";
27
+ if (!run?.root_token || escalationDigest(owningRootBinding(row.run_id, run.root_token)) !== escalationDigest(c.root))
28
+ return "owning root session/token binding changed; ask for fresh approval";
29
+ if (requiredDecider(c.capabilities, runConfig(row.run_id)) === "person" && c.required_decider !== "person")
30
+ return "required_decider changed";
31
+ if (c.required_decider !== "person" && c.required_decider !== "owning_run_root")
32
+ return "invalid required_decider";
33
+ if (!Number.isFinite(c.approval_deadline_ms) || Date.now() >= c.approval_deadline_ms || c.deadline_ms !== undefined && (!Number.isFinite(c.deadline_ms) || Date.now() >= c.deadline_ms))
34
+ return "escalation approval deadline expired";
35
+ if (policy) {
36
+ if (policy.hash !== c.never_hash)
37
+ return "escalation never policy hash changed; ask against the cumulative floor";
38
+ const why = escalationCapabilityProblem(c.capabilities, policy, c.access);
39
+ if (why)
40
+ return why;
41
+ }
42
+ if (turn?.access !== c.access)
43
+ return "escalation source access changed";
44
+ if (escalationDigest(turn.grant_json) !== c.baseline_grant_hash)
45
+ return "escalation baseline grant changed; ask for fresh approval";
46
+ return null;
47
+ }
48
+ export function authenticateEscalationDecision(d, auth, allow) {
49
+ if (!auth || auth.requestDigest !== d.request_digest)
50
+ return "escalation decision needs authenticated channel and matching request digest; labels and reason strings are not authority";
51
+ const c = d.escalation;
52
+ const inst = auth.instance;
53
+ const run = getRun(c.run_id);
54
+ if (auth.route === "person-terminal" || auth.route === "terminal-deny") {
55
+ if (allow && (auth.route !== "person-terminal" || c.required_decider === "person"))
56
+ return "this person-only request requires a qualified dialog or confirm";
57
+ return null; // CLI already checked interactive code and launched-agent ancestry.
58
+ }
59
+ if (!inst || inst.ctx.kind !== "root" || !run?.root_token || inst.token !== run.root_token || escalationDigest(owningRootBinding(c.run_id, inst.token)) !== escalationDigest(c.root))
60
+ return "missing or mismatched authenticated owning root session token";
61
+ if (auth.route === "person-confirm")
62
+ return inst.host.confirmTool === true ? null : "confirm is not a qualified person channel";
63
+ if (auth.route === "person-dialog")
64
+ return inst.host.personDialog === true && !!inst.host.elicit ? null : "dialog is not a qualified person channel";
65
+ if (auth.route !== "owning-run-root" || allow && c.required_decider === "person")
66
+ return "person-only capability cannot be authorized by the owning root";
67
+ return null;
68
+ }
69
+ /** A consumed approval must still carry exactly the provenance recorded in its terminal row. */
70
+ export function escalationDecisionProblem(d, row) {
71
+ const decision = d.decision;
72
+ if (!decision || decision.request_digest !== d.request_digest || escalationDigest(decision.root) !== escalationDigest(d.escalation.root) || decision.decided_by !== row.decided_by || decision.at !== row.decided_at || decision.note !== row.note)
73
+ return "escalation decision provenance changed";
74
+ const routes = d.escalation.required_decider === "person" ? ["person-dialog", "person-confirm"] : ["owning-run-root", "person-dialog", "person-confirm", "person-terminal"];
75
+ return routes.includes(decision.route) ? null : "escalation decision route does not qualify for required_decider";
76
+ }
@@ -0,0 +1,13 @@
1
+ const runtimes = new Map();
2
+ const key = (node, turn) => `${node}:${turn}`;
3
+ export function registerEscalationRuntime(node, turn, runtime) {
4
+ const k = key(node, turn);
5
+ if (runtimes.has(k))
6
+ throw new Error("escalation runtime already registered for this turn");
7
+ runtimes.set(k, runtime);
8
+ return () => { if (runtimes.get(k) === runtime)
9
+ runtimes.delete(k); };
10
+ }
11
+ export const escalationRuntime = (node, turn) => runtimes.get(key(node, turn));
12
+ // Keep the contract import surface stable while person-route availability owns its storage.
13
+ export { publishEscalationPersonPath, localEscalationPersonPath, refreshEscalationPersonPath, escalationPersonPathAvailable, } from "./escalation-person-path.js";
@@ -0,0 +1,131 @@
1
+ /** Availability of the person approval route, including private cross-process heartbeats. */
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { relayHome } from "./config.js";
6
+ import { db, getRun, registryMark, sameMark } from "./db.js";
7
+ import { owningRootBinding } from "./escalation-policy.js";
8
+ // Cross-process, short-lived person-route availability is published by the root server in the
9
+ // private state (see escalations.ts). This callback also makes host qualification changes immediate.
10
+ const paths = new Map();
11
+ export function publishEscalationPersonPath(owner, qualified) {
12
+ paths.set(owner, qualified);
13
+ return () => { if (paths.get(owner) === qualified)
14
+ paths.delete(owner); };
15
+ }
16
+ export const localEscalationPersonPath = (owner) => paths.get(owner)?.();
17
+ const personPathDir = () => path.join(relayHome(), "person-paths");
18
+ const personPathFile = (identity) => path.join(personPathDir(), `${identity}.json`);
19
+ const reportedPersonPathFailures = new Set();
20
+ function checkPersonPathDir(dir = personPathDir(), st = fs.lstatSync(dir)) {
21
+ if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid?.() || (st.mode & 0o077))
22
+ throw new Error(`${dir} is not a private directory owned by this user`);
23
+ }
24
+ /**
25
+ * Whether a run of the registry has this root token, as last read, with the registry's mark then:
26
+ * answered again only while the registry has not changed since (registryMark), and read afresh
27
+ * otherwise. The root server asks on every watch tick and every call.
28
+ */
29
+ const owners = new Map();
30
+ function ownsAnyRun(owner) {
31
+ const mark = registryMark(), last = owners.get(owner);
32
+ if (last && sameMark(last.mark, mark))
33
+ return last.owns;
34
+ const owns = Boolean(db().prepare("SELECT 1 FROM runs WHERE root_token = ? LIMIT 1").get(owner));
35
+ owners.set(owner, { mark, owns });
36
+ return owns;
37
+ }
38
+ /** The heartbeat's identity for a root token: a digest of the token alone, so worked out once per token. */
39
+ const identities = new Map();
40
+ function identityOf(owner) {
41
+ let identity = identities.get(owner);
42
+ if (identity === undefined) {
43
+ if (identities.size >= 256)
44
+ identities.clear();
45
+ identities.set(owner, (identity = owningRootBinding("", owner).session_identity));
46
+ }
47
+ return identity;
48
+ }
49
+ /** Root-server heartbeat. Ephemeral availability must not rewrite captured run state, and
50
+ * no bearer token is persisted. Atomic replacement keeps concurrent readers from seeing a
51
+ * partial heartbeat. Expired files grant nothing, including after root ownership changes. */
52
+ export function refreshEscalationPersonPath(owner, qualified) {
53
+ if (!ownsAnyRun(owner))
54
+ return;
55
+ const identity = identityOf(owner), file = personPathFile(identity);
56
+ try {
57
+ if (!qualified.confirm && !qualified.dialog) {
58
+ if (!fs.existsSync(personPathDir())) {
59
+ reportedPersonPathFailures.delete(identity);
60
+ return;
61
+ }
62
+ checkPersonPathDir();
63
+ fs.rmSync(file, { force: true });
64
+ reportedPersonPathFailures.delete(identity);
65
+ return;
66
+ }
67
+ // Made when it is not a directory yet (mkdir then refuses whatever else is in its place), and
68
+ // checked either way.
69
+ const dir = personPathDir();
70
+ let st;
71
+ try {
72
+ st = fs.lstatSync(dir);
73
+ }
74
+ catch { /* made below */ }
75
+ if (!st?.isDirectory())
76
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
77
+ checkPersonPathDir(dir, st?.isDirectory() ? st : undefined);
78
+ const value = { ...qualified, identity, expires_at: Date.now() + 5000 };
79
+ const tmp = `${file}.${crypto.randomBytes(8).toString("hex")}.tmp`;
80
+ let renamed = false;
81
+ try {
82
+ fs.writeFileSync(tmp, JSON.stringify(value), { flag: "wx", mode: 0o600 });
83
+ fs.renameSync(tmp, file);
84
+ renamed = true;
85
+ }
86
+ finally {
87
+ if (!renamed)
88
+ fs.rmSync(tmp, { force: true });
89
+ }
90
+ reportedPersonPathFailures.delete(identity);
91
+ }
92
+ catch (err) {
93
+ // A stale heartbeat must not leave person-only authority open. Remove it only after proving the
94
+ // parent is relay's private directory; never follow an unsafe replacement directory.
95
+ try {
96
+ checkPersonPathDir();
97
+ fs.rmSync(file, { force: true });
98
+ }
99
+ catch { /* unavailable is closed */ }
100
+ if (!reportedPersonPathFailures.has(identity)) {
101
+ reportedPersonPathFailures.add(identity);
102
+ console.error(`relay: person approval path is unavailable (${err.message}); person-only decisions remain closed`);
103
+ }
104
+ }
105
+ }
106
+ export function escalationPersonPathAvailable(runId) {
107
+ const run = getRun(runId);
108
+ if (!run?.root_token)
109
+ return false;
110
+ const local = localEscalationPersonPath(run.root_token);
111
+ if (local)
112
+ return local.confirm || local.dialog;
113
+ try {
114
+ checkPersonPathDir();
115
+ const identity = identityOf(run.root_token);
116
+ const fd = fs.openSync(personPathFile(identity), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
117
+ try {
118
+ const st = fs.fstatSync(fd);
119
+ if (!st.isFile() || st.uid !== process.getuid?.() || (st.mode & 0o077) || st.nlink !== 1 || st.size > 4096)
120
+ return false;
121
+ const saved = JSON.parse(fs.readFileSync(fd, "utf8"));
122
+ return saved?.identity === identity && Number.isFinite(saved.expires_at) && saved.expires_at > Date.now() && (saved.confirm === true || saved.dialog === true);
123
+ }
124
+ finally {
125
+ fs.closeSync(fd);
126
+ }
127
+ }
128
+ catch {
129
+ return false;
130
+ }
131
+ }
@@ -0,0 +1,79 @@
1
+ import { MEDIATED_NETWORK_EFFECT } from "./mediated-network-provider.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { canonical, insideAnyCase } from "./config.js";
6
+ import { neverDigest, neverEndpointProblem, neverPathIdentity, neverPathProblem } from "./never-policy.js";
7
+ const text = z.string().min(1).max(65536).refine(s => !s.includes("\0"), "NUL is not allowed");
8
+ const literalRoot = text.refine(s => path.isAbsolute(s) && path.normalize(s) === s && !/[\r\n*?\[\]{}~]/.test(s), "expected a literal absolute normalized root");
9
+ export const EscalationInputSchema = z.strictObject({
10
+ capabilities: z.array(z.discriminatedUnion("kind", [
11
+ z.strictObject({ kind: z.literal("localhost"), port: z.number().int().min(1).max(65535), operation: z.enum(["connect", "listen"]), host: z.enum(["127.0.0.1", "::1"]).default("127.0.0.1"), api_effects: text }),
12
+ z.strictObject({ kind: z.literal("port0") }),
13
+ z.strictObject({ kind: z.literal("write_root"), root: literalRoot, change_to_write: z.literal(true).optional() }),
14
+ z.strictObject({ kind: z.literal("network"), mode: z.enum(["mediated", "raw", "local"]) }),
15
+ ])).min(1).max(32),
16
+ reason: text,
17
+ continuation: z.strictObject({ argv: z.array(text).min(1).max(4096).optional(), command: text.optional(), cwd: literalRoot.optional(), work: text.optional() }),
18
+ });
19
+ /** One classifier for request, display and decision. Prose never supplies authorization. */
20
+ export function requiredDecider(caps, cfg) {
21
+ return caps.some(c => c.kind === "network" && c.mode !== "mediated" || c.kind === "port0" && typeof cfg.escalation === "object" && cfg.escalation.port0_authority === "person") ? "person" : "owning_run_root";
22
+ }
23
+ export function escalationDigest(value) { return neverDigest(value); }
24
+ /** This is a non-secret binding, not a bearer token or a user-provided root label. */
25
+ export const owningRootBinding = (run, token) => ({ run_id: run, session_identity: neverDigest(["relay-escalation-owner-v1", token]), token_version: 1 });
26
+ export function normalizeCapabilities(input, cwd) {
27
+ const values = input.capabilities.map(c => {
28
+ let extra = {};
29
+ if (c.kind === "localhost")
30
+ extra = { transport: "tcp", resolved_addresses: [c.host] };
31
+ if (c.kind === "write_root") {
32
+ const real = canonical(c.root);
33
+ if (insideAnyCase(c.root, cwd) || insideAnyCase(real, canonical(cwd)))
34
+ throw new Error("write_root must name an exact root outside the worktree");
35
+ extra = { real_root: real, exists: fs.existsSync(c.root), pins: [...neverPathIdentity(c.root), ...neverPathIdentity(real)] };
36
+ }
37
+ const body = { ...c, ...extra };
38
+ return { ...body, id: neverDigest(body) };
39
+ });
40
+ return [...new Map(values.map(c => [c.id, c])).values()].sort((a, b) => a.id.localeCompare(b.id));
41
+ }
42
+ export function escalationCapabilityProblem(caps, policy, access) {
43
+ for (const c of caps) {
44
+ if (c.kind === "write_root") {
45
+ if (access === "read" && !c.change_to_write)
46
+ return "read jobs need an explicit change_to_write for outside writes";
47
+ const why = neverPathProblem(policy, c.root, "write", true);
48
+ if (why)
49
+ return why;
50
+ if (canonical(c.root) !== c.real_root || neverDigest([...neverPathIdentity(c.root), ...neverPathIdentity(c.real_root)]) !== neverDigest(c.pins))
51
+ return "outside-write root identity changed; request fresh approval";
52
+ }
53
+ if (c.kind === "localhost") {
54
+ const why = neverEndpointProblem(policy, { host: c.host, port: c.port, transport: "tcp", operation: c.operation });
55
+ if (why)
56
+ return why;
57
+ }
58
+ if (c.kind === "network" && c.mode === "raw" && policy.hosts.length)
59
+ return "never.hosts disables raw network in Release A; request a qualified mediated route";
60
+ }
61
+ return null;
62
+ }
63
+ export const MUTABLE_CODE_TEXT = "The command runs worktree code that the agent can edit after approval.";
64
+ /** Release A's fixed four-port job block; kept local to avoid the policy/overlay/port runtime cycle. */
65
+ export const BIND_BLOCK_APPROVAL_TEXT = "The job's reserved block of 4 TCP ports ($PORT/$PORTS) is also opened for binding; listeners there may bind 0.0.0.0 and are exposed on the LAN and tailnet.";
66
+ export const PORT0_APPROVAL_TEXT = `The listener may bind 0.0.0.0 for that turn, so it is on the LAN and tailnet. This permits any otherwise allowed TCP bind port, not just OS-selected ephemeral ports. ${BIND_BLOCK_APPROVAL_TEXT} Never ports, relay control ports and protected listeners remain denied.`;
67
+ export const localhostConnectEffect = (port) => `IPv4 localhost connect also allows port ${port} on this Mac's LAN and tailnet addresses. It does not allow ::1, 127.0.0.2 or other ports. Never and relay control ports remain denied. Service API effects count as part of this authority.`;
68
+ export const localhostListenEffect = (port) => `TCP listen port ${port} may bind wildcard/0.0.0.0, exposing it on the LAN and tailnet. ${BIND_BLOCK_APPROVAL_TEXT} Outbound connect is not added.`;
69
+ export function escalationEffect(c) {
70
+ return `End turn ${c.origin_turn} and start one new turn with the explicit capabilities below. ${MUTABLE_CODE_TEXT} The addition applies to all commands and descendants in the replacement turn and ends when that turn and its processes stop; outside writes persist on disk. `
71
+ + (c.capabilities.some(x => x.kind === "network" && x.mode === "mediated") ? MEDIATED_NETWORK_EFFECT + " " : "")
72
+ + (c.capabilities.some(x => x.kind === "port0") ? `${PORT0_APPROVAL_TEXT} ` : "")
73
+ + c.capabilities.flatMap(x => x.kind === "localhost" && x.operation === "listen" ? [localhostListenEffect(x.port) + " "] : []).join("")
74
+ + c.capabilities.flatMap(x => x.kind === "localhost" && x.operation === "connect" ? [localhostConnectEffect(x.port) + " "] : []).join("")
75
+ + (c.capabilities.some(x => x.kind === "network" && x.mode !== "mediated") ? "Broad raw/local network is person-only: direct network, LAN/tailnet service APIs, forwarding and exfiltration are possible. " : "")
76
+ + `Required decider: ${c.required_decider}. The owning root may approve eligible effects only when the person's authorized task clearly covers them; port-0 requires tests or servers. `
77
+ + `Overlay budget: ${c.overlay_budget_s}s; approval expires at ${c.approval_deadline_ms}${c.deadline_ms ? `; earlier job/turn deadline ${c.deadline_ms}` : ""}. `
78
+ + `Capabilities: ${JSON.stringify(c.capabilities)}. Intended continuation (untrusted): ${JSON.stringify(c.continuation)}. Reason (untrusted): ${JSON.stringify(c.reason)}.`;
79
+ }
@@ -0,0 +1,135 @@
1
+ /** Trusted stage-2 adapter. No model-supplied value selects identity, policy or destination. */
2
+ import fs from "node:fs";
3
+ import { getNode, getTurn, runConfig, tx } from "./db.js";
4
+ import { getRequest } from "./approvals.js";
5
+ import { escalationDetail, escalationDecisionProblem, escalationRequestProblem } from "./escalation-authority.js";
6
+ import { escalationDigest } from "./escalation-policy.js";
7
+ import { checkpointNever } from "./never-checkpoint.js";
8
+ import { sessionParams } from "./params.js";
9
+ import { mediatedBaseline, mediatedNetworkProblem } from "./mediated-network-provider.js";
10
+ import { createOverlayRequest, getOverlay, localhostControlProblem, markOverlayReceipt, settleOverlayRequestInTransaction, stopOverlay } from "./restart-overlay.js";
11
+ function capabilities(caps) {
12
+ return caps.map(c => c.kind === "write_root"
13
+ ? { kind: "write", root: c.real_root, scope: fs.statSync(c.real_root, { throwIfNoEntry: false })?.isDirectory() ? "tree" : "file" }
14
+ : c.kind === "localhost" ? { kind: c.kind, operation: c.operation, port: c.port, host: "127.0.0.1" }
15
+ : c.kind === "network" ? { kind: c.kind, mode: c.mode } : { kind: c.kind });
16
+ }
17
+ export function createEscalationRuntime(o) {
18
+ const baselineHash = escalationDigest(o.baselineGrant ?? null);
19
+ const baselineProblem = () => {
20
+ const node = getNode(o.nodeId), turn = getTurn(o.turnId);
21
+ const grant = node && sessionParams(node).grant;
22
+ // Match session.grantFor: environment disclosure is per turn, separately pinned by WP3.
23
+ const { env: _env, ...standing } = grant ?? {};
24
+ const effective = !grant ? null : turn?.access === "write" ? standing : standing.network ? { network: true } : null;
25
+ return !node || !turn || escalationDigest(effective) !== baselineHash ? "the standing baseline grant changed since source launch; request a fresh turn" : null;
26
+ };
27
+ const bindings = new Map();
28
+ let disposed = false;
29
+ const abandon = (c) => {
30
+ const b = bindings.get(c.request_id);
31
+ if (!b)
32
+ return;
33
+ const r = getOverlay(c.run_id, b.id);
34
+ if (r.state === "requested")
35
+ tx(() => settleOverlayRequestInTransaction(c.run_id, b.id, b.digest, "cancelled"));
36
+ else if (["pending_restart", "stopping", "ready", "running"].includes(r.state)) {
37
+ if (r.state === "pending_restart" && r.receipt?.delivered === undefined)
38
+ markOverlayReceipt(c.run_id, b.id, false);
39
+ stopOverlay(c.run_id, b.id, r.launchedAt === undefined ? "call cancelled or receipt lost; allowed, not executed" : "requesting call cancelled after launch");
40
+ }
41
+ b.signal.removeEventListener("abort", b.cancel);
42
+ };
43
+ const runtime = {
44
+ snapshot: () => ({ ...o.snapshot }),
45
+ qualify(caps, policy) {
46
+ if (disposed)
47
+ return "the qualified stage-2 turn has ended";
48
+ const changed = baselineProblem();
49
+ if (changed)
50
+ return changed;
51
+ const mediated = mediatedNetworkProblem({ capabilities: caps, baseline: mediatedBaseline(o.baselineGrant, runConfig(getNode(o.nodeId).run_id)), policy });
52
+ if (mediated)
53
+ return mediated;
54
+ for (const c of caps) {
55
+ if (c.kind === "network" && c.mode === "local")
56
+ return "no qualified local network provider exists in this release";
57
+ if (c.kind === "network" && c.mode === "raw" && policy.hosts.length)
58
+ return "raw network is unavailable with any never.hosts entry";
59
+ if (c.kind === "localhost" && c.host !== "127.0.0.1")
60
+ return "no qualified IPv6 localhost overlay provider exists in this release";
61
+ if (c.kind === "write_root" && getTurn(o.turnId)?.access !== "write")
62
+ return "no qualified access-change provider exists in this release; read jobs cannot acquire outside writes";
63
+ }
64
+ return localhostControlProblem(caps);
65
+ },
66
+ prepare(c, digest, signal) {
67
+ if (disposed || signal.aborted || c.node_id !== o.nodeId || c.origin_turn !== o.turnId || escalationDigest(c) !== digest)
68
+ throw new Error("escalation lifecycle/identity lost before preparation");
69
+ const changed = baselineProblem();
70
+ if (changed)
71
+ throw new Error(changed);
72
+ const remaining = Math.min(c.overlay_budget_s * 1000, (c.deadline_ms ?? Infinity) - Date.now());
73
+ const r = createOverlayRequest({ nodeId: o.nodeId, originTurn: o.turnId, capabilities: capabilities(c.capabilities),
74
+ reason: c.reason, continuation: JSON.stringify(c.continuation), intended: {
75
+ ...(c.continuation.argv ? { argv: c.continuation.argv } : {}),
76
+ ...(c.continuation.command ? { script: c.continuation.command } : {}),
77
+ ...(c.continuation.cwd ? { cwd: c.continuation.cwd } : {}),
78
+ },
79
+ authority: { owningRoot: c.root.session_identity, tokenBinding: escalationDigest(c.root), required_decider: c.required_decider },
80
+ remainingMs: remaining, pendingMs: c.approval_deadline_ms - Date.now(), escalation: { requestId: c.request_id, digest },
81
+ });
82
+ const cancel = () => abandon(c);
83
+ bindings.set(c.request_id, { id: r.id, digest: r.digest, signal, cancel });
84
+ signal.addEventListener("abort", cancel, { once: true });
85
+ if (signal.aborted) {
86
+ cancel();
87
+ throw new Error("escalation call cancelled during preparation");
88
+ }
89
+ return { id: r.id, digest: r.digest };
90
+ },
91
+ abandon,
92
+ async request(approval, signal) {
93
+ const c = approval.canonical, b = bindings.get(c.request_id);
94
+ const policy = checkpointNever(c.run_id, "decision");
95
+ return tx(() => {
96
+ const row = getRequest(c.request_id), d = row && escalationDetail(row.detail_json);
97
+ if (disposed || signal.aborted || !b || !row || row.status !== "allowed" || !d || d.request_digest !== approval.digest
98
+ || escalationDigest(d.decision) !== escalationDigest(approval.decision))
99
+ throw new Error("approved escalation lost before handoff");
100
+ const why = baselineProblem() ?? escalationRequestProblem(d, row, policy) ?? escalationDecisionProblem(d, row);
101
+ if (why)
102
+ throw new Error(why);
103
+ const r = getOverlay(c.run_id, b.id);
104
+ if (r.state !== "pending_restart" || r.digest !== b.digest || !r.receipt || r.receipt.delivered !== undefined)
105
+ throw new Error("overlay decision/receipt is not pending");
106
+ return { state: "restart_pending", overlay_id: r.id, disclosures: r.receipt.disclosures };
107
+ });
108
+ },
109
+ async receipt(approval, delivered) {
110
+ const c = approval.canonical, b = bindings.get(c.request_id);
111
+ if (!b)
112
+ throw new Error("receipt has no prepared overlay");
113
+ const ok = delivered && !disposed && !b.signal.aborted;
114
+ const r = getOverlay(c.run_id, b.id);
115
+ if (r.receipt?.delivered === undefined && r.state === "pending_restart")
116
+ markOverlayReceipt(c.run_id, b.id, ok);
117
+ else if (ok)
118
+ throw new Error("receipt already invalidated; never replay");
119
+ if (!ok)
120
+ stopOverlay(c.run_id, b.id, "receipt delivery failed; allowed, not executed");
121
+ // Keep cancellation active until the lifecycle has finished teardown/consumption.
122
+ },
123
+ };
124
+ return { runtime, dispose() {
125
+ disposed = true;
126
+ for (const [requestId, b] of bindings) {
127
+ const row = getRequest(requestId), d = row && escalationDetail(row.detail_json);
128
+ const r = getOverlay(getNode(o.nodeId).run_id, b.id);
129
+ // A delivered handoff is owned by the worker after handle.done, not by the broker.
130
+ if (d && r.receipt?.delivered !== true)
131
+ abandon(d.escalation);
132
+ b.signal.removeEventListener("abort", b.cancel);
133
+ }
134
+ } };
135
+ }