@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
+ // Codex: relay is an [mcp_servers.relay] table relay writes into Codex's config.toml, and its
2
+ // skills come as a plugin from a local marketplace pointing at adapters/codex.
3
+ import { codexOwn, reportFamilies } from "../core/steering.js";
4
+ import { createHash } from "node:crypto";
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { spawnFound } from "../core/executables.js";
9
+ import { editCodexConfig, isTable, readToml, relayServer } from "../core/toml.js";
10
+ import { config, entriesState, errText, first, installKind, jsonText as json, judge, LAUNCHER, MARKETPLACE, NO_SERVER, note, objection, PLUGIN, planKit, readText, reinstallCommand, removable, removeFile, requireCli, say, sh, versionDir, writeFile, } from "../install/common.js";
11
+ import { otherFamilies, otherTargets, TARGETS, targetDef } from "../targets/index.js";
12
+ import { briefSkill } from "./types.js";
13
+ import { hostWaitCapS } from "../mcp/host.js";
14
+ import { CODEX_MCP_ENV_VARS, codexToolTimeoutS } from "../targets/codex.js";
15
+ import { DEFAULT_CONFIG, relayCodexHome } from "../core/config.js";
16
+ import { codexHomeProblem, codexLoginCommand } from "../backends/codex-pin.js";
17
+ /** A plugin skill as Codex names it: $relay-delegate. */
18
+ const skillRef = (skill) => `$relay-${skill}`;
19
+ /** Codex's plugin: skills are invoked as $relay-<name>, plus a snippet for AGENTS.md. */
20
+ function writeAdapter({ out, version, description, skills, write }) {
21
+ write(path.join(out, ".agents", "plugins", "marketplace.json"), json({
22
+ name: MARKETPLACE, interface: { displayName: "relay (local)" },
23
+ plugins: [{ name: "relay", source: { source: "local", path: "./relay" }, policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" }, category: "Developer Tools" }],
24
+ }));
25
+ write(path.join(out, "relay", ".codex-plugin", "plugin.json"), json({ name: "relay", version, description, skills: "./skills/" }));
26
+ for (const [name, s] of Object.entries(skills)) {
27
+ // A reference skill is for the agent to load itself, so it is not kept to the user's asking.
28
+ const description = s.reference ? s.description : `${s.description} Use only when the user asks for it by name.`;
29
+ const request = s.reference ? "" : `The user's request follows the skill name (usage: \`${skillRef(name)} ${s.hint}\`).\n\n`;
30
+ write(path.join(out, "relay", "skills", `relay-${name}`, "SKILL.md"), `---\nname: relay-${name}\ndescription: ${description}\n---\n\n${request}${s.body}\n\nThe relay tools are the tools of the \`relay\` MCP server.\n`);
31
+ }
32
+ const briefs = otherTargets("codex").map((t) => `\`${skillRef(briefSkill(t.id))}\``).join(", ");
33
+ write(path.join(out, "AGENTS.snippet.md"), `## relay\n\nThe \`relay\` MCP server reaches coding agents of other families from here (${otherFamilies("codex")}): it fills the gaps between families. ${codexOwn} \`delegate\` a well-defined chunk of work (then \`status\`, \`resume\`, \`result\`, \`merge\`), \`ask\` a question mid-task (pass \`thread_id\` to follow up), \`discuss\` a question turn by turn with you as one side, or get an independent \`review\` to set against your own. ${reportFamilies} Leave \`target\` out unless the user names an agent; relay uses your default, or asks you to name one. Use your own judgment about when any of these is worth it. Before you write the other agent a task or question, read relay's brief on writing for it: the plugin's skill (${briefs}), or relay's \`brief\` tool without the plugin. A refusal from relay explains why; carry on yourself.\n\nWhen the user writes \`relay delegate|ask|discuss|review|tree|chat …\`, do that with the matching tool (for \`tree\`, call \`status\` with no id; for \`chat\`, run \`relay chat <id> --print\` or \`--say\`).\n`);
34
+ }
35
+ export const codexConfigFile = () => path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "config.toml");
36
+ /** Codex's default tool timeout also applies when its registration omits the field. */
37
+ export const CODEX_DEFAULT_TOOL_TIMEOUT_S = 60;
38
+ /** Read the root's registration, never the timeout of an unrelated launched child's host. */
39
+ export function registeredCodexToolTimeoutS() {
40
+ try {
41
+ const parsed = readToml(fs.readFileSync(codexConfigFile(), "utf8"));
42
+ const entry = parsed.ok ? relayServer(parsed.data) : undefined;
43
+ const timeout = isTable(entry) ? entry.tool_timeout_sec : undefined;
44
+ if (typeof timeout === "number" && Number.isFinite(timeout) && timeout > 0)
45
+ return timeout;
46
+ }
47
+ catch {
48
+ // Missing/unreadable config: end waits below Codex's default instead of guessing a long cap.
49
+ }
50
+ return CODEX_DEFAULT_TOOL_TIMEOUT_S;
51
+ }
52
+ // Before 1.0, builds of relay wrote a Codex subagent role for each target of another family,
53
+ // agents/relay-<target>.toml beside config.toml (the proxy role), which handed its task to relay and
54
+ // waited. No release shipped it and relay writes none now. Install and uninstall take out the ones
55
+ // relay wrote, saved first, and leave alone any file of that name relay did not write, as
56
+ // `install claude-desktop` does with relay's entry under its earlier name.
57
+ const ROLE_MARKER = "# Written by relay from ";
58
+ const ROLE_DEFAULTS = "# relay role defaults: ";
59
+ const roleFile = (id) => path.join(path.dirname(codexConfigFile()), "agents", `relay-${id}.toml`);
60
+ /** A field's value as relay's role files recorded it: tables with their keys sorted, so that the order they are written in does not count. */
61
+ const roleHash = (value) => createHash("sha256").update(JSON.stringify(value, (_, v) => typeof v === "bigint" ? `${v}n` : isTable(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1))) : v)).digest("hex");
62
+ /**
63
+ * Whose a file at a role's path is. Relay's carries its marker on the first line and, on the second,
64
+ * a hash of each field as relay wrote it: relay's as written (own), relay's with fields changed
65
+ * since (customised), or not relay's (foreign).
66
+ */
67
+ function oldRole(text) {
68
+ const [marker, defaults] = text.split(/\r?\n/);
69
+ if (!marker.startsWith(ROLE_MARKER))
70
+ return { state: "foreign", note: "no relay ownership marker" };
71
+ const parsed = readToml(text);
72
+ if (!parsed.ok)
73
+ return { state: "customised", extras: [`it no longer parses as TOML (${parsed.error})`] };
74
+ let baseline = null;
75
+ try {
76
+ if (defaults?.startsWith(ROLE_DEFAULTS))
77
+ baseline = JSON.parse(defaults.slice(ROLE_DEFAULTS.length));
78
+ }
79
+ catch {
80
+ // Read as changed, below.
81
+ }
82
+ if (!isTable(baseline))
83
+ return { state: "customised", extras: ["relay ownership comments changed"] };
84
+ const keys = new Set([...Object.keys(parsed.data), ...Object.keys(baseline)]);
85
+ const changed = [...keys].filter((key) => (Object.hasOwn(parsed.data, key) ? roleHash(parsed.data[key]) : null) !== (baseline[key] ?? null));
86
+ return changed.length ? { state: "customised", extras: changed } : { state: "own", note: "relay's proxy role from before 1.0" };
87
+ }
88
+ /**
89
+ * Takes out the proxy roles relay wrote before 1.0: one per target of another family beside this
90
+ * config.toml, and any the installation record lists elsewhere (CODEX_HOME may have moved). A role
91
+ * someone changed is removed by install only with --force, as replacing it would be; uninstall
92
+ * removes it either way. Each is saved first. A file relay did not write is left alone, --force or not.
93
+ */
94
+ function planOldRoles(run) {
95
+ const recorded = Object.entries(run.record.hosts.codex?.resources ?? {})
96
+ .filter(([key, c]) => /^role:[a-z0-9-]+$/.test(key) && c.action !== "removed" && c.file)
97
+ .map(([key, c]) => [path.resolve(c.file), key]);
98
+ const files = new Map([...TARGETS.filter((t) => t.vendor !== targetDef("codex").vendor).map((t) => [roleFile(t.id), `role:${t.id}`]), ...recorded]);
99
+ const problems = [];
100
+ const steps = [];
101
+ for (const [file, resource] of files) {
102
+ let before;
103
+ try {
104
+ before = readText(file);
105
+ }
106
+ catch (err) {
107
+ steps.push(() => say(`# left alone: ${errText(err)}`));
108
+ continue;
109
+ }
110
+ if (!before)
111
+ continue;
112
+ const found = oldRole(before.text);
113
+ if (found.state === "foreign") {
114
+ steps.push(() => say(`# left alone: ${file} is not a role relay wrote (${found.note})`));
115
+ continue;
116
+ }
117
+ if (run.verb === "install" && found.state === "customised" && !run.force) {
118
+ problems.push(`${file} is relay's Codex proxy role from before 1.0, which relay no longer installs, but it has changes relay did not make (${found.extras.join(", ")}). ` +
119
+ "Run this again with --force to remove it anyway (it is saved first), or remove it yourself.");
120
+ continue;
121
+ }
122
+ steps.push(() => {
123
+ say(`# remove relay's Codex proxy role ${file}: relay no longer installs one`);
124
+ removeFile(run, file, before, resource, { action: "removed", what: `removed relay's Codex proxy role ${file}, which relay no longer installs`, undo: null });
125
+ });
126
+ }
127
+ return { problems, apply() { for (const step of steps)
128
+ step(); } };
129
+ }
130
+ const KIT = {
131
+ dir: "codex", hostName: "Codex", verbs: { add: "add", remove: "remove" }, manifestDir: ".codex-plugin",
132
+ marketplaces: (listed) => (isTable(listed) ? listed.marketplaces : undefined),
133
+ localSource: (raw) => (isTable(raw.marketplaceSource) && raw.marketplaceSource.sourceType === "local" ? raw.marketplaceSource.source : undefined),
134
+ plugins: (listed) => (isTable(listed) ? listed.installed : undefined),
135
+ isRelayPlugin: (p) => p.pluginId === PLUGIN && p.installed !== false,
136
+ // Codex's list does not name its copy; `codex plugin add` puts it at $CODEX_HOME/plugins/cache/<marketplace>/<plugin>/<version> (codex-cli 0.162.1).
137
+ copyOf: (p) => {
138
+ const v = versionDir(p.version);
139
+ return v ? path.join(path.dirname(codexConfigFile()), "plugins", "cache", MARKETPLACE, "relay", v) : null;
140
+ },
141
+ };
142
+ export const codexBlock = () => [
143
+ "[mcp_servers.relay]",
144
+ `command = ${JSON.stringify(LAUNCHER)}`,
145
+ 'args = ["mcp", "--host", "codex"]',
146
+ `env_vars = ${JSON.stringify(CODEX_MCP_ENV_VARS)}`,
147
+ `tool_timeout_sec = ${codexToolTimeoutS(DEFAULT_CONFIG.approval_timeout_s)}`,
148
+ "startup_timeout_sec = 30",
149
+ 'default_tools_approval_mode = "approve"',
150
+ "",
151
+ "# Deciding a launched agent's approval request is the one relay call Codex should confirm with you.",
152
+ "[mcp_servers.relay.tools.approve]",
153
+ 'approval_mode = "prompt"',
154
+ "",
155
+ ].join("\n");
156
+ /** 3600 was relay's previous shipped default, so its upgrade is a managed change. Other
157
+ * custom timeouts and every other customization still require the installer's usual review. */
158
+ function judgeCodex(existing, intended) {
159
+ const knownDefault = isTable(existing) && existing.tool_timeout_sec === 3600;
160
+ const found = judge(knownDefault ? { ...existing, tool_timeout_sec: intended.tool_timeout_sec } : existing, intended);
161
+ return knownDefault && found.state === "identical" ? { state: "own", note: "relay's previous MCP timeout" } : found;
162
+ }
163
+ function planCodex(run) {
164
+ const cfg = config();
165
+ const bin = cfg.targets.codex.bin;
166
+ requireCli("codex", bin);
167
+ const file = codexConfigFile();
168
+ const block = codexBlock();
169
+ const intended = relayServer(readToml(block).data);
170
+ const removing = run.verb === "uninstall";
171
+ if (!removing)
172
+ say(`# relay's block in ${file}:\n${block}`);
173
+ const before = readText(file);
174
+ let found = { state: "absent" };
175
+ let existing;
176
+ if (before) {
177
+ const parsed = readToml(before.text);
178
+ if (parsed.ok)
179
+ existing = relayServer(parsed.data);
180
+ found = parsed.ok ? judgeCodex(existing, intended) : { state: "blocked", note: `${file} does not parse as TOML (${parsed.error}). Relay does not edit a file it cannot read: fix it first${removing ? "" : ", or add the block above by hand"}.` };
181
+ }
182
+ const what = `[mcp_servers.relay] in ${file}`;
183
+ let no = objection(what, found, run.force, removing ? "remove" : "replace");
184
+ // The record says which file relay was installed into. If Codex's home has moved since, this run would look in the wrong one.
185
+ const recorded = run.record.hosts.codex?.resources.config?.file;
186
+ if (removing && !no && recorded && path.resolve(recorded) !== path.resolve(file) && fs.existsSync(recorded)) {
187
+ no = `The installation record says relay was put into ${recorded}, but this run looks at ${file}: CODEX_HOME is not what it was. Run this again with CODEX_HOME=${sh([path.dirname(recorded)])}, so that relay is removed from where it was installed.`;
188
+ }
189
+ const foreign = found.state === "foreign" ? found.note : "";
190
+ const leave = removing && found.state === "foreign" && !removable(run, found, isTable(existing) ? existing.command : undefined);
191
+ // The edit is made and proved here, before anything is changed anywhere.
192
+ let next = null;
193
+ if (!no && !leave && found.state !== (removing ? "absent" : "identical")) {
194
+ const edit = editCodexConfig(before?.text ?? "", removing ? null : block);
195
+ if (edit.ok)
196
+ next = edit.text;
197
+ else
198
+ no = `${file}: ${edit.reason}`;
199
+ }
200
+ const oldRoles = planOldRoles(run);
201
+ const plugin = planKit(run, KIT, bin);
202
+ const reverse = reinstallCommand(removing ? "install" : "uninstall", "codex");
203
+ return {
204
+ problems: [...(no ? [no] : []), ...oldRoles.problems, ...plugin.problems],
205
+ apply() {
206
+ // The config is edited before Codex's own commands run: they rewrite the same file.
207
+ if (leave)
208
+ say(`# left alone: ${what} is not relay's (${foreign}). --force removes it.`);
209
+ else if (next === null)
210
+ say(removing ? `# ${file} has no [mcp_servers.relay]` : `# ${file} already has relay's block for this ${installKind()}`);
211
+ else {
212
+ say(removing ? `# remove relay's [mcp_servers.relay] tables from ${file}` : `# ${found.state === "absent" ? "add the block to" : "replace relay's block in"} ${file}`);
213
+ writeFile(run, file, before, next, "config", {
214
+ action: removing ? "removed" : found.state === "absent" ? "added" : "replaced",
215
+ what: removing ? `removed relay's [mcp_servers.relay] tables from ${file}` : `${found.state === "absent" ? "added relay's block to" : "replaced the [mcp_servers.relay] tables in"} ${file}`,
216
+ undo: `${reverse}${removing ? "" : " (takes out relay's tables only)"}`,
217
+ });
218
+ }
219
+ if (!removing && next === null)
220
+ note(run, "config", { action: "kept", what: `${file} already had relay's block`, backup: null, undo: reverse });
221
+ oldRoles.apply();
222
+ plugin.apply();
223
+ },
224
+ };
225
+ }
226
+ export const codexHost = {
227
+ id: "codex",
228
+ target: "codex",
229
+ name: "Codex",
230
+ plan: planCodex,
231
+ adapter: { dir: "codex", ref: skillRef, write: writeAdapter },
232
+ registered() {
233
+ try {
234
+ const file = codexConfigFile();
235
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
236
+ if (text === null)
237
+ return "none";
238
+ const parsed = readToml(text);
239
+ if (!parsed.ok)
240
+ throw new Error(parsed.error);
241
+ const entry = relayServer(parsed.data);
242
+ return entriesState(entry);
243
+ }
244
+ catch {
245
+ return "unknown";
246
+ }
247
+ },
248
+ // The command is the CLI's own, documented under `codex login`. It reads stored credentials and
249
+ // makes no model request. Relay prints only the method: no account, no key. Asked of relay's Codex
250
+ // home, the login relay's Codex jobs run under (since 1.1.0), not of ~/.codex, which is the
251
+ // person's own Codex sessions' and is not read by relay's jobs.
252
+ doctorLogin(cfg, { line, warn, fail }) {
253
+ const home = relayCodexHome(cfg);
254
+ // A home that is not relay's is reported on the codex home line; its login is not relay's either.
255
+ if (codexHomeProblem(cfg))
256
+ return line("codex login", `not checked: relay will not use ${home} as its Codex home (see the codex home line)`);
257
+ const signIn = fs.existsSync(home) ? codexLoginCommand(cfg) : `relay install codex --write (which makes it), then ${codexLoginCommand(cfg)}`;
258
+ // Codex refuses a CODEX_HOME that does not exist, with a message that names no login.
259
+ if (!fs.existsSync(home))
260
+ return fail("codex login", `relay's Codex home ${home} does not exist yet, so relay's Codex jobs have no login. Run ${signIn}`);
261
+ const r = spawnFound(cfg.targets.codex.bin, ["login", "status"], { encoding: "utf8", env: { ...process.env, CODEX_HOME: home } });
262
+ // Kept to the method: a key login is printed by Codex with part of the key.
263
+ const said = first(`${r.stdout ?? ""}${r.stderr ?? ""}`).replace(/\s+-\s+.*$/, "").replace(/\bsk-\S+/g, "sk-…");
264
+ if (/not logged in/i.test(said))
265
+ fail("codex login", `relay's Codex home ${home} is not signed in, according to \`codex login status\` there. Sign in once with ${signIn}`);
266
+ else if (!r.error && r.status === 0 && said)
267
+ line("codex login", `${said}, in relay's Codex home ${home} (as \`codex login status\` reports it there)`);
268
+ else
269
+ warn("codex login", `\`codex login status\` did not say; relay cannot tell whether its Codex home ${home} is signed in (${signIn})`);
270
+ },
271
+ doctorRegistration(cfg, present, { line, warn, registration }) {
272
+ /** What doctor says of relay's registration, from Codex's own report or from its config.toml. */
273
+ const inspect = (transport, rawTimeout, extra = "") => {
274
+ const timeout = typeof rawTimeout === "bigint" ? Number(rawTimeout) : rawTimeout;
275
+ registration("codex mcp", "codex", transport.command, transport.args, `${timeout ? `, tool_timeout_sec=${timeout}` : ""}${extra}`);
276
+ for (const name of CODEX_MCP_ENV_VARS)
277
+ if (!Array.isArray(transport.env_vars) || !transport.env_vars.includes(name)) {
278
+ const why = name === "CODEX_HOME" ? "review withholding needs it to locate the caller's transcripts" : "T3 detection cannot work";
279
+ warn("codex mcp", `missing env_vars entry for ${name}: ${why}. Update it: ${reinstallCommand("install", "codex")}`);
280
+ }
281
+ if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0) {
282
+ warn("", "no valid tool_timeout_sec: relay caps waits below Codex's 60 s default (50 s per call). Set an explicit positive timeout in config.toml for longer waits; restart the session after changing it");
283
+ }
284
+ else if (hostWaitCapS(timeout) < 2 * cfg.block_s) {
285
+ warn("", `tool_timeout_sec=${timeout}: relay enforces a shared wait cap of ${hostWaitCapS(timeout)} s per call, including nested waits. Long waits return early (status says wait_ended), with pending events. Raise tool_timeout_sec in config.toml and restart the session if longer waits are needed`);
286
+ }
287
+ };
288
+ // No Codex relay checked as a target (the target is disabled, or its pin is not in place):
289
+ // relay runs no codex binary for it, so the registration is read from Codex's config.toml itself.
290
+ if (!present.codex) {
291
+ const file = codexConfigFile();
292
+ let text;
293
+ try {
294
+ text = fs.readFileSync(file, "utf8");
295
+ }
296
+ catch {
297
+ return;
298
+ } // no Codex configuration: nothing registered to inspect
299
+ const parsed = readToml(text);
300
+ if (!parsed.ok)
301
+ return warn("codex mcp", `relay could not read ${file} (${parsed.error})`);
302
+ const entry = relayServer(parsed.data);
303
+ if (entry === undefined)
304
+ return line("codex mcp", `relay NOT registered in ${file} (${reinstallCommand("install", "codex")})`);
305
+ if (!isTable(entry))
306
+ return warn("codex mcp", `a server named relay is in ${file}, but not as a table relay can read`);
307
+ return inspect(entry, entry.tool_timeout_sec, `; read from ${file}, without running Codex`);
308
+ }
309
+ const r = spawnFound(cfg.targets.codex.bin, ["mcp", "get", "relay", "--json"], { encoding: "utf8" });
310
+ if (r.status !== 0 && NO_SERVER.test(`${r.stdout ?? ""}${r.stderr ?? ""}`))
311
+ line("codex mcp", `relay NOT registered (${reinstallCommand("install", "codex")})`);
312
+ else if (r.status !== 0)
313
+ warn("codex mcp", `\`codex mcp get relay --json\` failed: ${first(r.stderr ?? "") || `exit ${r.status}`}`);
314
+ else {
315
+ let got;
316
+ try {
317
+ got = JSON.parse(r.stdout);
318
+ }
319
+ catch {
320
+ // Older output format; reported below.
321
+ }
322
+ const transport = isTable(got) && isTable(got.transport) ? got.transport : null;
323
+ if (!transport)
324
+ warn("codex mcp", "a server named relay is registered, but relay could not read what `codex mcp get relay --json` printed");
325
+ else
326
+ inspect(transport, got.tool_timeout_sec);
327
+ }
328
+ },
329
+ };
@@ -0,0 +1,20 @@
1
+ // The Claude desktop app's own relay entry: its name, the name it had before, and what it is, for
2
+ // install and doctor to say (README, "Claude desktop app and Cowork").
3
+ //
4
+ // Seen 2026-10-16 (Claude.app 2.42304.0, Claude Code 2.1.299 in the app): the app starts relay from
5
+ // its entry outside any project, once for its chats and once for Cowork and the Code tab together,
6
+ // and passes the second one's tools into each of those sessions as a server named after the entry.
7
+ // Nothing the app sends tells the sessions apart over one connection, so each conversation's model
8
+ // carries a session token relay issued it (docs/d9-isolation-plan.md). Under the name `relay` those tools hid
9
+ // the ones of the relay Claude Code starts in a Code tab session from its own registration, hence
10
+ // the entry's own name. The app's tool calls time out after 60 s, and a timeout restarts the shared
11
+ // relay for every session, so waits there end sooner (src/mcp/host.ts DESKTOP_WAIT_S).
12
+ import { DESKTOP_WAIT_S } from "../mcp/host.js";
13
+ import { SHARED_REASON } from "../core/identity.js";
14
+ /** The entry's name under mcpServers. */
15
+ export const DESKTOP_ENTRY = "relay-desktop";
16
+ /** The name relay's entry had before (0.2.0 and the 0.9 release candidates). Install moves it. */
17
+ export const DESKTOP_OLD_ENTRY = "relay";
18
+ export const DESKTOP_SHARED = `${DESKTOP_ENTRY} is the desktop app's own relay, and is shared. ${SHARED_REASON} The token is a bearer key its model holds: it separates conversations that use relay honestly. ` +
19
+ "Configuration describes the topology; doctor does not observe calls or verify which conversation used it. Claude.app 2.42304.0's code was checked on 2026-10-17: neither process forwards per-conversation metadata. Pass cwd on merge and on starts (a new ask without it consults in a new, empty directory of its own); " +
20
+ `no session on this shared entry gets an approval dialog, confirm or notices, and its waits end after ${DESKTOP_WAIT_S} s, under the app's 60 s tool timeout (README, "Claude desktop app and Cowork").`;
@@ -0,0 +1,11 @@
1
+ // The registry of hosts. Adding one is a module beside claude.ts and a line here.
2
+ import { claudeDesktopHost } from "./claude-desktop.js";
3
+ import { claudeHost } from "./claude.js";
4
+ import { codexHost } from "./codex.js";
5
+ import { HOST_IDS } from "./types.js";
6
+ export { briefSkill, HOST_IDS } from "./types.js";
7
+ export const HOSTS = [claudeHost, codexHost, claudeDesktopHost];
8
+ if (HOSTS.map((h) => h.id).join() !== HOST_IDS.join())
9
+ throw new Error("relay's host registry does not match HOST_IDS");
10
+ export const isHost = (id) => typeof id === "string" && HOST_IDS.includes(id);
11
+ export const hostDef = (id) => HOSTS.find((h) => h.id === id);
@@ -0,0 +1,4 @@
1
+ /** Every host relay installs into, in the order install, doctor and the usage text list them. */
2
+ export const HOST_IDS = ["claude", "codex", "claude-desktop"];
3
+ /** The reference skill carrying the brief on writing tasks for a target: write-for-codex. */
4
+ export const briefSkill = (target) => `write-for-${target}`;
@@ -0,0 +1,18 @@
1
+ // The two things every relay command may need, kept apart from install and doctor so that the CLI
2
+ // can report its version or a usage mistake without loading either (or the registry, or zod).
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ /** A mistake in how relay was called: said on stderr, with exit code 2. */
6
+ export function usageError(message) {
7
+ console.error(message);
8
+ process.exitCode = 2;
9
+ }
10
+ /** Relay's version, from the package.json of this checkout (two levels above dist/install). */
11
+ export function relayVersion() {
12
+ try {
13
+ return String(JSON.parse(fs.readFileSync(path.resolve(import.meta.dirname, "..", "..", "package.json"), "utf8")).version);
14
+ }
15
+ catch {
16
+ return "unknown";
17
+ }
18
+ }
@@ -0,0 +1,133 @@
1
+ // Doctor's local /skills probe: the same isolated skill/plugin settings as a turn, no model
2
+ // prompt, no MCP servers, hooks or tools. /skills is the local command used by
3
+ // scripts/probe-skill-isolation.mjs. Stop at init, then verify the process ended without a result.
4
+ import { spawn } from "node:child_process";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import readline from "node:readline";
8
+ import { claudeSkillIsolation, claudeSkillsProblem } from "../backends/claude.js";
9
+ import { claudeTempPath } from "../backends/native-temp.js";
10
+ import { installedVersion } from "../backends/cli-version.js";
11
+ import { ensurePrivateRoot, nativeTempRoot } from "../confine/private-root.js";
12
+ import { privateTurnTemp } from "../confine/turn.js";
13
+ import { drainGroup, groupAlive, isGroupSignalRefusal, pidAlive, sendGroupSignal } from "../core/procs.js";
14
+ import { executable } from "../core/executables.js";
15
+ /**
16
+ * A probe failure is diagnostic only; it never makes doctor crash or changes launch policy. Claude
17
+ * gets a private temporary directory the way a turn does (native-temp.ts): one in ~/.rn, named
18
+ * through relay's short link on a long home, so that Claude does not fall back to shared /tmp
19
+ * during the probe either. The probe never makes the link: without it, it is not run and says so.
20
+ * `versionProblem` is the turn's check on Claude's version for that link.
21
+ */
22
+ export async function claudeInitProblem(bin, selected, versionProblem) {
23
+ let dir;
24
+ try {
25
+ dir = privateTurnTemp(ensurePrivateRoot(nativeTempRoot()), "");
26
+ let tmp;
27
+ try {
28
+ tmp = claudeTempPath(dir, versionProblem, { create: false });
29
+ }
30
+ catch (err) {
31
+ return `Claude's init-only probe was not run: ${err.message}`;
32
+ }
33
+ const env = { ...selected, TMPDIR: tmp, CLAUDE_CODE_TMPDIR: tmp,
34
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1",
35
+ CLAUDE_CODE_DISABLE_REFUSAL_RETRY: "1", CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: "1" };
36
+ delete env.CLAUDECODE;
37
+ const settings = path.join(dir, "settings.json");
38
+ // The same plugin settings a turn on this version gets: cc-plugin-privacy left on where relay keeps it.
39
+ fs.writeFileSync(settings, JSON.stringify({ ...claudeSkillIsolation(dir, env, installedVersion("claude", bin, selected)), disableAllHooks: true,
40
+ fastMode: false, env: { TMPDIR: tmp, CLAUDE_CODE_TMPDIR: tmp, CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS: "0" } }));
41
+ let exe;
42
+ try {
43
+ exe = executable(bin, env.PATH);
44
+ }
45
+ catch (err) {
46
+ return `Claude's init-only probe could not start (${err.code ?? "error"})`;
47
+ }
48
+ const child = spawn(exe, ["-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence",
49
+ "--setting-sources", "", "--settings", settings, "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}',
50
+ "--tools", "", "--permission-mode", "dontAsk", "--permission-prompts", "none", "/skills"], { cwd: dir, env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
51
+ let init, result = false, assistant = false, problem;
52
+ let stoppedAtInit = false, bytes = 0;
53
+ const stop = () => {
54
+ if (!child.pid)
55
+ return;
56
+ try {
57
+ sendGroupSignal(child.pid, "SIGKILL");
58
+ }
59
+ catch (err) {
60
+ if (!isGroupSignalRefusal(err))
61
+ child.kill("SIGKILL");
62
+ }
63
+ };
64
+ const lines = readline.createInterface({ input: child.stdout });
65
+ lines.on("line", (line) => {
66
+ if (line.length > 1024 * 1024) {
67
+ problem = "Claude's init report exceeded the probe limit";
68
+ stop();
69
+ return;
70
+ }
71
+ // Nothing after init is read. The prompt is the local /skills command, with no tools and no
72
+ // MCP servers, so its own reply can already be queued behind init when the stop lands; that
73
+ // is no model work. A result or assistant event before init is what this check is for.
74
+ if (stoppedAtInit)
75
+ return;
76
+ let event;
77
+ try {
78
+ event = JSON.parse(line);
79
+ }
80
+ catch {
81
+ return;
82
+ }
83
+ if (event?.type === "result") {
84
+ result = true;
85
+ stop();
86
+ }
87
+ if (event?.type === "assistant") {
88
+ assistant = true;
89
+ stop();
90
+ }
91
+ if (!init && event?.type === "system" && event.subtype === "init") {
92
+ init = event;
93
+ stoppedAtInit = true;
94
+ stop();
95
+ }
96
+ });
97
+ child.stdout.on("data", (chunk) => {
98
+ bytes += chunk.length;
99
+ if (bytes > 1024 * 1024) {
100
+ problem = "Claude's init stream exceeded the probe limit";
101
+ stop();
102
+ }
103
+ });
104
+ child.stderr.resume();
105
+ child.stdin.on("error", () => { });
106
+ child.stdin.end();
107
+ const timer = setTimeout(() => { problem = "Claude's init-only probe timed out"; stop(); }, 10_000);
108
+ try {
109
+ await new Promise((resolve) => {
110
+ child.once("error", (err) => { problem = `Claude's init-only probe could not start (${err.code ?? "error"})`; });
111
+ child.once("close", () => resolve());
112
+ });
113
+ }
114
+ finally {
115
+ clearTimeout(timer);
116
+ lines.close();
117
+ if (child.pid)
118
+ await drainGroup(child.pid);
119
+ }
120
+ const stopProblem = child.pid && (pidAlive(child.pid) || groupAlive(child.pid)) ? "Claude's init-only probe did not stop completely"
121
+ : result || assistant ? "Claude's init-only probe emitted a result or assistant event; relay could not verify a stop before model work"
122
+ : problem ?? (!init || !stoppedAtInit ? "Claude's init-only probe exited without an init report" : null);
123
+ // Even a failed stop must name an unfamiliar built-in if the init report exposed it.
124
+ return [init ? claudeSkillsProblem(init, undefined) : null, stopProblem].filter(Boolean).join(". ") || null;
125
+ }
126
+ catch (err) {
127
+ return `Claude's init-only probe failed (${err.code ?? "could not prepare or read init"})`;
128
+ }
129
+ finally {
130
+ if (dir)
131
+ fs.rmSync(dir, { recursive: true, force: true });
132
+ }
133
+ }