@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,329 @@
1
+ // Secrets relay knows the shape of, kept out of what it writes (agents' logs, final messages,
2
+ // errors, activity, prompts' copies, transcripts, its own diagnostic logs). By value: the values of
3
+ // variables in the environment relay passes to agents whose names say they hold a secret (a token,
4
+ // a key, a password), and the password in a proxy URL (and its Basic form). By shape alone, for
5
+ // what relay cannot know by value: the vendor credentials relay handles, by their published
6
+ // prefixes; a URL's password; an Authorization header's credentials (Bearer, Basic or Token ones
7
+ // of 8 characters or more, token-like ones after any other scheme or none); and a token-like value
8
+ // given to a variable or a key whose name says it holds a secret. The last three cover the per-turn
9
+ // proxy token and bridge secret relay hands a confined agent; those are also registered by value
10
+ // in the turn's private scope below. A value known by value is cut wherever its text appears, in each of the forms it
11
+ // takes (formsOf), as a word of a reply too, so a variable whose name only might be a secret's (a
12
+ // CREDENTIAL_STORE, a CACHE_KEY) has its value cut only when it looks like a token (tokenLike).
13
+ // Names are read in camelCase as in snake_case (nameWords).
14
+ import { AsyncLocalStorage } from "node:async_hooks";
15
+ // Each turn keeps its generated credentials until its results and errors have been persisted,
16
+ // including after the proxy and broker close. Concurrent turns never share these values.
17
+ const turnSecrets = new AsyncLocalStorage();
18
+ // A worker learns these from its owning root over a peer-bound broker claim, never through
19
+ // process.env. They exist only to cut records; no launch/bridge environment consumes this set.
20
+ const rootSecretForms = new Set();
21
+ let rootSecretPattern = null;
22
+ export function registerRootRedactionValues(values) {
23
+ for (const value of values)
24
+ for (const form of formsOf(value))
25
+ if (form)
26
+ rootSecretForms.add(form);
27
+ rootSecretPattern = rootSecretForms.size
28
+ ? new RegExp([...rootSecretForms].sort((a, b) => b.length - a.length).map(escape).join("|"), "g") : null;
29
+ }
30
+ function cutRootSecrets(text) {
31
+ return rootSecretPattern ? text.replace(rootSecretPattern, REDACTED) : text;
32
+ }
33
+ export function withTurnSecrets(run, o = {}) {
34
+ return o.reuse && turnSecrets.getStore() ? run() : turnSecrets.run(new Map(), run);
35
+ }
36
+ /** Register before handing a generated credential to the harness. Never persist its value. */
37
+ export function registerTurnSecret(value, kind) {
38
+ const scope = turnSecrets.getStore();
39
+ if (!scope)
40
+ throw new Error("a generated credential needs a turn redaction scope");
41
+ for (const form of formsOf(value))
42
+ if (form)
43
+ scope.set(form, `[redacted: ${kind}]`);
44
+ }
45
+ /**
46
+ * Direct backend unit calls have no turn; production launches run inside withTurnSecrets. Only a
47
+ * value worth cutting wherever it appears is registered (secretLike): a released flag such as "1",
48
+ * a number or a path is no secret, and cutting it by value would garble every log and result that
49
+ * mentions it (an exit code or a path). Longer control strings are registered too; fixtures
50
+ * must not use the exact prose/model name their assertions expect as a released control value.
51
+ */
52
+ export function registerReleasedEnvironment(env, names) {
53
+ if (!turnSecrets.getStore())
54
+ return;
55
+ for (const name of names)
56
+ if (env[name] !== undefined && secretLike(env[name]))
57
+ registerTurnSecret(env[name], "environment value");
58
+ }
59
+ function cutTurnSecrets(text, scope) {
60
+ if (!scope?.size || !text)
61
+ return text;
62
+ const literal = new RegExp([...scope.keys()].sort((a, b) => b.length - a.length).map(escape).join("|"), "g");
63
+ return text.replace(literal, (value) => scope.get(value));
64
+ }
65
+ // Every pattern below costs at most a bounded amount of work from each place it can start, so
66
+ // that one long line of an agent's output (a tool's whole output is one event) is cut in time
67
+ // linear in its length: a quantifier that could scan to the end of a long run from each start, or
68
+ // a lookahead that does, would take minutes on a crafted line, and stall the worker that cuts it.
69
+ /**
70
+ * A variable in relay's environment whose name says its value is a secret: the secret's word ends
71
+ * the name (GH_TOKEN, NEXTAUTH_SECRET, DB_PASSWORD, AWS_SECRET_ACCESS_KEY); a password's word
72
+ * glued to what it is for (libpq's PGPASSWORD); or _PWD (MySQL's MYSQL_PWD; not PWD or OLDPWD,
73
+ * the working directories). Its value is cut wherever it appears (secretLike).
74
+ */
75
+ const SECRET_VALUE_NAME = /(?:(?:^|_)(?:TOKEN|SECRET|(?:API|ACCESS|PRIVATE|SECRET|SIGNING|ENCRYPTION)_?KEY)|PASSWORD|PASSWD|PASSPHRASE|_PWD)$/i;
76
+ /**
77
+ * A variable in relay's environment whose name may be a secret's, or says something about one
78
+ * (AWS_ACCESS_KEY_ID, a CREDENTIAL_STORE, an AUTH_MODE, any name ending in _KEY): its value is cut
79
+ * wherever it appears only when it looks like a token (tokenLike), not when it is a word, words or
80
+ * a time, which a reply can hold for other reasons.
81
+ */
82
+ const SECRET_NAME = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIALS?|AUTH)(?:_|$)|_KEY$/i;
83
+ /**
84
+ * A variable or key next to a value relay does not know, whose name says plainly that it holds a
85
+ * secret (as nameWords spells it). Narrower than SECRET_NAME: a bare _KEY (cache_key, primary_key,
86
+ * idempotency_key) names ordinary data as often as a secret, and the text it is cut from can be an
87
+ * agent's reply.
88
+ */
89
+ const SECRET_CONTEXT_NAME = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|(?:API|ACCESS|PRIVATE|SECRET|SIGNING|ENCRYPTION)_?KEY|CREDENTIALS?|AUTH)(?:_|$)|(?:PASSWORD|PASSWD|PASSPHRASE|_PWD)$/i;
90
+ /** Tokens named for what they page through, not what they open. */
91
+ const NOT_SECRET_NAME = /(?:^|_)(?:NEXT|PAGE|NEXT_PAGE|CONTINUATION|CURSOR|SYNC)_?TOKEN$/i;
92
+ /**
93
+ * A name with its words parted by `_` where camelCase parts them by case, so that the rules above
94
+ * read JSON's and JavaScript's spelling as they read a variable's: accessToken as access_Token,
95
+ * clientSecret as client_Secret, secretAccessKey as secret_Access_Key, npm's _authToken as
96
+ * _auth_Token. maxTokens (max_Tokens) and authorName (author_Name) still name no secret.
97
+ */
98
+ const nameWords = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1_$2");
99
+ const PROXY_NAME = /^(?:https?|all|ftp)_proxy$/i;
100
+ /** Credentials by their shape: Anthropic's keys and OAuth tokens, OpenAI's keys (with a digit in them: checked in cut), xAI's keys, GitHub's tokens. */
101
+ /**
102
+ * A relay session token's shape, in any case (session-token.ts issues them lowercase): a bearer key
103
+ * a conversation's model carries on a shared relay. Cut wherever an agent writes one, so that relay
104
+ * neither keeps nor returns it.
105
+ */
106
+ export const SESSION_TOKEN_SHAPE = /rs1_[0-9a-f]{56}/i;
107
+ const SHAPES = [
108
+ [new RegExp(SESSION_TOKEN_SHAPE.source, "gi"), () => true],
109
+ [/\bsk-ant-[A-Za-z0-9_-]{20,}/g, () => true],
110
+ [/\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{32,}/g, (m) => /\d/.test(m.replace(/^sk-(?:proj-|svcacct-|admin-)?/, ""))],
111
+ // xAI's official SDK uses (?i)xai-[a-z0-9]{20,80}; keep longer matches whole too, as above.
112
+ // https://github.com/xai-org/xai-sdk-python/blob/ddc27ddf06dd9799058c44def8818aa496ba1722/.gitleaks.toml#L7
113
+ [/\bxai-[A-Za-z0-9]{20,}/gi, () => true],
114
+ [/\bgh[pousr]_[A-Za-z0-9]{36,}/g, () => true],
115
+ [/\bgithub_pat_[A-Za-z0-9_]{60,}/g, () => true],
116
+ ];
117
+ export const REDACTED = "[redacted]";
118
+ /** Admission primitive, independent of replacement text or a variable's name. Linear bounded patterns. */
119
+ export function recognizedSecretShape(value) {
120
+ for (const [pattern, is] of SHAPES) {
121
+ const scan = new RegExp(pattern.source, pattern.flags);
122
+ for (let m = scan.exec(value); m; m = scan.exec(value))
123
+ if (is(m[0]))
124
+ return true;
125
+ }
126
+ if (/-----BEGIN (?:[A-Z0-9 ]{0,40} )?PRIVATE KEY-----/.test(value))
127
+ return true;
128
+ if (/\b(?:Bearer|Basic|Token)[ \t]{1,8}[A-Za-z0-9._~+/=-]{8,}/i.test(value))
129
+ return true;
130
+ if (/\bAKIA[A-Z0-9]{16}\b/.test(value))
131
+ return true;
132
+ if (/"(?:private_key|client_secret|access_token)"[ \t\r\n]{0,32}:[ \t\r\n]{0,32}"[^"\r\n]{1,4096}"/.test(value))
133
+ return true;
134
+ if (/\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@"'<>]{0,256}:[^\s@/"'<>]{1,4096}@/i.test(value))
135
+ return true;
136
+ return false;
137
+ }
138
+ /** Whether a variable's value is worth cutting wherever it appears: long enough, and not a path or a number. */
139
+ const secretLike = (v) => v.length >= 8 && !/^[/~.]/.test(v) && !/^\d+$/.test(v);
140
+ /** A word of a value: its letters in one case or capitalised, then up to three digits (v2, oauth2, x509, Rs256); or a short number (2026). */
141
+ const WORD = /^(?:[a-z]+|[A-Z]+|[A-Z][a-z]+)\d{0,3}$|^\d{1,4}$/;
142
+ /** Whether a value is words joined by _ - . or /: an enum (oauth2_device_flow_v2), a relative path (secrets/token_v2.json). */
143
+ const words = (v) => {
144
+ const parts = v.split(/[_./-]/);
145
+ return parts.length >= 2 && parts.every((p) => WORD.test(p));
146
+ };
147
+ /** A date, or a date and time, as ISO 8601 and RFC 3339 write them (2026-10-19, 2026-10-19T03:00:00Z): an expiry, not a secret. */
148
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:[.,]\d{1,9})?)?(?:Z|[+-]\d{2}(?::?\d{2})?)?)?$/i;
149
+ /** An identifier in camel or Pascal case (getAccessToken, SomeProviderName): code, not a token, where it has no digit. */
150
+ const CAMEL = /^[a-z]*(?:[A-Z][a-z]+)+$/;
151
+ /**
152
+ * Whether a value found next to a secret's name looks like a secret rather than code, a URL, a
153
+ * time or words: 16 characters or more of a token's alphabet with letters and digits both, or 24
154
+ * or more in both cases and no digit (a base64url secret can draw none) that is not an identifier;
155
+ * not a path, not a URL (the rule for a URL's password cuts what of it is secret), not a date or
156
+ * time, and not words (see words). A token's random characters (a UUID, base64) are not words,
157
+ * separators or not.
158
+ */
159
+ const tokenLike = (v) => v.length >= 16 && /[A-Za-z]/.test(v) && !/^[/~.]/.test(v) && !v.includes("://") && !words(v) && !TIMESTAMP.test(v)
160
+ && (/\d/.test(v) || (v.length >= 24 && /[a-z]/.test(v) && /[A-Z]/.test(v) && !CAMEL.test(v)));
161
+ /** The schemes of an Authorization header whose credentials are cut at 8 characters or more, token-like or not. */
162
+ const KNOWN_SCHEME = /^(?:Bearer|Basic|Token)$/i;
163
+ /** Secrets by their context, each with what is kept of a match. Applied after the values, so a value already cut is not matched again. */
164
+ const CONTEXTS = [
165
+ // A URL's password, scheme://user:password@, however short: not a reference to one ($VAR, ${...},
166
+ // <...>, %s). The scheme is bounded (32 characters), and the user and the password both stop at
167
+ // a slash, as the next start's :// has one: from each start, the scan ends where the next could begin.
168
+ [/\b([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@"'<>]*:)([^\s@/"'<>]+)@/gi, (m, before, pass) => (/^[$<{%*[]/.test(pass) ? m : `${before}${REDACTED}@`)],
169
+ // An Authorization or Proxy-Authorization header's credentials: as a header line
170
+ // (`Authorization: Bearer x`), a JSON key (`"Authorization": "Bearer x"`, its quotes escaped too,
171
+ // inside a JSON string) or a TOML or shell assignment (`Authorization = "Bearer x"`). After a
172
+ // scheme (one word, bounded) or none: those of Bearer, Basic or Token at 8 characters or more,
173
+ // any other only when they look like a token (an ApiKey's, a Bot's, a bare one). Digest's
174
+ // parameters are not cut.
175
+ [/\b((?:Proxy-)?Authorization\\*"?[ \t]{0,8}[:=][ \t]{0,8}\\*"?[ \t]{0,8})(?:([A-Za-z][A-Za-z0-9_-]{0,31})([ \t]{1,8}))?([A-Za-z0-9._~+/=-]+)/gi,
176
+ (m, before, scheme, space, creds) => ((scheme && KNOWN_SCHEME.test(scheme) ? creds.length >= 8 : tokenLike(creds)) ? `${before}${scheme ?? ""}${space ?? ""}${REDACTED}` : m)],
177
+ ];
178
+ /**
179
+ * The head of an assignment or a key, whose value is read after it (VALUE): `NAME=value`;
180
+ * `NAME="value"` and `name = 'value'` (shell, TOML, INI, code: with spaces around the = only when
181
+ * the value is quoted); `name: value` (YAML); and `"name": "value"` (JSON, or a Python dict's
182
+ * single quotes, and with its quotes escaped inside a JSON string). The name stops where a word
183
+ * does, so a scan of it from one start ends where the next start could be.
184
+ */
185
+ const ASSIGNMENT = /\b([A-Za-z_][A-Za-z0-9_]*)(\\*["'][ \t]{0,8}:[ \t]{0,8}\\*["']|[ \t]{0,8}=[ \t]{0,8}(?:\\*"|')|=|:[ \t]{1,8}(?:\\*"|')?)/g;
186
+ const VALUE = /[A-Za-z0-9_\-+/=.~:]+/y;
187
+ /**
188
+ * Cuts a token-like value given to a name that plainly names a secret. A name that does not is
189
+ * passed over, but not what follows it, which can itself be an assignment: in
190
+ * `--from-literal=API_TOKEN=x` or `--build-arg=NPM_TOKEN=x`, `literal=` is passed over and
191
+ * `API_TOKEN=x` read next. A secret's value is read once, so the work stays linear.
192
+ */
193
+ function cutAssignments(text) {
194
+ let out = "";
195
+ let kept = 0;
196
+ ASSIGNMENT.lastIndex = 0;
197
+ for (let m = ASSIGNMENT.exec(text); m; m = ASSIGNMENT.exec(text)) {
198
+ const name = nameWords(m[1]);
199
+ if (!SECRET_CONTEXT_NAME.test(name) || NOT_SECRET_NAME.test(name))
200
+ continue;
201
+ const at = m.index + m[0].length;
202
+ VALUE.lastIndex = at;
203
+ const value = VALUE.exec(text)?.[0];
204
+ if (!value)
205
+ continue;
206
+ if (tokenLike(value)) {
207
+ out += text.slice(kept, at) + REDACTED;
208
+ kept = at + value.length;
209
+ }
210
+ ASSIGNMENT.lastIndex = at + value.length;
211
+ }
212
+ return kept ? out + text.slice(kept) : text;
213
+ }
214
+ /** The secret values in an environment: see the top of this file. */
215
+ export function secretValues(env) {
216
+ const out = [];
217
+ for (const [k, v] of Object.entries(env ?? {})) {
218
+ if (typeof v !== "string" || !v)
219
+ continue;
220
+ if (PROXY_NAME.test(k)) {
221
+ try {
222
+ const u = new URL(v);
223
+ const pass = decodeURIComponent(u.password);
224
+ if (pass && secretLike(pass)) {
225
+ out.push(pass, u.password);
226
+ out.push(Buffer.from(`${decodeURIComponent(u.username)}:${pass}`).toString("base64"));
227
+ }
228
+ }
229
+ catch {
230
+ // Not a URL: nothing in it relay knows to be a secret.
231
+ }
232
+ continue;
233
+ }
234
+ const name = nameWords(k);
235
+ if (SECRET_VALUE_NAME.test(name) ? secretLike(v) : SECRET_NAME.test(name) && secretLike(v) && tokenLike(v))
236
+ out.push(v);
237
+ }
238
+ return out;
239
+ }
240
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
241
+ /** The armour around a PEM block, which says what the block holds and is no part of the secret. */
242
+ const ARMOUR = /^-----(?:BEGIN|END) [A-Z0-9 ]+-----$/;
243
+ /**
244
+ * The forms a secret's text takes where relay meets it, beside the text itself: trimmed of the
245
+ * whitespace around it (a value read from a file, or from a CRLF .env, ends in a line break); each
246
+ * line of one that has several (a PEM key, printed a line at a time, and an agent's log is cut a
247
+ * line at a time), when the line is 16 characters or more with no space in it and is not the armour
248
+ * around a key; percent-encoded, as in a URL, with its hex in either case; and JSON-escaped, once
249
+ * (an agent's event stream) or twice (a tool's arguments given as a JSON string inside an event).
250
+ */
251
+ function formsOf(v) {
252
+ const bases = [v];
253
+ const trimmed = v.trim();
254
+ if (trimmed !== v && secretLike(trimmed))
255
+ bases.push(trimmed);
256
+ if (/[\r\n]/.test(trimmed)) {
257
+ for (const line of trimmed.split(/\r?\n|\r/)) {
258
+ const l = line.trim();
259
+ if (l.length >= 16 && !/\s/.test(l) && !ARMOUR.test(l))
260
+ bases.push(l);
261
+ }
262
+ }
263
+ const out = new Set();
264
+ for (const b of bases) {
265
+ out.add(b);
266
+ try {
267
+ const url = encodeURIComponent(b);
268
+ out.add(url);
269
+ out.add(url.replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase()));
270
+ }
271
+ catch {
272
+ // A lone surrogate, which no URL holds.
273
+ }
274
+ let json = b;
275
+ for (let depth = 0; depth < 2; depth++) {
276
+ const next = JSON.stringify(json).slice(1, -1);
277
+ if (next === json)
278
+ break;
279
+ out.add(next);
280
+ json = next;
281
+ }
282
+ }
283
+ return [...out];
284
+ }
285
+ /** Every by-value form the ordinary redactor cuts, captured after turn credentials register. */
286
+ export function streamSecretValues(extra = [], ...envs) {
287
+ const values = new Set([...rootSecretForms, ...(turnSecrets.getStore()?.keys() ?? [])]);
288
+ for (const v of [...extra, ...[process.env, ...envs].flatMap(secretValues)]) {
289
+ for (const form of formsOf(v))
290
+ if (form)
291
+ values.add(form);
292
+ }
293
+ return [...values];
294
+ }
295
+ /**
296
+ * A function that cuts every secret of these environments out of a text, in each of its forms
297
+ * (formsOf), and the secrets known by their shape or their context whatever the environment.
298
+ */
299
+ function environmentRedactor(...envs) {
300
+ const values = new Set();
301
+ for (const env of envs) {
302
+ for (const v of secretValues(env))
303
+ for (const form of formsOf(v))
304
+ values.add(form);
305
+ }
306
+ const literal = values.size ? new RegExp([...values].sort((a, b) => b.length - a.length).map(escape).join("|"), "g") : null;
307
+ return (text) => {
308
+ if (!text)
309
+ return text;
310
+ let out = literal ? text.replace(literal, REDACTED) : text;
311
+ for (const [shape, is] of SHAPES)
312
+ out = out.replace(shape, (m) => (is(m) ? REDACTED : m));
313
+ for (const [shape, keep] of CONTEXTS)
314
+ out = out.replace(shape, keep);
315
+ return cutAssignments(out);
316
+ };
317
+ }
318
+ /** Capture the turn's mutable set too, so stream callbacks keep their turn's redactor. */
319
+ export function redactor(...envs) {
320
+ const scope = turnSecrets.getStore();
321
+ const cut = environmentRedactor(...envs);
322
+ return (text) => cut(cutRootSecrets(cutTurnSecrets(text, scope)));
323
+ }
324
+ let own = null;
325
+ /** Cuts this process's secrets, root redaction-only values, and the current turn's secrets. */
326
+ export function redact(text) {
327
+ own ??= environmentRedactor(process.env);
328
+ return own(cutRootSecrets(cutTurnSecrets(text, turnSecrets.getStore())));
329
+ }
@@ -0,0 +1,175 @@
1
+ // Conversation scopes on a shared relay process (docs/d9-isolation-plan.md). The Claude desktop
2
+ // app runs one relay for many conversations and forwards no per-conversation key, so relay issues
3
+ // each conversation a token its model carries on every call (the design's capability fallback).
4
+ // The token is a bearer capability: it separates conversations that use relay honestly, and
5
+ // whoever presents it acts as its conversation. Relay keeps only its owner hash, which stands
6
+ // where a process token stood before (runs.root_token, request_id scopes, the env broker).
7
+ // OpenCode 2 runs one relay for all the sessions of its background service, and stamps every call
8
+ // with the session it comes from: there the stamp, not a token, picks the view (hostSessionOwner).
9
+ import crypto from "node:crypto";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { relayHome } from "./config.js";
13
+ import { db } from "./db.js";
14
+ import { procStart } from "./procs.js";
15
+ import { ownerOpen } from "./adoption.js";
16
+ import { SESSION_TOKEN_SHAPE } from "./secrets.js";
17
+ const PREFIX = "rs1_";
18
+ const NONCE = 16, TAG = 12;
19
+ /** A token-shaped string in any case, wherever it appears: never forwarded to another agent (server.ts), cut from agents' output (secrets.ts). */
20
+ export const TOKEN_SHAPE = SESSION_TOKEN_SHAPE;
21
+ /** What relay issues and accepts: lowercase only. */
22
+ const TOKEN = new RegExp(`^${TOKEN_SHAPE.source}$`);
23
+ /**
24
+ * The relay home's session key, created on first need. Written to a temporary name and linked
25
+ * into place, so that processes starting together agree on one key and none reads a partial one.
26
+ * It lets its holder mint new, empty sessions; it reveals no existing token. Read on every use,
27
+ * so that deleting it revokes every token at once, in running processes too.
28
+ */
29
+ function sessionKey() {
30
+ const file = path.join(relayHome(), "session.key");
31
+ const read = () => {
32
+ try {
33
+ const k = fs.readFileSync(file);
34
+ if (k.length !== 32)
35
+ throw new Error(`relay's session key ${file} is damaged; remove it to revoke every session token and start over`);
36
+ return k;
37
+ }
38
+ catch (err) {
39
+ if (err.code === "ENOENT")
40
+ return null;
41
+ throw err;
42
+ }
43
+ };
44
+ let key = read();
45
+ if (!key) {
46
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
47
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}`;
48
+ fs.writeFileSync(tmp, crypto.randomBytes(32), { mode: 0o600, flag: "wx" });
49
+ try {
50
+ fs.linkSync(tmp, file);
51
+ }
52
+ catch (err) {
53
+ if (err.code !== "EEXIST")
54
+ throw err;
55
+ }
56
+ finally {
57
+ fs.rmSync(tmp, { force: true });
58
+ }
59
+ key = read();
60
+ if (!key)
61
+ throw new Error(`relay could not create its session key ${file}`);
62
+ }
63
+ return key;
64
+ }
65
+ const tag = (nonce) => crypto.createHmac("sha256", sessionKey()).update("relay-session-v1").update(nonce).digest().subarray(0, TAG);
66
+ /** A new conversation token. Nothing is recorded: a token exists by its valid tag alone. */
67
+ export function issueSessionToken() {
68
+ const nonce = crypto.randomBytes(NONCE);
69
+ return PREFIX + Buffer.concat([nonce, tag(nonce)]).toString("hex");
70
+ }
71
+ /** The owner hash a valid token stands for, or null for anything relay did not issue under this home's key. */
72
+ export function sessionOwner(raw) {
73
+ if (typeof raw !== "string" || !TOKEN.test(raw))
74
+ return null;
75
+ const bytes = Buffer.from(raw.slice(PREFIX.length), "hex");
76
+ if (!crypto.timingSafeEqual(bytes.subarray(NONCE), tag(bytes.subarray(0, NONCE))))
77
+ return null;
78
+ return crypto.createHash("sha256").update("relay-session-owner-v1").update(raw).digest("hex");
79
+ }
80
+ /**
81
+ * One conversation's view of a shared root instance: its own owner token, default run and
82
+ * delivery state; the process's context, client and host profile read through. Assigning a
83
+ * read-through field on a view throws, so per-conversation code cannot change the process.
84
+ * via says what chose it: a session token its model carries, or the host's own session key.
85
+ */
86
+ export function sessionView(base, owner, via = "token") {
87
+ const view = {
88
+ runId: null, token: owner, ...(via === "token" ? { carried: true } : { keyed: true }),
89
+ get hostKey() { return base.hostKey; },
90
+ handedOff: new Set(), asking: new Map(), noted: new Set(),
91
+ since: new Map(), waiting: new Map(), reapedAt: undefined,
92
+ get ctx() { return base.ctx; }, get cwd() { return base.cwd; }, get family() { return base.family; },
93
+ get registration() { return base.registration; }, get clientName() { return base.clientName; },
94
+ get desktopEntry() { return base.desktopEntry; }, get host() { return base.host; },
95
+ get singletonStamps() { return base.singletonStamps; }, get singletonViolation() { return base.singletonViolation; },
96
+ };
97
+ return view;
98
+ }
99
+ /**
100
+ * The owner a host session key stands for in this process. The key is no secret (OpenCode keeps it
101
+ * in its logs and database), so it is bound to the process's own random token: it keeps sessions
102
+ * apart within the process, and gives no claim on work after a restart, which stays orphaned until
103
+ * the person adopts it, as for a dedicated session.
104
+ */
105
+ export function hostSessionOwner(base, kind, key) {
106
+ return crypto.createHash("sha256").update("relay-host-session-v1").update(JSON.stringify([base.token, kind, key])).digest("hex");
107
+ }
108
+ /**
109
+ * A view for a token presented again, after a restart or an eviction: membership is the owner
110
+ * hash, so the conversation keeps its runs. Its events come from each run's creation, it goes on
111
+ * in its latest run that is not cancelled, and it takes over the lease of runs whose recorded
112
+ * process is gone, so that they no longer look orphaned to relay adopt.
113
+ */
114
+ export function hydrate(view) {
115
+ const runs = db().prepare("SELECT * FROM runs WHERE root_token = ? ORDER BY created_at, id").all(view.token);
116
+ for (const r of runs) {
117
+ view.since.set(r.id, r.created_at);
118
+ if (r.status !== "cancelled")
119
+ view.runId = r.id;
120
+ if (!ownerOpen(r)) {
121
+ db().prepare("UPDATE runs SET root_pid = ?, root_start = ? WHERE id = ? AND root_token = ?").run(process.pid, procStart(process.pid), r.id, view.token);
122
+ }
123
+ }
124
+ return view;
125
+ }
126
+ /**
127
+ * The conversation views of one shared process: a bounded cache. A view is pinned while any call
128
+ * acts as it (acquire to release), and while it has a wait or a question open, and is never
129
+ * evicted then: a conversation never has two views at once.
130
+ */
131
+ export class SessionViews {
132
+ base;
133
+ max;
134
+ views = new Map();
135
+ active = new Map();
136
+ constructor(base, max = 256) {
137
+ this.base = base;
138
+ this.max = max;
139
+ }
140
+ /** The conversation's view, pinned until release: hydrated from the registry when not cached. */
141
+ acquire(owner, via = "token") {
142
+ let view = this.views.get(owner);
143
+ if (view)
144
+ this.views.delete(owner);
145
+ else
146
+ view = hydrate(sessionView(this.base, owner, via));
147
+ this.views.set(owner, view);
148
+ this.active.set(view, (this.active.get(view) ?? 0) + 1);
149
+ for (const [k, v] of this.views) {
150
+ if (this.views.size <= this.max)
151
+ break;
152
+ if (!this.active.has(v) && !v.waiting.size && !v.asking.size)
153
+ this.views.delete(k);
154
+ }
155
+ return view;
156
+ }
157
+ release(view) {
158
+ const n = (this.active.get(view) ?? 1) - 1;
159
+ if (n > 0)
160
+ this.active.set(view, n);
161
+ else
162
+ this.active.delete(view);
163
+ }
164
+ /** Whether a call acts as this owner now, or its view has a wait or a question open. */
165
+ inUse(owner) {
166
+ for (const v of this.active.keys())
167
+ if (v.token === owner)
168
+ return true;
169
+ const view = this.views.get(owner);
170
+ return Boolean(view && (view.waiting.size || view.asking.size));
171
+ }
172
+ all() { return [...this.views.values()]; }
173
+ }
174
+ /** Whether any work of runs this owner holds is queued or running, so that its environment broker is still wanted. */
175
+ export const ownerBusy = (owner) => Boolean(db().prepare("SELECT 1 FROM nodes n JOIN runs r ON r.id = n.run_id WHERE r.root_token = ? AND n.status IN ('queued', 'running') LIMIT 1").get(owner));