@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,604 @@
1
+ // A stub ACP agent standing in for Gemini CLI 0.64.0's `gemini --acp`, in the dialect relay's Gemini
2
+ // profile relies on (backends/gemini.ts; each point read in the 0.64.0 package, docs/gemini.md):
3
+ //
4
+ // - initialize offers Gemini's four login methods and no login state; loadSession, no session/resume.
5
+ // - authenticate {methodId: "gemini-api-key", _meta: {"api-key": <key>}} keeps the key in memory for
6
+ // the process's later sessions (GeminiAgent.authenticate). session/new and session/load sign in as
7
+ // the user settings say (security.auth.selectedType, in $GEMINI_CLI_HOME/.gemini/settings.json):
8
+ // with "gemini-api-key", from that key, else GEMINI_API_KEY in its environment; without either they
9
+ // fail with -32000 "Gemini API key is missing or not configured."
10
+ // - Its session lists a menu of models (as the real 0.64.0 listed it under relay's sandbox), not every
11
+ // id it takes: --model takes any id. The session reports --model, else "auto".
12
+ // - With security.environmentVariableRedaction on, the commands its tools run do not see variables
13
+ // that look like secrets (sanitizeEnvironment, 0.64.0); the stub drops them from its own
14
+ // environment once it has read the key, since its steps' commands inherit that.
15
+ // - In an untrusted folder (GEMINI_CLI_TRUST_WORKSPACE=false) no MCP server connects, the ones passed
16
+ // in session/new included, and its approval mode is "default".
17
+ // - Its command-based tool discovery runs in any folder, as 0.64.0's does (tool-registry.ts:376-540,
18
+ // no trust check), whenever a config of it is initialized: while it answers initialize, for its
19
+ // start-up config (acpRpcDispatcher.ts:81), and when each session is made or loaded
20
+ // (acpSessionManager.ts newSession, loadSession): tools.discoveryCommand from the user settings,
21
+ // split into words as shell-quote splits it and run without a shell; a non-zero exit, or output
22
+ // that is not a JSON list, fails initialize, session/new or session/load. Each function declaration
23
+ // (bare, or under function_declarations or functionDeclarations) becomes a tool named
24
+ // discovered_tool_<name>. A step's `call` names one so; it runs tools.callCommand, without a shell,
25
+ // with the tool's own name as its one argument and the arguments as JSON on stdin, its stdout the
26
+ // result; an error starting it, a non-zero exit, a signal or any stderr is a failure, reported to
27
+ // the model as 0.64.0 reports it (Stdout, Stderr, Error, Exit Code, Signal; tool-registry.ts:76-180).
28
+ // `tools` lists them. Both commands run with the environment its redaction leaves (above).
29
+ // STUB_GEMINI_SKIP_DISCOVERY: "1", it runs no discovery at all, as a release that changed when it
30
+ // runs it might, for relay's check at launch that discovery ran; "load", none for session/load only
31
+ // (initialize still runs it, as 0.64.0 does, which is what relay's check must not be fooled by).
32
+ // - initialize reports agentInfo.version as `--version` prints it (getVersion, the package's): 0.64.0,
33
+ // or STUB_VERSION's first word.
34
+ // - Its tool calls carry no rawInput: a shell command's title is the command, and its one text
35
+ // content says where it runs and why ("[in <dir_path>] (<description>)").
36
+ // - The prompt's response says which models answered in _meta.quota.model_usage[].model, and
37
+ // nothing else does. As 0.64.0 builds it (acpSession.ts, modelUsageMap): the main loop only, one
38
+ // entry per model in order of first use; the first round under the model it was routed to (its
39
+ // ModelInfo), every later round, after a tool call, under the configured id (--model, else
40
+ // "auto"). A session's first prompt here has one tool call (read_file-1), so two rounds; a loaded
41
+ // session's prompt has none, so one. A `routed` hook step
42
+ // names the model the first round was routed to (by Gemini's router, or a pin it promoted to a
43
+ // newer id); else the pin, or under an alias gemini-3.8-flash. (A fallback taken inside a round
44
+ // would be listed under the model that failed, which the stub does not model.)
45
+ // - With SANDBOX=sandbox-exec its runtime state (sessions) is under $GEMINI_CLI_HOME/.cache/.gemini,
46
+ // otherwise under $GEMINI_CLI_HOME/.gemini.
47
+ // - session/load answers first and then streams the conversation, one update at a time (0.64.0
48
+ // acpSessionManager.ts loadSession calls streamHistory without waiting for it, then returns): each
49
+ // earlier prompt as a user_message_chunk, then what the agent said and its tool call, ending with
50
+ // its reply, as acpSession.ts streamHistory sends them. STUB_GEMINI_REPLAY_STALL_MS pauses the
51
+ // replay before each prompt after the first; STUB_GEMINI_EXIT_IN_REPLAY has the agent die after
52
+ // replaying the first.
53
+ // - A prompt's first words come after the model's latency (STUB_GEMINI_LATENCY_MS, default 100). A
54
+ // loaded session's prompt is answered with text alone, no tool call (one round).
55
+ // - A prompt whose text starts with "/" or "$" and names one of its ACP commands (memory, extensions,
56
+ // init, restore, about, help) is run as that command, never reaching the model (acpSession.ts
57
+ // prompt, acpCommandHandler.ts), with an empty model_usage.
58
+ // - STUB_GEMINI_REPORT_MODEL: the session reports that model, whatever --model says.
59
+ // - STUB_GEMINI_REFUSE_SIGNIN: authenticate fails, its message quoting the key it was handed (as an
60
+ // error that quotes a request would).
61
+ // - At every start, unless the user settings turn general.sessionRetention off, it deletes each
62
+ // session file with nothing resumable in it, here one whose prompts all failed before a reply
63
+ // (0.64.0 gemini.tsx main, cleanupExpiredSessions; sessionUtils.ts getAllSessionFiles drops a file
64
+ // without hasResumableContent, and identifySessionsToDelete deletes every such file). It loads a
65
+ // session by its id whether or not it has a reply (acpSessionManager.ts loadSession, allowEmpty).
66
+ // - session/load of a session it has no file for fails as 0.64.0's does: -32603 "Internal error", with
67
+ // the reason in data.details ("Invalid session identifier …"). STUB_GEMINI_LOAD_ERROR fails every
68
+ // session/load so, for another reason, quoting the key it was handed in data.details.
69
+ //
70
+ // It runs under relay's own sandbox, so its records go to stderr as `STUB-RECORD <json>` lines, which
71
+ // relay keeps in the agent's log. It never records the key, only whether one came and its SHA-256.
72
+ import { spawn } from "node:child_process";
73
+ import crypto from "node:crypto";
74
+ import fs from "node:fs";
75
+ import net from "node:net";
76
+ import path from "node:path";
77
+ import readline from "node:readline";
78
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
79
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
80
+ import { procArgs } from "../procargs.mjs";
81
+ import { runSteps } from "../stub-agent.mjs";
82
+
83
+ /** What 0.64.0 names a discovered tool: this prefix and the name its declaration gives (tool-names.ts:237). */
84
+ const DISCOVERED_PREFIX = "discovered_tool_";
85
+ /**
86
+ * A command line in words, as shell-quote's parse splits one with no environment (0.64.0 parses
87
+ * tools.discoveryCommand so, tool-registry.ts:383): single quotes literal, backslashes and double
88
+ * quotes escaping, a variable expanded to nothing. Operators are not modelled; relay's has none.
89
+ */
90
+ function parseCommand(s) {
91
+ const words = [];
92
+ let word = null;
93
+ for (let i = 0; i < s.length; i++) {
94
+ const c = s[i];
95
+ if (/\s/.test(c)) {
96
+ if (word !== null) words.push(word);
97
+ word = null;
98
+ } else if (c === "'") {
99
+ const end = s.indexOf("'", i + 1);
100
+ if (end < 0) throw new Error(`unterminated quote in ${s}`);
101
+ word = (word ?? "") + s.slice(i + 1, end);
102
+ i = end;
103
+ } else if (c === '"') {
104
+ word ??= "";
105
+ for (i++; i < s.length && s[i] !== '"'; i++) {
106
+ if (s[i] === "\\" && i + 1 < s.length) word += s[++i];
107
+ else if (s[i] === "$") while (i + 1 < s.length && /\w/.test(s[i + 1])) i++;
108
+ else word += s[i];
109
+ }
110
+ } else if (c === "\\" && i + 1 < s.length) {
111
+ word = (word ?? "") + s[++i];
112
+ } else if (c === "$") {
113
+ word ??= "";
114
+ while (i + 1 < s.length && /\w/.test(s[i + 1])) i++;
115
+ } else {
116
+ word = (word ?? "") + c;
117
+ }
118
+ }
119
+ if (word !== null) words.push(word);
120
+ return words;
121
+ }
122
+ /** Runs a command without a shell, as 0.64.0 runs discovery and calls: what it wrote, and how it ended. */
123
+ function runCommand(command, args, input) {
124
+ return new Promise((resolve) => {
125
+ let stdout = "", stderr = "", error = null;
126
+ let child;
127
+ try {
128
+ child = spawn(command, args, { env: process.env });
129
+ } catch (err) {
130
+ return resolve({ stdout, stderr, error: String(err), code: null, signal: null });
131
+ }
132
+ child.stdout.on("data", (d) => (stdout += d));
133
+ child.stderr.on("data", (d) => (stderr += d));
134
+ child.on("error", (err) => (error = String(err)));
135
+ child.on("close", (code, signal) => resolve({ stdout, stderr, error, code, signal }));
136
+ if (input !== undefined) child.stdin.write(input);
137
+ child.stdin.end();
138
+ });
139
+ }
140
+
141
+ /** Gemini's model aliases (config/models.ts), which serve nothing themselves. */
142
+ const ALIASES = new Set(["auto", "pro", "flash", "flash-lite", "auto-gemini-3", "auto-gemini-2.5"]);
143
+ const MODES = [{ id: "default", name: "Default" }, { id: "autoEdit", name: "Auto Edit" }, { id: "yolo", name: "YOLO" }];
144
+ /** The menu the real 0.64.0's session listed under relay's sandbox, 2026-10-17 (buildAvailableModels). */
145
+ const MODELS = ["auto", "gemini-3.1-pro-preview-customtools", "gemini-3-flash-preview", "gemini-2.5-pro", "gemini-3.8-flash", "gemini-3.5-flash-lite"];
146
+ const AUTH_METHODS = [
147
+ { id: "oauth-personal", name: "Log in with Google", description: "Log in with your Google account" },
148
+ { id: "gemini-api-key", name: "Gemini API key", description: "Use an API key with Gemini Developer API", _meta: { "api-key": { provider: "google" } } },
149
+ { id: "vertex-ai", name: "Vertex AI", description: "Use an API key with Vertex AI GenAI API" },
150
+ { id: "gateway", name: "AI API Gateway", description: "Use a custom AI API Gateway", _meta: { gateway: { protocol: "google", restartRequired: "false" } } },
151
+ ];
152
+ /** Names and values Gemini's redaction keeps from its tools (environmentSanitization.ts, abridged). */
153
+ const SECRET_NAME = /TOKEN|SECRET|PASSWORD|PASSWD|KEY|AUTH|CREDENTIAL|CREDS|PRIVATE|CERT/i;
154
+ const SECRET_VALUE = /(https?|ftp|smtp):\/\/[^:\s]{1,1024}:[^@\s]{1,1024}@|AIzaSy[a-zA-Z0-9_\\-]{33}/i;
155
+
156
+ const record = (obj) => process.stderr.write(`STUB-RECORD ${JSON.stringify({ t: Date.now(), pid: process.pid, ...obj })}\n`);
157
+ const flag = (argv, name) => {
158
+ const i = argv.indexOf(name);
159
+ return i < 0 ? undefined : argv[i + 1];
160
+ };
161
+ const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");
162
+ const home = () => process.env.GEMINI_CLI_HOME ?? process.cwd();
163
+ const runtimeDir = () => (process.env.SANDBOX === "sandbox-exec" ? path.join(home(), ".cache", ".gemini") : path.join(home(), ".gemini"));
164
+ function settings() {
165
+ try {
166
+ return JSON.parse(fs.readFileSync(path.join(home(), ".gemini", "settings.json"), "utf8"));
167
+ } catch {
168
+ return {};
169
+ }
170
+ }
171
+
172
+ function sessionFile(id) {
173
+ const dir = path.join(runtimeDir(), "tmp", "stub", "chats");
174
+ fs.mkdirSync(dir, { recursive: true });
175
+ return path.join(dir, `${id}.json`);
176
+ }
177
+
178
+ async function acpServer(argv) {
179
+ // A key in its environment, read as Gemini reads it, then kept from the commands its tools run when
180
+ // redaction is on. A key handed over in authenticate replaces it.
181
+ const envKey = process.env.GEMINI_API_KEY || undefined;
182
+ // Which other credentials it was started with, before its redaction drops them from its tools:
183
+ // other vendors' keys, and relay's proxy URL with the turn's token in it (the control for what
184
+ // its tools then see). The proxy URL is kept for its own requests, as Gemini's undici agent keeps it.
185
+ const startProxy = process.env.HTTPS_PROXY;
186
+ const startedWith = { google: Boolean(process.env.GOOGLE_API_KEY), anthropic: Boolean(process.env.ANTHROPIC_API_KEY), openai: Boolean(process.env.OPENAI_API_KEY), proxy: /^https?:\/\/[^:@\s]+:[^@\s]+@/.test(startProxy ?? "") };
187
+ let apiKey = envKey;
188
+ let keyFrom = envKey ? "env" : null;
189
+ const userSettings = settings();
190
+ // Its start-up session cleanup, on unless the user settings turn it off (0.64.0's default is on).
191
+ if (userSettings.general?.sessionRetention?.enabled !== false) {
192
+ const dir = path.dirname(sessionFile("cleanup"));
193
+ for (const name of fs.readdirSync(dir)) {
194
+ const file = path.join(dir, name);
195
+ let replies = 0;
196
+ try { replies = JSON.parse(fs.readFileSync(file, "utf8")).replies ?? 0; } catch { /* unreadable: deleted too */ }
197
+ if (!replies) { fs.rmSync(file, { force: true }); record({ event: "session-cleanup", deleted: name }); }
198
+ }
199
+ }
200
+ const redaction = userSettings.security?.environmentVariableRedaction?.enabled === true;
201
+ if (redaction) for (const [k, v] of Object.entries(process.env)) if (!k.startsWith("GEMINI_CLI_") && (SECRET_NAME.test(k) || SECRET_VALUE.test(v ?? ""))) delete process.env[k];
202
+
203
+ // Its command-based tool discovery, from the user settings (the only settings an untrusted folder loads).
204
+ const toolCommands = { discoveryCommand: userSettings.tools?.discoveryCommand ?? null, callCommand: userSettings.tools?.callCommand ?? null };
205
+ /** Runs discovery as a session's config is initialized; the tools by the name the model calls them, or throws as session setup would fail. */
206
+ const discover = async (loading = false) => {
207
+ const tools = new Map();
208
+ // A Gemini that does not run discovery at session setup (a release that changed it), for relay's launch check.
209
+ const skip = process.env.STUB_GEMINI_SKIP_DISCOVERY;
210
+ if (!toolCommands.discoveryCommand || skip === "1" || (skip === "load" && loading)) return tools;
211
+ const [command, ...args] = parseCommand(toolCommands.discoveryCommand);
212
+ const r = await runCommand(command, args);
213
+ if (r.error) throw new Error(r.error);
214
+ if (r.code !== 0) throw new Error(`Tool discovery command failed with exit code ${r.code}`);
215
+ const items = JSON.parse(r.stdout.trim());
216
+ if (!Array.isArray(items)) throw new Error("Tool discovery command did not return a JSON array of tools.");
217
+ const functions = items.flatMap((t) => (Array.isArray(t?.function_declarations) ? t.function_declarations : Array.isArray(t?.functionDeclarations) ? t.functionDeclarations : t?.name ? [t] : []));
218
+ for (const f of functions) if (f.name) tools.set(DISCOVERED_PREFIX + f.name, { original: f.name, description: f.description ?? "", parameters: f.parametersJsonSchema ?? {} });
219
+ return tools;
220
+ };
221
+ /** Whether the mark relay's --list leaves is there, by the path relay's bridge.json names (for tests). */
222
+ const discoveryMark = () => {
223
+ if (!toolCommands.callCommand) return null;
224
+ try {
225
+ const listed = JSON.parse(fs.readFileSync(path.join(path.dirname(toolCommands.callCommand), "bridge.json"), "utf8")).listed;
226
+ return { path: listed, there: fs.existsSync(listed) };
227
+ } catch (err) {
228
+ return { error: err.code ?? String(err) };
229
+ }
230
+ };
231
+ /** A discovered tool called as the model calls it: the result as relay's tools give it (JSON), or a failure as 0.64.0 reports one. */
232
+ const callDiscovered = async (tools, name, params) => {
233
+ const tool = tools.get(name);
234
+ if (!tool) return { error: `Tool "${name}" not found in registry.` };
235
+ const r = await runCommand(toolCommands.callCommand, [tool.original], JSON.stringify(params));
236
+ record({ event: "discovered-call", name, code: r.code, stderr: Boolean(r.stderr) });
237
+ if (r.error || r.code !== 0 || r.signal || r.stderr) {
238
+ return { error: [`Stdout: ${r.stdout || "(empty)"}`, `Stderr: ${r.stderr || "(empty)"}`, `Error: ${r.error ?? "(none)"}`, `Exit Code: ${r.code ?? "(none)"}`, `Signal: ${r.signal ?? "(none)"}`].join("\n") };
239
+ }
240
+ try { return JSON.parse(r.stdout); } catch { return { raw: r.stdout }; }
241
+ };
242
+
243
+ const out = (m) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...m }) + "\n");
244
+ const answers = new Map();
245
+ let nextId = 1000;
246
+ const toClient = (method, params, timeoutMs = 120000) => new Promise((resolve) => {
247
+ const id = nextId++;
248
+ const timer = setTimeout(() => { answers.delete(id); resolve({ timeout: true }); }, timeoutMs);
249
+ answers.set(id, (m) => { clearTimeout(timer); resolve(m); });
250
+ out({ id, method, params });
251
+ });
252
+ const update = (sessionId, u) => out({ method: "session/update", params: { sessionId, update: u } });
253
+
254
+ const trusted = process.env.GEMINI_CLI_TRUST_WORKSPACE !== "false";
255
+ let session = null;
256
+ let mode = "default";
257
+ const model = flag(argv, "--model") ?? "auto";
258
+ let cancelled = false;
259
+ let finishPrompt = null;
260
+ let calls = 0;
261
+ const sessionResult = () => ({
262
+ modes: { currentModeId: mode, availableModes: MODES },
263
+ models: { currentModelId: process.env.STUB_GEMINI_REPORT_MODEL || model, availableModels: MODELS.map((modelId) => ({ modelId, name: modelId })) },
264
+ });
265
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
266
+ /** The conversation so far, streamed after session/load has answered, as 0.64.0 streams it. */
267
+ const replay = async (id, turns) => {
268
+ await pause(20);
269
+ for (let n = 1; n <= turns; n++) {
270
+ if (n > 1 && process.env.STUB_GEMINI_EXIT_IN_REPLAY) {
271
+ process.stderr.write("stub: died in the middle of its replay\n", () => process.exit(4));
272
+ return;
273
+ }
274
+ if (n > 1 && process.env.STUB_GEMINI_REPLAY_STALL_MS) await pause(Number(process.env.STUB_GEMINI_REPLAY_STALL_MS));
275
+ for (const u of [
276
+ { sessionUpdate: "user_message_chunk", content: { type: "text", text: `the prompt of turn ${n}` } },
277
+ { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Let me look. " } },
278
+ { sessionUpdate: "tool_call", toolCallId: `read_file-${n}`, status: "completed", title: "README.md", content: [], kind: "read" },
279
+ { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `REPLAYED turn ${n}` } },
280
+ ]) {
281
+ update(id, u);
282
+ await pause(5);
283
+ }
284
+ }
285
+ };
286
+ /** Gemini's ACP commands (acpCommandHandler.ts), matched on the prompt's first word. */
287
+ const COMMANDS = new Set(["memory", "extensions", "init", "restore", "about", "help"]);
288
+
289
+ /** Gemini's permission request: its own option ids with ACP kinds; no rawInput, the command as the title. */
290
+ const ask = async (request) => {
291
+ const sessionId = session.id;
292
+ const toolCallId = `run_shell_command-${++calls}`;
293
+ const options = [
294
+ { optionId: "proceed_once", name: "Allow", kind: "allow_once" },
295
+ { optionId: "proceed_always", name: "Allow for this session", kind: "allow_always" },
296
+ { optionId: "cancel", name: "Reject", kind: "reject_once" },
297
+ ];
298
+ const command = typeof request === "string" ? request : request.command;
299
+ const where = `${request.dir_path ? `[in ${request.dir_path}]` : `[current working directory ${process.cwd()}]`} (stub needs it)`;
300
+ const call = { toolCallId, status: "pending", title: command, content: [{ type: "content", content: { type: "text", text: where } }], locations: [], kind: "execute" };
301
+ update(sessionId, { sessionUpdate: "tool_call", ...call });
302
+ const reply = await toClient("session/request_permission", { sessionId, options, toolCall: call });
303
+ const o = reply.result?.outcome;
304
+ const kind = o?.outcome === "selected" ? options.find((x) => x.optionId === o.optionId)?.kind ?? `unoffered:${o.optionId}` : o?.outcome ?? "no answer";
305
+ update(sessionId, { sessionUpdate: "tool_call_update", toolCallId, status: kind === "allow_once" ? "completed" : "failed", kind: "execute" });
306
+ return { decision: kind === "allow_once" ? "allow" : "deny", optionKind: kind };
307
+ };
308
+
309
+ const handle = async (line) => {
310
+ let m;
311
+ try { m = JSON.parse(line); } catch { return; }
312
+ if (m.id !== undefined && m.method === undefined) { answers.get(m.id)?.(m); answers.delete(m.id); return; }
313
+ const p = m.params ?? {};
314
+ switch (m.method) {
315
+ case "initialize": {
316
+ // Its start-up config is initialized while it answers, which runs discovery too
317
+ // (acpRpcDispatcher.ts:81, config.initialize); a discovery that throws fails initialize.
318
+ let atInitialize;
319
+ try {
320
+ atInitialize = await discover(false);
321
+ } catch (err) {
322
+ record({ event: "discovery-failed", at: "initialize", error: String(err?.message ?? err) });
323
+ out({ id: m.id, error: { code: -32603, message: "Internal error", data: { details: String(err?.message ?? err) } } });
324
+ return;
325
+ }
326
+ record({ event: "initialize", protocolVersion: p.protocolVersion, clientCapabilities: p.clientCapabilities, discoveredAtInitialize: atInitialize.size, discoveryMark: discoveryMark() });
327
+ out({ id: m.id, result: {
328
+ protocolVersion: 1, authMethods: AUTH_METHODS,
329
+ agentInfo: { name: "gemini-cli", title: "Gemini CLI", version: (process.env.STUB_VERSION ?? "0.64.0").split(" ")[0] },
330
+ agentCapabilities: { loadSession: true, promptCapabilities: { image: true, audio: true, embeddedContext: true }, mcpCapabilities: { http: true, sse: true } },
331
+ } });
332
+ break;
333
+ }
334
+ case "authenticate": {
335
+ const key = typeof p._meta?.["api-key"] === "string" ? p._meta["api-key"] : undefined;
336
+ record({ event: "authenticate", methodId: p.methodId, meta: Object.keys(p._meta ?? {}), keySha256: key ? sha(key) : null, session: Boolean(session) });
337
+ if (!AUTH_METHODS.some((a) => a.id === p.methodId)) { out({ id: m.id, error: { code: -32602, message: `Invalid enum value: ${p.methodId}` } }); return; }
338
+ if (process.env.STUB_GEMINI_REFUSE_SIGNIN) { out({ id: m.id, error: { code: -32000, message: `API key not valid. Please pass a valid API key. (request: {"api-key":"${key}"})` } }); return; }
339
+ if (key) { apiKey = key; keyFrom = "authenticate"; }
340
+ out({ id: m.id, result: {} });
341
+ break;
342
+ }
343
+ case "session/new":
344
+ case "session/load": {
345
+ const selected = userSettings.security?.auth?.selectedType;
346
+ if (selected !== "gemini-api-key" || !apiKey) { out({ id: m.id, error: { code: -32000, message: "Gemini API key is missing or not configured." } }); return; }
347
+ const loading = m.method === "session/load";
348
+ const id = loading ? p.sessionId : crypto.randomUUID();
349
+ const file = sessionFile(id);
350
+ if (loading && process.env.STUB_GEMINI_LOAD_ERROR) { out({ id: m.id, error: { code: -32603, message: "Internal error", data: { details: `the session store is locked\n (signed in with ${apiKey})` } } }); return; }
351
+ if (loading && !fs.existsSync(file)) {
352
+ const details = `Invalid session identifier "${id}".\n Searched for sessions in ${path.dirname(file)}.\n Use --list-sessions to see available sessions, then use --resume {number}, --resume {uuid}, or --resume latest.`;
353
+ out({ id: m.id, error: { code: -32603, message: "Internal error", data: { details } } });
354
+ return;
355
+ }
356
+ const sess = loading ? JSON.parse(fs.readFileSync(file, "utf8")) : { turns: 0 };
357
+ // Discovery as the session's config is initialized; a failure fails the session.
358
+ let tools;
359
+ try {
360
+ tools = await discover(loading);
361
+ } catch (err) {
362
+ record({ event: "discovery-failed", error: String(err?.message ?? err) });
363
+ out({ id: m.id, error: { code: -32603, message: "Internal error", data: { details: String(err?.message ?? err) } } });
364
+ return;
365
+ }
366
+ // An untrusted folder connects no MCP server: what relay passed is recorded, and not used.
367
+ session = { id, sess, file, loading, mcpServers: trusted ? (p.mcpServers ?? []) : [], passed: p.mcpServers ?? [], cwd: p.cwd, tools };
368
+ record({ event: "session", method: m.method, sessionId: id, cwd: p.cwd, passedMcpServers: (p.mcpServers ?? []).map((s) => s.name), trusted, keySha256: sha(apiKey), keyFrom,
369
+ toolCommands, discovered: [...tools.entries()].map(([name, t]) => ({ name, description: t.description, parameters: t.parameters })), discoveryMark: discoveryMark() });
370
+ out({ id: m.id, result: loading ? sessionResult() : { sessionId: id, ...sessionResult() } });
371
+ if (loading) void replay(id, sess.turns);
372
+ break;
373
+ }
374
+ case "session/set_mode":
375
+ if (!trusted && !["default", "plan"].includes(p.modeId)) { out({ id: m.id, error: { code: -32602, message: "untrusted folder: only default and plan" } }); return; }
376
+ mode = p.modeId;
377
+ out({ id: m.id, result: {} });
378
+ break;
379
+ case "session/cancel":
380
+ record({ event: "cancel" });
381
+ cancelled = true;
382
+ finishPrompt?.({ stopReason: "cancelled" });
383
+ break;
384
+ case "session/prompt": {
385
+ session.sess.turns += 1;
386
+ fs.writeFileSync(session.file, JSON.stringify(session.sess));
387
+ const prompt = (p.prompt ?? []).map((b) => b.text ?? "").join("");
388
+ const relay = session.mcpServers.find((s) => s.name === "relay");
389
+ const parsed = { relay: relay ? { command: relay.command, args: relay.args ?? [], env: Object.fromEntries((relay.env ?? []).map((e) => [e.name, e.value])) } : undefined };
390
+ const env = process.env;
391
+ record({
392
+ event: "start", target: "gemini", via: "acp", argv, prompt, sessionId: session.id, resumed: session.loading, turn: session.sess.turns,
393
+ cwd: process.cwd(), hasRelay: Boolean(parsed.relay), discovered: [...session.tools.keys()].sort(), mode, model, redaction,
394
+ env: {
395
+ // What the commands its tools run see, and whether a key was in its own environment at all.
396
+ toolsSeeKey: Boolean(env.GEMINI_API_KEY), startedWithKey: Boolean(envKey), startedWith, googleKey: Boolean(env.GOOGLE_API_KEY), adc: Boolean(env.GOOGLE_APPLICATION_CREDENTIALS), project: Boolean(env.GOOGLE_CLOUD_PROJECT),
397
+ proxyInTools: Boolean(env.HTTPS_PROXY), geminiModel: env.GEMINI_MODEL ?? null, home: env.HOME ?? null, geminiHome: env.GEMINI_CLI_HOME ?? null, sandbox: env.SANDBOX ?? null,
398
+ geminiSandbox: env.GEMINI_SANDBOX ?? null, noRelaunch: env.GEMINI_CLI_NO_RELAUNCH ?? null, trust: env.GEMINI_CLI_TRUST_WORKSPACE ?? null, fileStorage: env.GEMINI_FORCE_FILE_STORAGE ?? null,
399
+ systemSettings: env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? null, systemDefaults: env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? null,
400
+ otel: Object.keys(env).filter((k) => k.startsWith("OTEL_")), anthropicKey: Boolean(env.ANTHROPIC_API_KEY), openaiKey: Boolean(env.OPENAI_API_KEY), tmpdir: env.TMPDIR ?? null,
401
+ },
402
+ });
403
+ // Its ACP commands are run, never sent to the model: the trimmed text, its first word.
404
+ const text = prompt.trim();
405
+ if ((text.startsWith("/") || text.startsWith("$")) && COMMANDS.has(text.slice(1).trim().split(/\s+/)[0])) {
406
+ record({ event: "command", command: text.slice(1).trim().split(/\s+/)[0] });
407
+ update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Gemini CLI commands: /memory, /extensions, /init, /restore, /about, /help" } });
408
+ out({ id: m.id, result: { stopReason: "end_turn", usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, _meta: { quota: { token_count: { input_tokens: 0, output_tokens: 0 }, model_usage: [] } } } });
409
+ break;
410
+ }
411
+ await pause(Number(process.env.STUB_GEMINI_LATENCY_MS ?? 100));
412
+ // A first turn looks before it answers (two rounds); a loaded session's is answered with text alone.
413
+ const rounds = session.loading ? 1 : 2;
414
+ if (rounds === 2) {
415
+ update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Let me look. " } });
416
+ update(session.id, { sessionUpdate: "tool_call", toolCallId: "read_file-1", title: "README.md", kind: "read", status: "completed", locations: [{ path: path.join(session.cwd, "README.md") }] });
417
+ }
418
+ const done = new Promise((resolve) => (finishPrompt = resolve));
419
+ let routed = null;
420
+ void (async () => {
421
+ const hook = async (h) => {
422
+ // The model the prompt's first round was routed to, where it is not the one asked for.
423
+ if (h.routed) routed = h.routed;
424
+ // The agent prints the key it was given: in a tool call's title, on stderr (once split across two writes).
425
+ if (h.leakKey) {
426
+ update(session.id, { sessionUpdate: "tool_call", toolCallId: "leak-1", title: `echo ${apiKey}`, kind: "execute", status: "completed" });
427
+ process.stderr.write(`stub diagnostics: key=${apiKey}\n`);
428
+ process.stderr.write(`partial ${apiKey.slice(0, 10)}`);
429
+ await new Promise((r) => setTimeout(r, 50));
430
+ process.stderr.write(`${apiKey.slice(10)} end\n`);
431
+ }
432
+ // What a command its tools run could learn of the environment the agent was started with
433
+ // (kern.procargs2, which ps reads), asked from a child, as a tool's command would ask.
434
+ if (h.procArgsSelf) {
435
+ const got = procArgs(process.pid);
436
+ // envShown: a variable relay sets in its start-up environment is there, so that what is
437
+ // not there means something.
438
+ record({ event: "procargs-self", readable: typeof got.text === "string", errno: got.errno ?? null, error: got.error ?? null, envShown: Boolean(got.text?.includes("GEMINI_CLI_HOME=")), keyShown: Boolean(apiKey && got.text?.includes(apiKey)), varShown: Boolean(got.text?.includes("GEMINI_API_KEY=")) });
439
+ }
440
+ // For tests only, not what Gemini does: the tools relay's bridge offers this turn, read from
441
+ // the bridge relay passed in session/new (which the untrusted folder leaves unconnected), to
442
+ // set against what discovery gave.
443
+ if (h.bridgeTools) {
444
+ const relayEntry = session.passed.find((s) => s.name === "relay");
445
+ let tools = null;
446
+ if (relayEntry) {
447
+ const env = { ...process.env, ...Object.fromEntries((relayEntry.env ?? []).map((e) => [e.name, e.value])) };
448
+ const client = new Client({ name: "stub-gemini-check", version: "0" });
449
+ await client.connect(new StdioClientTransport({ command: relayEntry.command, args: relayEntry.args ?? [], env }));
450
+ tools = (await client.listTools()).tools.map((t) => ({ name: t.name, description: t.description ?? "", parameters: t.inputSchema }));
451
+ await client.close().catch(() => {});
452
+ }
453
+ record({ event: "bridge-tools", tools });
454
+ }
455
+ // What relay's tool files for the turn hold, and what can be done with them from inside the
456
+ // turn: the secret's file is read (as any command could), recorded by its SHA-256 only.
457
+ if (h.toolFiles) {
458
+ const dir = toolCommands.callCommand ? path.dirname(toolCommands.callCommand) : null;
459
+ let where = {};
460
+ try { where = JSON.parse(fs.readFileSync(path.join(dir, "bridge.json"), "utf8")); } catch { /* recorded as missing */ }
461
+ let secret = null;
462
+ let readError = null;
463
+ try { secret = fs.readFileSync(where.secret, "utf8"); } catch (err) { readError = err.code ?? String(err); }
464
+ let writable;
465
+ try {
466
+ fs.closeSync(fs.openSync(where.secret, fs.constants.O_WRONLY | fs.constants.O_NONBLOCK));
467
+ writable = "opened";
468
+ } catch (err) {
469
+ writable = err.code ?? String(err);
470
+ }
471
+ let listed;
472
+ try {
473
+ fs.readdirSync(path.dirname(where.secret));
474
+ listed = "listed";
475
+ } catch (err) {
476
+ listed = err.code ?? String(err);
477
+ }
478
+ const holds = (s) => Boolean(secret && s && s.includes(secret));
479
+ let shim = null;
480
+ try { shim = fs.readFileSync(toolCommands.callCommand, "utf8"); } catch { /* recorded as null */ }
481
+ const homeFiles = fs.readdirSync(dir).map((n) => fs.readFileSync(path.join(dir, n), "utf8"));
482
+ record({
483
+ event: "tool-files", dir, where, readError, secretSha256: secret ? sha(secret) : null, secretMode: secret ? (fs.statSync(where.secret).mode & 0o777) : null, writable, listed,
484
+ inCommands: holds(toolCommands.discoveryCommand) || holds(toolCommands.callCommand), inShim: holds(shim), inEnv: Object.values(process.env).some(holds),
485
+ inHome: homeFiles.some(holds), shim,
486
+ });
487
+ }
488
+ // Another turn's secret file, whose path the test leaves in the stub's directory (readable here).
489
+ if (h.readOtherSecret) {
490
+ const other = fs.readFileSync(path.join(process.env.STUB_DIR, "other-secret-path"), "utf8");
491
+ const attempt = (fn) => {
492
+ try { fn(); return "ok"; } catch (err) { return err.code ?? String(err); }
493
+ };
494
+ record({
495
+ event: "other-secret", path: other,
496
+ read: attempt(() => fs.readFileSync(other)), exists: attempt(() => fs.accessSync(other, fs.constants.F_OK)),
497
+ listed: attempt(() => fs.readdirSync(path.dirname(other))),
498
+ });
499
+ }
500
+ // A connection to the turn's broker from inside the turn with a secret that is not the turn's.
501
+ if (h.wrongSecret) {
502
+ const dir = path.dirname(toolCommands.callCommand);
503
+ const socketPath = JSON.parse(fs.readFileSync(path.join(dir, "bridge.json"), "utf8")).socket;
504
+ const outcome = await new Promise((resolve) => {
505
+ const sock = net.connect(socketPath);
506
+ let data = "";
507
+ const timer = setTimeout(() => { sock.destroy(); resolve({ answered: Boolean(data), closed: false }); }, 5000);
508
+ sock.on("connect", () => {
509
+ sock.write(JSON.stringify({ relay_bridge_secret: "not-the-turns-secret-0123456789abcdef" }) + "\n");
510
+ sock.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "x", version: "0" } } }) + "\n");
511
+ });
512
+ sock.on("data", (d) => (data += d));
513
+ sock.on("error", () => {});
514
+ sock.on("close", () => { clearTimeout(timer); resolve({ answered: Boolean(data), closed: true }); });
515
+ });
516
+ record({ event: "wrong-secret", ...outcome });
517
+ }
518
+ // Gemini's own process reaching a host through the proxy it was started with, as its
519
+ // requests to Google go: the proxy decides (curl takes the proxy from HTTPS_PROXY).
520
+ if (h.proxyProbe) {
521
+ const { spawnSync } = await import("node:child_process");
522
+ const r = spawnSync("/usr/bin/curl", ["-s", "-m", "5", "-o", "/dev/null", `https://${h.proxyProbe}/`], { env: { ...process.env, HTTPS_PROXY: startProxy ?? "" } });
523
+ record({ event: "proxy-probe", host: h.proxyProbe, proxied: Boolean(startProxy), status: r.status });
524
+ }
525
+ // Its tools reading the key file where the person keeps it, as any command could.
526
+ if (h.readKeyFile) {
527
+ const file = h.readKeyFile;
528
+ let got;
529
+ try {
530
+ got = fs.readFileSync(file, "utf8").includes(apiKey) ? "read the key" : "read something else";
531
+ } catch (err) {
532
+ got = err.code ?? String(err);
533
+ }
534
+ let listed;
535
+ try {
536
+ listed = fs.readdirSync(path.dirname(file)).length >= 0 ? "listed" : "";
537
+ } catch (err) {
538
+ listed = err.code ?? String(err);
539
+ }
540
+ // Whether its name can be tested for, and whether it opens for writing (never truncated, nothing written).
541
+ let tested;
542
+ try {
543
+ fs.accessSync(file, fs.constants.F_OK);
544
+ tested = "exists";
545
+ } catch (err) {
546
+ tested = err.code ?? String(err);
547
+ }
548
+ let writable;
549
+ try {
550
+ fs.closeSync(fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_NONBLOCK));
551
+ writable = "opened";
552
+ } catch (err) {
553
+ writable = err.code ?? String(err);
554
+ }
555
+ record({ event: "read-key-file", got, listed, tested, writable });
556
+ }
557
+ };
558
+ // Relay's tools, as discovered: the model calls them by their discovered names.
559
+ const relayTools = session.tools.size ? { list: () => [...session.tools.keys()].sort(), call: (name, args) => callDiscovered(session.tools, name, args) } : undefined;
560
+ const r = await runSteps({ id: "gemini", hook, relayTools }, parsed, prompt, session.sess, ask);
561
+ if (cancelled) return;
562
+ record({ event: "end", target: "gemini", sessionId: session.id, calls: r.calls, failure: r.failure });
563
+ if (r.failure) return finishPrompt({ error: r.failure });
564
+ // A reply makes the session resumable (hasResumableContent), so its start-up cleanup keeps it.
565
+ session.sess.replies = (session.sess.replies ?? 0) + 1;
566
+ fs.writeFileSync(session.file, JSON.stringify(session.sess));
567
+ const reply = r.reply.replaceAll("@@KEY@@", apiKey);
568
+ // Streamed in pieces, as models do.
569
+ const half = Math.ceil(reply.length / 2);
570
+ update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: reply.slice(0, half) } });
571
+ update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: reply.slice(half) } });
572
+ // The first round under the model it was routed to; a round after a tool call under the configured id.
573
+ const answered = [...new Set([routed ?? (ALIASES.has(model) ? "gemini-3.8-flash" : model), ...(rounds === 2 ? [model] : [])])];
574
+ finishPrompt({
575
+ stopReason: "end_turn",
576
+ usage: { inputTokens: 200, outputTokens: 40, totalTokens: 240, cachedReadTokens: 20, thoughtTokens: 5 },
577
+ _meta: { quota: { token_count: { input_tokens: 200, output_tokens: 40 }, model_usage: answered.map((mu) => ({ model: mu, token_count: { input_tokens: 100, output_tokens: 20 } })) } },
578
+ });
579
+ })().catch((err) => {
580
+ record({ event: "steps-error", error: String(err?.message ?? err) });
581
+ finishPrompt({ error: String(err?.stack ?? err) });
582
+ });
583
+ const res = await done;
584
+ if (res.error) out({ id: m.id, error: { code: -32000, message: res.error } });
585
+ else out({ id: m.id, result: { stopReason: res.stopReason, ...(res.usage ? { usage: res.usage } : {}), ...(res._meta ? { _meta: res._meta } : {}) } });
586
+ if (cancelled) process.exit(0);
587
+ break;
588
+ }
589
+ default:
590
+ if (m.id !== undefined) out({ id: m.id, error: { code: -32601, message: `Method not found: ${m.method}` } });
591
+ }
592
+ };
593
+ const rl = readline.createInterface({ input: process.stdin });
594
+ rl.on("line", (line) => void handle(line).catch((err) => record({ event: "stub-error", error: String(err?.stack ?? err) })));
595
+ await new Promise((resolve) => rl.on("close", resolve));
596
+ }
597
+
598
+ const gemini = {
599
+ id: "gemini",
600
+ version: "0.64.0",
601
+ serve: (argv) => (argv.includes("--acp") ? acpServer(argv) : null),
602
+ parse: () => { throw new Error("the stub Gemini agent runs only as `--acp`"); },
603
+ };
604
+ export default gemini;
@@ -0,0 +1,11 @@
1
+ // Safe before synthetic root capture: only the temporary root changes, never HOME or
2
+ // host identity. Tests and their children use os.tmpdir(), so normalize TMPDIR once.
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ const inherited = fs.realpathSync(os.tmpdir());
8
+ // The deepest fixture socket: macOS allows 103 bytes, excluding the terminating NUL.
9
+ const socketExample = path.join(inherited, "relay-probe-test-XXXXXX", "home/.relay-t/s/relay-probe-XXXXXXXXXXXX/relay.sock");
10
+ export const TEST_TEMP_ROOT = Buffer.byteLength(socketExample) <= 103 ? inherited : fs.realpathSync("/tmp");
11
+ process.env.TMPDIR = TEST_TEMP_ROOT;