@jbkjr/relay 0.0.0-stage → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +393 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1539 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +345 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +641 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +345 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +635 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1518 -0
  186. package/docs/pinned-codex.md +333 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
@@ -0,0 +1,110 @@
1
+ // Dispatch: starting the detached worker that runs a session's queued turns, and queueing turns.
2
+ // A call that queues a turn commits it first, then starts the worker (review X1): a failure to
3
+ // start is not the call's error, and a later call starts it (redispatch).
4
+ import { spawn } from "node:child_process";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { nodeDir, RELAY_CLI } from "./config.js";
8
+ import { ownsRun } from "./caller.js";
9
+ import { ACTIVE, db, getNode, getRun, insertTurn, nextQueuedTurn, now, runConfig, tx, updateNode, workerLive } from "./db.js";
10
+ import { logBytes, noteDiagnosticProblem, rotateLog, writeProblem } from "./storage.js";
11
+ import { workerEnvironment } from "./env-broker.js";
12
+ /** Starts a detached worker for the node unless one already owns it. */
13
+ export function ensureWorker(nodeId) {
14
+ const claimedAt = now();
15
+ const claimed = tx(() => {
16
+ const n = getNode(nodeId);
17
+ if (workerLive(n))
18
+ return false;
19
+ updateNode(nodeId, { worker_pid: -1, worker_start: null, worker_claimed_at: claimedAt });
20
+ return true;
21
+ });
22
+ if (!claimed)
23
+ return;
24
+ try {
25
+ const n = getNode(nodeId);
26
+ // The worker's own output, rotated at the run's log_max_mb. A log that cannot be opened (a full
27
+ // disk, a directory that is not writable) does not keep the worker from starting: what goes
28
+ // wrong for its turn then is recorded in the registry, and the log's failure is said with this
29
+ // process's next result (storage.ts noteDiagnosticProblem). Whether the turn can still run
30
+ // depends on what else it must write there (its node directory, its launch files), so that is
31
+ // left to the turn's own result to say.
32
+ // The failure names the run's paths: said only to the conversation that owns the run.
33
+ let fd = null;
34
+ let logFile = "its worker.log";
35
+ const owner = getRun(n.run_id)?.root_token ?? null;
36
+ try {
37
+ logFile = path.join(nodeDir(n.run_id, nodeId), "worker.log");
38
+ const unrotated = rotateLog(logFile, logBytes(runConfig(n.run_id)));
39
+ if (unrotated)
40
+ noteDiagnosticProblem(logFile, `relay could not rotate ${logFile} at log_max_mb (${unrotated}), so it grows past that size`, owner);
41
+ fd = fs.openSync(logFile, "a");
42
+ }
43
+ catch (err) {
44
+ fd = null;
45
+ noteDiagnosticProblem(logFile, writeProblem(logFile, err, `what the worker of ${nodeId} prints is not kept`), owner);
46
+ }
47
+ try {
48
+ const out = fd ?? "ignore";
49
+ const child = spawn(process.execPath, [RELAY_CLI, "worker", nodeId], { detached: true, stdio: ["ignore", out, out], env: workerEnvironment(n.run_id) });
50
+ child.unref();
51
+ }
52
+ finally {
53
+ if (fd !== null)
54
+ fs.closeSync(fd);
55
+ }
56
+ }
57
+ catch (err) {
58
+ // No worker was started: the claim is let go, so that the next dispatch (see redispatch) can
59
+ // start one, rather than wait out the claim and then find the node written off as lost.
60
+ db().prepare("UPDATE nodes SET worker_pid = NULL, worker_claimed_at = NULL WHERE id = ? AND worker_pid = -1 AND worker_claimed_at = ?").run(nodeId, claimedAt);
61
+ throw err;
62
+ }
63
+ }
64
+ /**
65
+ * Starts the node's worker once its work is committed (review X1). A failure does not undo that
66
+ * work and is not the call's error: the item exists, the caller is told its id, and the warning
67
+ * returned here says how it gets started (redispatch).
68
+ */
69
+ export function dispatch(nodeId) {
70
+ try {
71
+ ensureWorker(nodeId);
72
+ return null;
73
+ }
74
+ catch (err) {
75
+ return `relay could not start the worker of ${nodeId} (${err.message}), so it has not started yet. Call again with the same request_id, or call status with id "${nodeId}", to start it.`;
76
+ }
77
+ }
78
+ /** Whether this caller may start workers in the run: the root session that owns it, or a launched agent in it. */
79
+ export const mayDispatch = (inst, runId) => (inst.ctx.kind === "root" ? ownsRun(inst, runId) : inst.ctx.kind === "child" && inst.ctx.runId === runId);
80
+ /**
81
+ * Starts the worker of a session left queued with a turn to run and no worker: one whose call
82
+ * committed the work and then could not start a worker, or ended before it did (review X1). A
83
+ * session with a worker, or one claimed a moment ago, is left alone: ensureWorker claims once.
84
+ */
85
+ export function redispatch(nodeId) {
86
+ const n = getNode(nodeId);
87
+ if (!n || n.status !== "queued" || n.worker_pid !== null || !nextQueuedTurn(nodeId))
88
+ return null;
89
+ return dispatch(nodeId);
90
+ }
91
+ /** Puts a finished session back in the queue for another turn; never revives a cancelled one. */
92
+ function requeue(nodeId) {
93
+ db().prepare("UPDATE nodes SET status = 'queued', ended_at = NULL, error = NULL WHERE id = ? AND status NOT IN ('cancelled', 'queued', 'running')").run(nodeId);
94
+ }
95
+ /**
96
+ * Queues a turn for a session, and puts the session back in the queue if it had settled (requeue).
97
+ * `idle` runs first in that case, while the session still shows how it last ended. Call it inside
98
+ * the transaction that records what the turn is for: the session's worker then sees all of it or
99
+ * none. Returns the turn, and whether the session was busy (the turn then runs after its current one).
100
+ */
101
+ export function queueTurn(nodeId, source, body, access, o = {}) {
102
+ const n = getNode(nodeId);
103
+ const wasActive = ACTIVE.includes(n.status);
104
+ const turnId = insertTurn(nodeId, source, body, access);
105
+ if (!wasActive) {
106
+ o.idle?.(n);
107
+ requeue(nodeId);
108
+ }
109
+ return { turnId, wasActive };
110
+ }
@@ -0,0 +1,505 @@
1
+ import { escalationEnabled } from "./config.js";
2
+ // Root-owned environment authority. Worker environments carry runtime controls only. Workers
3
+ // also hold the root's secret values in memory for redaction only, never as launch authority.
4
+ import crypto from "node:crypto";
5
+ import fs from "node:fs";
6
+ import net from "node:net";
7
+ import path from "node:path";
8
+ import { configPath, loadConfig, networkOn, relayHome } from "./config.js";
9
+ import { getNode, getRun, getTurn, runConfig, updateTurn, workCwd } from "./db.js";
10
+ import { claimGone, requestApproval, webGranted } from "./approvals.js";
11
+ import { procStart, sameProcess } from "./procs.js";
12
+ import { socketPeer } from "../confine/peer.js";
13
+ import { ensureRelaySocketsDir } from "../confine/sockets.js";
14
+ import { capturedRootEnvironment, effectiveChildEnv, runtimeEnvironment, selectEnvironment } from "./env-policy.js";
15
+ import { redact, registerReleasedEnvironment, registerRootRedactionValues, secretValues, withTurnSecrets } from "./secrets.js";
16
+ import { targetDef } from "../targets/index.js";
17
+ import { clipped } from "./shown.js";
18
+ export const ENV_SOCKET = "RELAY_ENV_SOCKET";
19
+ const roots = new Map();
20
+ const opening = new Map();
21
+ const MAX = 4 * 1024 * 1024;
22
+ /**
23
+ * Where a root's broker is published for rediscovery: in relay's control directory, which no
24
+ * agent can write, by a hash of the owner token (never the token). A worker that outlived the root
25
+ * which started it (a shared desktop process restarted under a conversation's session token) finds
26
+ * its run's current broker here instead of the dead address it inherited (environmentClaim).
27
+ */
28
+ const brokerRecord = (owner) => path.join(relayHome(), "brokers", `${crypto.createHash("sha256").update("relay-env-broker-v1").update(owner).digest("hex").slice(0, 32)}.json`);
29
+ function publishBroker(owner, socket) {
30
+ const file = brokerRecord(owner);
31
+ try {
32
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
33
+ const tmp = `${file}.${process.pid}.tmp`;
34
+ fs.writeFileSync(tmp, JSON.stringify({ socket, pid: process.pid, start: procStart(process.pid) }), { mode: 0o600 });
35
+ fs.renameSync(tmp, file);
36
+ }
37
+ catch {
38
+ // Workers this root started have its address already; only rediscovery after a restart is lost.
39
+ }
40
+ }
41
+ function unpublishBroker(owner, socket) {
42
+ try {
43
+ if (JSON.parse(fs.readFileSync(brokerRecord(owner), "utf8")).socket === socket)
44
+ fs.rmSync(brokerRecord(owner), { force: true });
45
+ }
46
+ catch { /* Gone already. */ }
47
+ }
48
+ /**
49
+ * The broker of the run's current owner, as it published itself, when that process is the run's
50
+ * recorded lease holder and still alive; otherwise null. Read from the registry and the control
51
+ * directory, never from anything an agent supplies.
52
+ */
53
+ function currentBroker(claim) {
54
+ try {
55
+ const nodeId = "turn" in claim ? getTurn(claim.turn)?.node_id : claim.worker;
56
+ const run = nodeId ? getRun(getNode(nodeId)?.run_id ?? "") : undefined;
57
+ if (!run?.root_token || !run.root_pid)
58
+ return null;
59
+ const rec = JSON.parse(fs.readFileSync(brokerRecord(run.root_token), "utf8"));
60
+ if (typeof rec.socket !== "string" || !path.isAbsolute(rec.socket) || rec.pid !== run.root_pid || rec.start !== run.root_start)
61
+ return null;
62
+ return sameProcess(rec.pid, rec.start) ? rec : null;
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ function rootFor(runId) {
69
+ const owner = getRun(runId)?.root_token;
70
+ return owner ? roots.get(owner) : undefined;
71
+ }
72
+ /**
73
+ * Why a grant only the person can allow, given to a job before it starts (grant.local_network),
74
+ * cannot be asked for here, or null: as for grant.env, the owning root session must have a person
75
+ * path (confirm, or an approval dialog relay knows a person answers), and approval requests must be on.
76
+ */
77
+ export function personConsentAdmission(runId, what) {
78
+ const root = rootFor(runId);
79
+ if (!root || (!root.inst.host.confirmTool && !root.inst.host.personDialog)) {
80
+ return `${what} needs the user's consent through confirm or a qualified approval dialog in the owning root session. No such person path is available here; use a session where relay can ask them.`;
81
+ }
82
+ try {
83
+ if (!escalationEnabled(environmentConfig(runId)))
84
+ return `${what} needs the user's consent through an approval request, but escalation is off in relay's config.`;
85
+ }
86
+ catch (err) {
87
+ return err.message;
88
+ }
89
+ return null;
90
+ }
91
+ /** Names only, and only a person path. Called before creating an item or any harness process. */
92
+ export function environmentAdmission(runId, target, names) {
93
+ if (!names.length)
94
+ return null;
95
+ const root = rootFor(runId);
96
+ if (!root || (!root.inst.host.confirmTool && !root.inst.host.personDialog)) {
97
+ return "grant.env needs the user's consent through confirm or a qualified approval dialog in the owning root session. No such person path is available; ask the person to configure exact child_env.pass entries, or use a session where relay can ask them.";
98
+ }
99
+ try {
100
+ const cfg = environmentConfig(runId);
101
+ if (!escalationEnabled(cfg))
102
+ return "grant.env needs person-only approval, but escalation is off; ask the person to configure exact child_env.pass entries or enable approval requests";
103
+ selectEnvironment(target, cfg, capturedRootEnvironment, names);
104
+ }
105
+ catch (err) {
106
+ return err.message;
107
+ }
108
+ return null;
109
+ }
110
+ /** Child relay servers learn the address, never the root's environment or a value-bearing ticket. */
111
+ export function environmentSocketFor(runId) {
112
+ const socket = rootFor(runId)?.socket ?? process.env[ENV_SOCKET];
113
+ if (!socket)
114
+ throw new Error("the owning root's environment broker is unavailable; restart the root relay server before launching another turn");
115
+ return socket;
116
+ }
117
+ export function workerEnvironment(runId) {
118
+ const root = rootFor(runId);
119
+ const env = runtimeEnvironment(root ? capturedRootEnvironment : process.env);
120
+ const socket = root?.socket ?? process.env[ENV_SOCKET];
121
+ // Still start a worker when the address is missing: turnEnvironment then records a failed
122
+ // turn. Throwing in dispatch would strand it queued with no worker to report the failure.
123
+ if (socket)
124
+ env[ENV_SOCKET] = socket;
125
+ else
126
+ delete env[ENV_SOCKET];
127
+ return env;
128
+ }
129
+ /** A socket operation is bound to the registry-pinned worker, not to a bearer held by an agent. */
130
+ export async function openRootEnvironment(inst, opts = {}) {
131
+ if (inst.ctx.kind !== "root")
132
+ throw new Error("only a root server owns an environment broker");
133
+ const existing = roots.get(inst.token);
134
+ if (existing)
135
+ return existing;
136
+ const pending = opening.get(inst.token);
137
+ if (pending)
138
+ return pending;
139
+ const started = (async () => {
140
+ const dir = fs.mkdtempSync(path.join(ensureRelaySocketsDir(), "e-"));
141
+ const socket = path.join(dir, "s");
142
+ if (Buffer.byteLength(socket) > 103) {
143
+ fs.rmSync(dir, { recursive: true });
144
+ throw new Error("the root environment broker's socket path exceeds the platform limit");
145
+ }
146
+ const connections = new Set();
147
+ const consumed = new Set();
148
+ const redactionValues = secretValues(capturedRootEnvironment);
149
+ const server = net.createServer((sock) => {
150
+ connections.add(sock);
151
+ sock.on("error", () => { });
152
+ sock.once("close", () => connections.delete(sock));
153
+ sock.setTimeout(5000, () => sock.destroy());
154
+ let buf = "", handled = false;
155
+ sock.setEncoding("utf8");
156
+ sock.on("data", (chunk) => {
157
+ if (handled)
158
+ return;
159
+ buf += chunk;
160
+ if (buf.length > 1024)
161
+ return void sock.destroy();
162
+ const nl = buf.indexOf("\n");
163
+ if (nl < 0)
164
+ return;
165
+ handled = true;
166
+ sock.setTimeout(0);
167
+ void withTurnSecrets(async () => {
168
+ let id;
169
+ try {
170
+ const input = JSON.parse(buf.slice(0, nl));
171
+ const startup = typeof input.worker === "string" && input.turn === undefined;
172
+ if (!startup && (input.worker !== undefined || !Number.isSafeInteger(input.turn)))
173
+ throw new Error("invalid environment claim identity");
174
+ id = input.turn;
175
+ const turn = startup ? undefined : getTurn(id);
176
+ const node = startup ? getNode(input.worker) : turn && getNode(turn.node_id);
177
+ if (!node?.target || !["job", "thread", "participant"].includes(node.kind) || (!startup && !turn)
178
+ || getRun(node.run_id)?.root_token !== inst.token)
179
+ throw new Error("this root does not own that environment worker or turn");
180
+ const peer = await (opts.peerIdentity ?? socketPeer)(sock);
181
+ const pinned = () => {
182
+ const n = getNode(node.id);
183
+ return !sock.destroyed && getRun(node.run_id)?.root_token === inst.token
184
+ && n?.worker_pid === peer.pid && n.worker_start === peer.start && peer.uid === process.getuid?.()
185
+ && sameProcess(peer.pid, peer.start, { fresh: true });
186
+ };
187
+ // A worker claims a turn as it picks it up, while the turn is still queued (claimGone).
188
+ const live = () => pinned() && (startup || !claimGone(node.id, id));
189
+ if (!pinned())
190
+ throw new Error("environment requests require the registry-pinned live worker of this node");
191
+ // Only the pinned worker learns why its turn cannot be claimed: ids and statuses, no values.
192
+ const gone = startup ? null : claimGone(node.id, id);
193
+ if (gone)
194
+ throw new Error(`this turn's environment cannot be claimed: ${gone}`);
195
+ if (startup) {
196
+ // Housekeeping can log before any turn. This claim releases no agent environment,
197
+ // config or consent capability, and has exactly the same pinned peer checks.
198
+ sock.end(JSON.stringify({ redactionValues }) + "\n");
199
+ return;
200
+ }
201
+ if (!turn)
202
+ throw new Error("invalid environment turn identity");
203
+ if (consumed.has(id))
204
+ throw new Error("this turn's environment claim has already been consumed; resume with a new turn");
205
+ // The opaque claim lives only here, is consumed once and dies with this root server.
206
+ consumed.add(id);
207
+ const grant = JSON.parse(turn.grant_json ?? "{}");
208
+ const names = grant.env ?? [];
209
+ const cfg = environmentConfig(node.run_id);
210
+ const revision = policyRevision(cfg, node.target);
211
+ const cwd = workCwd(node);
212
+ const directory = directoryIdentity(cwd);
213
+ const selection = selectEnvironment(node.target, cfg, capturedRootEnvironment, names);
214
+ registerReleasedEnvironment(selection.env, selection.releasedNames);
215
+ // What the worker checks again before it launches the turn (claimBinding), as it may wait for a slot first.
216
+ const bound = () => {
217
+ try {
218
+ return live() && getNode(node.id)?.target === node.target && workCwd(getNode(node.id)) === cwd
219
+ && (!names.length || inst.host.confirmTool === true || inst.host.personDialog === true)
220
+ && directoryIdentity(cwd) === directory
221
+ && policyRevision(environmentConfig(node.run_id), node.target) === revision
222
+ && getTurn(id)?.access === turn.access && getTurn(id)?.grant_json === turn.grant_json;
223
+ }
224
+ catch {
225
+ return false;
226
+ }
227
+ };
228
+ if (names.length) {
229
+ const unavailable = environmentAdmission(node.run_id, node.target, names);
230
+ if (unavailable)
231
+ throw new Error(unavailable);
232
+ // An authenticated claim can wait for a person longer than the transport deadline.
233
+ // This acknowledges only the pending consent, and releases no environment values.
234
+ // requestApproval can wait once behind another request, then once for a decision.
235
+ const timeoutMs = Math.min(2_147_483_647, 2 * cfg.approval_timeout_s * 1000 + 10_000);
236
+ sock.write(JSON.stringify({ pending: true, timeoutMs }) + "\n");
237
+ const policy = effectiveChildEnv(cfg, node.target);
238
+ const fullAccess = cfg.allow_dangerous && turn.access === "write" && targetDef(node.target).capabilities.confinement === "verified";
239
+ const network = networkOn(cfg, grant) || fullAccess;
240
+ const purpose = clipped(redact(turn.body), 1000);
241
+ const answer = await requestApproval(node.id, id, {
242
+ kind: "env", summary: `release environment variables ${names.join(", ")} to ${node.target} for this turn only. Caller-supplied purpose (untrusted): ${purpose}`,
243
+ reason: `Caller-supplied purpose (untrusted): ${purpose}`,
244
+ detail: { names, target: node.target, run: node.run_id, item: node.id, turn: id, cwd, access: turn.access,
245
+ full_access: fullAccess, network,
246
+ web: network || webGranted(node.id) ? "network/native web access permitted" : cfg.child_web === "ask" ? "requires approval (Codex search off)" : "native target configuration; model and result channels remain available", standing_passes: policy.pass },
247
+ }, () => !bound());
248
+ if (!answer.allow || !bound())
249
+ throw new Error("environment consent was denied, expired, cancelled or its binding changed; no environment values were released. Resume with a fresh grant.env request, or ask the person to configure child_env.pass.");
250
+ }
251
+ if (!bound())
252
+ throw new Error("the environment turn or policy changed before release; no values were released");
253
+ // The separate set never becomes part of selection.env or an agent/tool response.
254
+ sock.end(JSON.stringify({ selection: { env: selection.env, releasedNames: selection.releasedNames }, config: cfg, redactionValues }) + "\n");
255
+ }
256
+ catch (err) {
257
+ // All policy errors are names/reasons; never serialize an environment or URL value.
258
+ if (!sock.destroyed)
259
+ sock.end(JSON.stringify({ error: err.message }) + "\n");
260
+ }
261
+ });
262
+ });
263
+ });
264
+ try {
265
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(socket, resolve); });
266
+ fs.chmodSync(socket, 0o600);
267
+ server.unref();
268
+ }
269
+ catch (err) {
270
+ fs.rmSync(dir, { recursive: true, force: true });
271
+ throw err;
272
+ }
273
+ publishBroker(inst.token, socket);
274
+ const authority = { inst, socket, close: async () => {
275
+ roots.delete(inst.token);
276
+ unpublishBroker(inst.token, socket);
277
+ for (const s of connections)
278
+ s.destroy();
279
+ await new Promise((resolve) => server.close(() => resolve()));
280
+ fs.rmSync(dir, { recursive: true, force: true });
281
+ } };
282
+ roots.set(inst.token, authority);
283
+ return authority;
284
+ })();
285
+ opening.set(inst.token, started);
286
+ try {
287
+ return await started;
288
+ }
289
+ finally {
290
+ opening.delete(inst.token);
291
+ }
292
+ }
293
+ export async function closeRootEnvironment(inst) { await roots.get(inst.token)?.close(); }
294
+ // Names/policy only; comparison stays in memory and is deliberately not a reusable value hash.
295
+ // Every config input of a selection is here: the target's effective child_env and child_auth, and
296
+ // Claude's child_auth, which decides the host-session endpoint guard for every target. The config
297
+ // file's identity is added unless the caller compares a standing selection alone (claimBinding).
298
+ function policyRevision(cfg, target, o = {}) {
299
+ return JSON.stringify({ policy: effectiveChildEnv(cfg, target), auth: cfg.child_auth, ownAuth: cfg.targets[target].child_auth,
300
+ hostAuth: cfg.targets.claude.child_auth, network: cfg.child_network, web: cfg.child_web, escalation: cfg.escalation,
301
+ ...(o.file === false ? {} : { config_file: configIdentity() }) });
302
+ }
303
+ function configIdentity() {
304
+ try {
305
+ const st = fs.statSync(configPath(), { bigint: true });
306
+ return [st.dev, st.ino, st.mtimeNs, st.ctimeNs, st.size].map(String).join(":");
307
+ }
308
+ catch (err) {
309
+ if (err.code === "ENOENT")
310
+ return "missing";
311
+ throw err;
312
+ }
313
+ }
314
+ function directoryIdentity(cwd) {
315
+ const st = fs.statSync(cwd, { bigint: true });
316
+ if (!st.isDirectory())
317
+ throw new Error("the environment turn's working directory is no longer a directory");
318
+ return JSON.stringify([fs.realpathSync(cwd), String(st.dev), String(st.ino)]);
319
+ }
320
+ /** Run execution limits stay snapshotted; the person's environment/auth policy is read each turn. */
321
+ function environmentConfig(runId) {
322
+ const cfg = runConfig(runId), current = loadConfig(() => { });
323
+ cfg.child_env = current.child_env;
324
+ cfg.child_auth = current.child_auth;
325
+ for (const target of Object.keys(cfg.targets)) {
326
+ cfg.targets[target].child_env = current.targets[target].child_env;
327
+ cfg.targets[target].child_auth = current.targets[target].child_auth;
328
+ }
329
+ return cfg;
330
+ }
331
+ export function recordEnvironmentRequest(turnId, names) {
332
+ if (names?.length) {
333
+ // At queue time grant_json holds names only; the worker records the complete effective grant
334
+ // when it claims the turn. A missing field never reuses a previous turn's request.
335
+ const turn = getTurn(turnId);
336
+ if (!turn || turn.status !== "queued")
337
+ throw new Error("environment requests belong to a queued turn");
338
+ // Imported lazily below would add no safety: updateTurn persists names, never selected values.
339
+ updateTurn(turnId, { grant_json: JSON.stringify({ env: [...new Set(names)] }) });
340
+ }
341
+ }
342
+ /** Fail closed when the owner is gone. Workers never fall back to their inherited environment. */
343
+ export async function turnEnvironment(turnId, signal) {
344
+ const result = await environmentClaim({ turn: turnId }, signal);
345
+ registerRootRedactionValues(result.redactionValues);
346
+ return { selection: result.selection, config: result.config };
347
+ }
348
+ /** Said when what a turn's environment was claimed under changed before its launch. */
349
+ const CLAIM_CHANGED = "what this turn's environment was claimed under changed while it waited to start (its environment/auth policy, relay's config file for a turn with a grant.env request, the working directory, the turn's grant or its worker), so it was not started with the environment it was given then. Resume it to claim afresh; consent to a grant.env request is asked again";
350
+ /**
351
+ * What a turn's environment claim is bound to, as the worker reads it: the turn, its access and
352
+ * recorded grant, the target, the registry-pinned worker, the working directory's identity, and the
353
+ * environment/auth policy. Names and identities only, never a value or a value hash. The broker's
354
+ * bound() checks the same, with the config file's identity, until it releases the selection. At
355
+ * launch the file's identity counts only for a turn with a grant.env request, whose consent is bound
356
+ * to it: a standing selection depends on nothing in the file beyond the policy compared here, so an
357
+ * unrelated edit, a touch or a no-op save does not fail it (or, through settle, its follow-ups).
358
+ */
359
+ function claimBinding(turnId) {
360
+ const turn = getTurn(turnId);
361
+ const node = turn ? getNode(turn.node_id) : undefined;
362
+ if (!turn || !node?.target)
363
+ throw new Error("the environment turn is no longer in the registry");
364
+ const cwd = workCwd(node);
365
+ const requested = Boolean(JSON.parse(turn.grant_json ?? "{}").env?.length);
366
+ return JSON.stringify({
367
+ turn: turnId, access: turn.access, grant: turn.grant_json, node: node.id, target: node.target, worker: [node.worker_pid, node.worker_start],
368
+ cwd, directory: directoryIdentity(cwd), policy: policyRevision(environmentConfig(node.run_id), node.target, { file: requested }),
369
+ });
370
+ }
371
+ /**
372
+ * Claims a turn's environment from the owning root as its worker picks the turn up, before the turn
373
+ * waits for a concurrency slot: from then on it needs its root no more than a running turn does. The
374
+ * binding is read before the claim is sent and checked on the reply and again at launch, while the
375
+ * broker checks its own reading until it replies, so a change at any point fails the turn closed.
376
+ * Consent to a one-turn request is asked within the claim, so it is decided before the slot wait.
377
+ */
378
+ export async function claimTurnEnvironment(turnId, signal) {
379
+ const binding = claimBinding(turnId);
380
+ const { run_id: runId, target } = getNode(getTurn(turnId).node_id);
381
+ let held = await turnEnvironment(turnId, signal);
382
+ const drop = () => {
383
+ if (!held)
384
+ return;
385
+ // Drops this worker's references to the values; they were never written anywhere.
386
+ for (const name of Object.keys(held.selection.env))
387
+ delete held.selection.env[name];
388
+ held = null;
389
+ };
390
+ const unchanged = () => {
391
+ let same = false;
392
+ // Unchanged since before the claim was sent, and selected under the policy in force now: the
393
+ // broker returns the config it selected from, so an edit undone in between cannot slip through.
394
+ try {
395
+ same = claimBinding(turnId) === binding
396
+ && policyRevision(held.config, target, { file: false }) === policyRevision(environmentConfig(runId), target, { file: false });
397
+ }
398
+ catch { /* Unreadable counts as changed. */ }
399
+ if (!same) {
400
+ drop();
401
+ throw new Error(CLAIM_CHANGED);
402
+ }
403
+ };
404
+ unchanged();
405
+ return {
406
+ check: () => {
407
+ if (!held)
408
+ throw new Error("this turn's environment was already used or dropped; resume it to claim afresh");
409
+ unchanged();
410
+ },
411
+ take: () => {
412
+ if (!held)
413
+ throw new Error("this turn's environment was already used or dropped; resume it to claim afresh");
414
+ unchanged();
415
+ const claimed = held;
416
+ held = null;
417
+ return claimed;
418
+ },
419
+ drop,
420
+ };
421
+ }
422
+ /** Startup redaction only. The values stay inside the redactor, including before a first turn. */
423
+ export async function workerRedaction(nodeId) {
424
+ const result = await environmentClaim({ worker: nodeId });
425
+ registerRootRedactionValues(result.redactionValues);
426
+ }
427
+ /** Said when no broker of the run's owner can be reached: the turn fails, nothing waits for one. */
428
+ const NO_BROKER = "the owning root's environment broker is unavailable, unresponsive or closed: restart the root, or on a shared relay call relay again from the conversation that owns this run (either opens its broker), then resume this work; environment consent is asked afresh";
429
+ function environmentClaim(claim, signal) {
430
+ return new Promise((resolve, reject) => {
431
+ // The address inherited from the root that started this worker, unless that root has since been
432
+ // replaced: then the run's current owner, as published in the control directory, provided the
433
+ // kernel says the listening process is that owner (checked below before anything is sent).
434
+ const inherited = process.env[ENV_SOCKET];
435
+ const current = currentBroker(claim);
436
+ const moved = current && current.socket !== inherited ? current : null;
437
+ const address = moved?.socket ?? inherited;
438
+ if (!address)
439
+ return reject(new Error(`no owning root environment broker: ${NO_BROKER}`));
440
+ const sock = net.connect(address);
441
+ let buf = "", settled = false, pending = false;
442
+ let deadline = setTimeout(() => fail(), 10_000);
443
+ const fail = (why = NO_BROKER) => { clearTimeout(deadline); if (!settled) {
444
+ settled = true;
445
+ reject(new Error(why));
446
+ } sock.destroy(); };
447
+ const abort = () => fail();
448
+ signal?.addEventListener("abort", abort, { once: true });
449
+ sock.once("connect", () => {
450
+ if (!moved)
451
+ return void sock.write(JSON.stringify(claim) + "\n");
452
+ void socketPeer(sock).then((peer) => {
453
+ if (peer.pid !== moved.pid || peer.start !== moved.start || peer.uid !== process.getuid?.())
454
+ return fail(`the environment broker relay recorded for this run is not its owning root process; nothing was claimed. ${NO_BROKER}`);
455
+ // Handing the socket to the kernel-identity helper pauses it; the answer must be read.
456
+ if (!settled) {
457
+ sock.resume();
458
+ sock.write(JSON.stringify(claim) + "\n");
459
+ }
460
+ }, () => fail());
461
+ });
462
+ sock.setEncoding("utf8");
463
+ sock.on("data", (chunk) => {
464
+ buf += chunk;
465
+ if (buf.length > MAX)
466
+ return fail();
467
+ while (!settled && buf.includes("\n")) {
468
+ const nl = buf.indexOf("\n"), line = buf.slice(0, nl);
469
+ buf = buf.slice(nl + 1);
470
+ try {
471
+ const result = JSON.parse(line);
472
+ if (result.pending === true) {
473
+ if (!("turn" in claim) || pending || !Number.isFinite(result.timeoutMs) || result.timeoutMs <= 0 || result.timeoutMs > 2_147_483_647)
474
+ return fail();
475
+ pending = true;
476
+ clearTimeout(deadline);
477
+ deadline = setTimeout(() => fail(), result.timeoutMs);
478
+ continue;
479
+ }
480
+ if (result.error) {
481
+ settled = true;
482
+ reject(new Error(result.error));
483
+ }
484
+ else if (!Array.isArray(result.redactionValues) || !result.redactionValues.every((v) => typeof v === "string")
485
+ || ("turn" in claim && (!result.selection?.env || !Array.isArray(result.selection.releasedNames) || !result.config)))
486
+ return fail();
487
+ else {
488
+ settled = true;
489
+ resolve(result);
490
+ }
491
+ }
492
+ catch {
493
+ return fail();
494
+ }
495
+ clearTimeout(deadline);
496
+ sock.destroy();
497
+ }
498
+ });
499
+ sock.once("error", () => fail());
500
+ sock.once("close", () => { clearTimeout(deadline); signal?.removeEventListener("abort", abort); if (!settled)
501
+ fail(); });
502
+ if (signal?.aborted)
503
+ fail();
504
+ });
505
+ }