@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,607 @@
1
+ // Google's Gemini CLI over ACP (`gemini --acp`): its profile for the generic driver (acp.ts). What
2
+ // this says about Gemini comes from the 0.64.0 package (docs/research/acp-google-grok.md §1.2,
3
+ // re-read in the package's bundle for docs/gemini.md) and from `gemini --acp` run without a key,
4
+ // with the network denied (initialize and its login methods, session/new refused without a key,
5
+ // authenticate rewriting its settings, where it keeps its state). Nothing here has been seen with
6
+ // a real key; the qualification run must confirm what docs/gemini.md marks unverified.
7
+ import fs from "node:fs";
8
+ import crypto from "node:crypto";
9
+ import path from "node:path";
10
+ import { apiKeyFile, readApiKey } from "../core/api-keys.js";
11
+ import { harnessHome, networkOn } from "../core/config.js";
12
+ import { shellQuote } from "../core/shell.js";
13
+ import { targetDef } from "../targets/index.js";
14
+ import { acpBackend, genericApproval, promptModels } from "./acp.js";
15
+ import { discoveryVerified, fullVersionOf } from "./tool-discovery.js";
16
+ /**
17
+ * Where Gemini CLI reads administrator policies on macOS. They outrank every other policy tier,
18
+ * relay's included, and no variable moves them, so relay does not run Gemini where there are any.
19
+ */
20
+ let adminPoliciesDir = "/Library/Application Support/GeminiCli/policies";
21
+ /** Tests only: another place to look for administrator policies, or null for the real one. */
22
+ export function setAdminPoliciesDirForTests(dir) {
23
+ adminPoliciesDir = dir ?? "/Library/Application Support/GeminiCli/policies";
24
+ }
25
+ /**
26
+ * Relay's settings for Gemini (its user settings, `<home>/.gemini/settings.json`), the only
27
+ * settings it loads: system settings are pointed at files that do not exist, and the working
28
+ * directory is untrusted, so the repository's are not read. Each key is in 0.64.0's schema.
29
+ */
30
+ export const GEMINI_SETTINGS = Object.freeze({
31
+ security: {
32
+ // Sign in with an API key: the one relay hands over in ACP authenticate. Set here as well, since
33
+ // a session is created and loaded with the method these settings name, and authenticate's own
34
+ // write of it is refused in relay's read-only home (Gemini ignores that failure).
35
+ auth: { selectedType: "gemini-api-key" },
36
+ // Its own per-tool sandbox would nest inside relay's.
37
+ toolSandboxing: false,
38
+ // No approval is saved, and no "always" offered: relay answers each request once.
39
+ enablePermanentToolApproval: false,
40
+ disableAlwaysAllow: true,
41
+ // Its tools' environment (shell commands, hooks) without variables that look like secrets, the
42
+ // proxy URL with relay's per-turn token among them. Its own environment holds no key.
43
+ environmentVariableRedaction: { enabled: true },
44
+ },
45
+ tools: { sandbox: false },
46
+ // Clearcut usage statistics (play.googleapis.com) are on unless this says otherwise; OTEL telemetry too.
47
+ privacy: { usageStatisticsEnabled: false },
48
+ telemetry: { enabled: false },
49
+ general: {
50
+ enableAutoUpdate: false, enableAutoUpdateNotification: false, checkpointing: { enabled: false },
51
+ // No session cleanup of Gemini's own: relay continues a session by loading it, and removes the
52
+ // session's home with its run (core/retention.ts). The cleanup is on by default (0.64.0
53
+ // packages/cli/src/config/settingsSchema.ts:389-437, maxAge "30d") and runs at every start, ACP
54
+ // included (packages/cli/src/gemini.tsx:786). It deletes every session file with nothing
55
+ // resumable in it (packages/cli/src/utils/sessionUtils.ts:295, sessionCleanup.ts:302-311), such
56
+ // as one whose only prompt failed before the model answered (seen 2026-10-21), and every one
57
+ // idle past maxAge. session/load then fails ("Internal error", "Invalid session identifier"), for
58
+ // a session it would otherwise load by its id, reply or none (packages/cli/src/acp/
59
+ // acpSessionManager.ts:216-219, allowEmpty; sessionUtils.ts:513-547). Disabled, it returns
60
+ // before it looks (sessionCleanup.ts:116); relay's user settings outrank the schema's default
61
+ // (packages/cli/src/config/settings.ts:255-280).
62
+ sessionRetention: { enabled: false },
63
+ },
64
+ // No .env file from the working directory or above it (in an untrusted folder Gemini would still
65
+ // take GEMINI_API_KEY, GOOGLE_API_KEY and the Cloud project from one), and no memory flags.
66
+ advanced: { ignoreLocalEnv: true, autoConfigureMemory: false },
67
+ hooksConfig: { enabled: false },
68
+ ide: { enabled: false },
69
+ // Its subagents (codebase_investigator, cli_help, generalist: on by default) run models of their own
70
+ // choosing in a loop of their own, which the prompt's response does not report (model_usage counts
71
+ // the main loop only), and the target says it has none (capabilities.subagents "never").
72
+ experimental: { enableAgents: false },
73
+ });
74
+ /**
75
+ * Relay's policy for Gemini's tools, `<home>/relay-policy.toml`, handed to each of relay's turns with
76
+ * `--policy` (which takes the place of the user policies directory and keeps the user tier, 0.64.0
77
+ * packages/core/src/policy/config.ts getPolicyDirectories and createPolicyEngineConfig). Never in
78
+ * `<home>/.gemini/policies`, where Gemini looks by itself: the session the resume command opens in
79
+ * the person's terminal, outside relay's sandbox, would then run every tool unasked.
80
+ * In the untrusted folder relay runs it in, Gemini's approval mode is forced to "default", which
81
+ * asks before every edit and command; relay's sandbox is the boundary instead, and nothing
82
+ * approved lifts it, so every tool is allowed, as Copilot runs with --allow-all-tools. Gemini
83
+ * still asks, over ACP, about the shell commands its own checks single out (git in an untrusted
84
+ * folder, a directory outside the workspace), and relay answers those as it does every approval
85
+ * request. Denied: save_memory (not a tool in 0.64.0, which keeps memory in a file relay clears
86
+ * between turns, clearGeminiMemory; denied should a release bring it back), invoke_agent (its
87
+ * subagents, switched off in GEMINI_SETTINGS as well), and without network access the two web tools, which reach the web
88
+ * through Google's API host (search and URL fetch run at Google). That denial is defence in depth,
89
+ * not what keeps the turn off the web: any command in the turn can reach that host through the proxy
90
+ * with a key of its own (docs/security-model.md, "What it does not do").
91
+ */
92
+ export function geminiPolicy(spec) {
93
+ const rule = (fields) => "[[rule]]\n" + Object.entries(fields).map(([k, v]) => `${k} = ${typeof v === "string" ? JSON.stringify(v) : String(v)}`).join("\n") + "\n";
94
+ const rules = [
95
+ "# Written by relay before every turn; read-only to the agent. Relay's sandbox is the boundary.\n",
96
+ rule({ toolName: "run_shell_command", decision: "allow", priority: 100, allowRedirection: true }),
97
+ rule({ toolName: "*", decision: "allow", priority: 90 }),
98
+ // Relay's own tools, which Gemini discovers as discovered_tool_<name> (geminiTools), are allowed
99
+ // by the rule above; none can be discovered under a name denied below (writeGeminiToolFiles).
100
+ rule({ toolName: "save_memory", decision: "deny", priority: 900, denyMessage: "relay keeps no memory from one turn to the next; say what should be remembered in your reply" }),
101
+ rule({ toolName: "invoke_agent", decision: "deny", priority: 900, denyMessage: "subagents are not available in this harness under relay; do the work yourself" }),
102
+ ];
103
+ if (!networkOn(spec.config, spec.grant)) {
104
+ for (const tool of ["google_web_search", "web_fetch"]) {
105
+ rules.push(rule({ toolName: tool, decision: "deny", priority: 900, denyMessage: "this turn has no network access; ask whoever started you for a network grant if the work needs the web" }));
106
+ }
107
+ }
108
+ return rules.join("\n");
109
+ }
110
+ /**
111
+ * The Node that runs Gemini CLI. npm installs it as a script whose `#!/usr/bin/env node` line finds
112
+ * `node` on PATH, and relay's sandbox runs executables only from its fixed list (the system's,
113
+ * Homebrew's, /usr/local, relay's own Node) and those a profile names: a Node from a version
114
+ * manager (fnm, nvm) needs naming. The first `node` on the PATH Gemini is given, which is relay's,
115
+ * resolved through links; null when there is none (Gemini then cannot start, and says so).
116
+ */
117
+ export function nodeOnPath(pathVar = process.env.PATH) {
118
+ for (const dir of (pathVar ?? "").split(path.delimiter)) {
119
+ if (!path.isAbsolute(dir))
120
+ continue;
121
+ const p = path.join(dir, "node");
122
+ try {
123
+ fs.accessSync(p, fs.constants.X_OK);
124
+ if (fs.statSync(p).isFile())
125
+ return fs.realpathSync(p);
126
+ }
127
+ catch {
128
+ // Not here.
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+ /**
134
+ * Removes Gemini's private project memory from the runtime directory relay keeps between turns
135
+ * (`<home>/.cache/.gemini/tmp/<project>/memory`). Gemini 0.64.0 loads that directory's MEMORY.md
136
+ * into every session whatever the folder's trust (packages/core/src/context/memoryContextManager.ts
137
+ * discoverMemoryPaths, its userProjectMemory; storage.ts getProjectMemoryDir), and its system prompt
138
+ * asks the model to keep notes there with its file tools (prompts/promptProvider.ts and snippets.ts,
139
+ * "Private Project Memory"). The runtime directory is kept only because loading a session needs its
140
+ * chats, so whatever a turn wrote there would otherwise come back as standing instructions in the
141
+ * session's later turns, and in the unconfined session the resume command opens. Called before every
142
+ * turn (geminiState) and after it (its cleanup). The directory is the agent's to write, so nothing
143
+ * here follows a link: one where Gemini keeps a directory is removed, never followed.
144
+ */
145
+ export function clearGeminiMemory(home) {
146
+ // Move the entire mutable ancestor first. `home` is relay-owned and read-only to the
147
+ // sandbox; after the rename the child cannot rename entries under the quarantine path.
148
+ // No check or recursive removal traverses an agent-writable ancestor by its old name.
149
+ const cache = path.join(home, ".cache");
150
+ const held = path.join(home, `.relay-cleanup-${crypto.randomUUID()}`);
151
+ try {
152
+ fs.renameSync(cache, held);
153
+ }
154
+ catch (err) {
155
+ if (err.code === "ENOENT")
156
+ return;
157
+ throw err;
158
+ }
159
+ try {
160
+ const root = fs.lstatSync(held);
161
+ if (!root.isDirectory() || root.isSymbolicLink()) {
162
+ fs.rmSync(held, { force: true });
163
+ return;
164
+ }
165
+ cleanHeldGeminiMemory(held);
166
+ }
167
+ finally {
168
+ if (fs.lstatSync(held, { throwIfNoEntry: false })) {
169
+ if (fs.lstatSync(cache, { throwIfNoEntry: false }))
170
+ throw new Error(`Gemini cache reappeared during cleanup; isolated cache kept at ${held}`);
171
+ fs.renameSync(held, cache);
172
+ }
173
+ }
174
+ }
175
+ function cleanHeldGeminiMemory(cache) {
176
+ const runtime = path.join(cache, ".gemini");
177
+ const tmp = path.join(runtime, "tmp");
178
+ for (const dir of [runtime, tmp]) {
179
+ const st = fs.lstatSync(dir, { throwIfNoEntry: false });
180
+ if (!st)
181
+ return;
182
+ if (st.isSymbolicLink()) {
183
+ fs.rmSync(dir, { force: true });
184
+ return;
185
+ }
186
+ if (!st.isDirectory())
187
+ return;
188
+ }
189
+ for (const name of fs.readdirSync(tmp)) {
190
+ const project = path.join(tmp, name);
191
+ const st = fs.lstatSync(project, { throwIfNoEntry: false });
192
+ if (st?.isSymbolicLink())
193
+ fs.rmSync(project, { force: true });
194
+ // A link or a file named memory is removed as it is; a directory with all it holds, links included, none followed.
195
+ else if (st?.isDirectory())
196
+ fs.rmSync(path.join(project, "memory"), { recursive: true, force: true });
197
+ }
198
+ }
199
+ /** The Gemini home of the relay session a turn belongs to (geminiState). */
200
+ export const geminiHome = (spec) => path.join(harnessHome(), spec.markers.runId, spec.markers.nodeId, "gemini");
201
+ /** Where relay's tool policy for a turn is (geminiPolicy): in the home, outside `.gemini/`, read-only to the agent. */
202
+ export const geminiPolicyFile = (spec) => path.join(geminiHome(spec), "relay-policy.toml");
203
+ /**
204
+ * The Gemini home a session runs with (GEMINI_CLI_HOME): one per relay session, under relay's
205
+ * harness directory, outside its control directory. It is relay's, and read-only to the agent,
206
+ * but for `.cache/`. With SANDBOX=sandbox-exec Gemini keeps its runtime state there
207
+ * (`.cache/.gemini`: its project registry, its sessions under `tmp/<project>/chats`, history) and
208
+ * its configuration in `.gemini/` (seen with 0.64.0: Storage.getGlobalRuntimeDir), so relay can
209
+ * keep the configuration its own and only the runtime state writable, the one thing kept from turn
210
+ * to turn, since loading a session needs it. Relay refuses to run on `.cache` if it is anything but
211
+ * a plain directory (an agent could otherwise swap in a link that the next turn's sandbox would
212
+ * follow), and before every turn rebuilds the rest: its settings (GEMINI_SETTINGS) and its policy
213
+ * (geminiPolicy, in its own file beside `.gemini/`). Nothing of the person's own Gemini configuration
214
+ * (`~/.gemini`) comes along: no MCP servers, extensions, skills, commands, policies or stored login.
215
+ *
216
+ * The key is read here, from the person's key file (core/api-keys.ts), only once every refusal
217
+ * that can come earlier has passed, and never without the per-target opt-in, which is checked here
218
+ * again whatever ran before. Relay hands it to Gemini in the ACP authenticate request
219
+ * (`authenticate`: methodId "gemini-api-key", `_meta["api-key"]`, which Gemini's initialize
220
+ * advertises), and Gemini keeps it in memory for the process's sessions (GeminiAgent.authenticate,
221
+ * 0.64.0). Not in GEMINI_API_KEY: in relay's sandbox the turn's own processes can read the
222
+ * environment each of them was started with (kern.procargs2), so every command the agent ran could
223
+ * read a key there (docs/gemini.md §2.4). Relay's sandbox denies the default key directory to every
224
+ * agent it confines, and relay redacts the key from everything it reads back (`secrets`).
225
+ */
226
+ export function geminiState(spec) {
227
+ // The opt-in again, before the key file is opened: whatever runs this, no key without it.
228
+ const optIn = optInProblem(spec);
229
+ if (optIn)
230
+ throw new Error(optIn);
231
+ const key = readApiKey("gemini");
232
+ const home = geminiHome(spec);
233
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
234
+ fs.chmodSync(home, 0o700);
235
+ const cache = path.join(home, ".cache");
236
+ const kept = fs.lstatSync(cache, { throwIfNoEntry: false });
237
+ if (kept && (kept.isSymbolicLink() || !kept.isDirectory())) {
238
+ throw new Error(`Gemini's session state for this session (${cache}) has been replaced by something other than a directory, which relay's sandbox would follow, so relay does not run Gemini on it. Start a new job.`);
239
+ }
240
+ for (const name of fs.readdirSync(home))
241
+ if (name !== ".cache")
242
+ fs.rmSync(path.join(home, name), { recursive: true, force: true });
243
+ fs.mkdirSync(cache, { recursive: true, mode: 0o700 });
244
+ // Of what Gemini keeps in .cache, its sessions carry over; its private project memory does not.
245
+ clearGeminiMemory(home);
246
+ // Relay's tools, through Gemini's tool discovery (geminiTools), for every turn relay serves them to
247
+ // (one with a broker), whatever the version: before the prompt, relay checks that discovery ran
248
+ // (geminiDiscoveryCheck), and tells the agent where it did not.
249
+ const toolsDir = spec.relay ? geminiToolsDir(spec) : null;
250
+ /** Where the helper's --list leaves its mark, once relay has written the turn's tool files. */
251
+ let listed = null;
252
+ const shim = toolsDir ? writeGeminiShim(toolsDir) : null;
253
+ const config = path.join(home, ".gemini");
254
+ fs.mkdirSync(config, { recursive: true, mode: 0o700 });
255
+ const settings = shim ? { ...GEMINI_SETTINGS, tools: { ...GEMINI_SETTINGS.tools, ...geminiToolCommands(shim) } } : GEMINI_SETTINGS;
256
+ fs.writeFileSync(path.join(config, "settings.json"), JSON.stringify(settings, null, 2), { mode: 0o600 });
257
+ fs.writeFileSync(geminiPolicyFile(spec), geminiPolicy(spec), { mode: 0o600 });
258
+ const node = nodeOnPath();
259
+ const execPaths = [...(node ? [node] : []), ...(shim ? [shim] : [])];
260
+ return {
261
+ stateDirs: [],
262
+ persistent: { root: home, writable: [".cache"] },
263
+ home: "temp",
264
+ ...(execPaths.length ? { execPaths } : {}),
265
+ env: {
266
+ GEMINI_CLI_HOME: home,
267
+ // Runtime state under .cache (above), and Gemini starts no sandbox of its own: it is inside
268
+ // one, relay's, as its system prompt then says (prompts/promptProvider.ts getSandboxMode).
269
+ SANDBOX: "sandbox-exec",
270
+ // The process relay starts is the agent, not a supervisor that relaunches it.
271
+ GEMINI_CLI_NO_RELAUNCH: "true",
272
+ GEMINI_SANDBOX: "false",
273
+ // Never the keychain (relay's sandbox denies it anyway): no stored key or login is looked for there.
274
+ GEMINI_FORCE_FILE_STORAGE: "true",
275
+ // Untrusted: the repository's .gemini/settings.json, .gemini/.env, hooks, skills, agents,
276
+ // commands and policies are not loaded. A trusted folder's .env could set any variable,
277
+ // GOOGLE_GEMINI_BASE_URL included, and send the key elsewhere.
278
+ GEMINI_CLI_TRUST_WORKSPACE: "false",
279
+ // Files that do not exist, in relay's read-only home: no administrator settings are read.
280
+ GEMINI_CLI_SYSTEM_SETTINGS_PATH: path.join(home, "system-settings.json"),
281
+ GEMINI_CLI_SYSTEM_DEFAULTS_PATH: path.join(home, "system-defaults.json"),
282
+ },
283
+ keychain: false,
284
+ authenticate: { methodId: "gemini-api-key", meta: { "api-key": key } },
285
+ secrets: [key],
286
+ ...(toolsDir ? {
287
+ bridgeReady: async (bridge) => { listed = await writeGeminiToolFiles(toolsDir, bridge); },
288
+ afterInitialize: () => geminiClearMark(listed),
289
+ beforePrompt: ({ agentVersion }) => geminiDiscoveryCheck(listed, agentVersion),
290
+ } : {}),
291
+ // Once the turn is over, so that the person's own session (resumeCommand) loads none of it either;
292
+ // the next turn clears it again whatever happened here. The turn's tool files go with it (the
293
+ // secret's own file goes with the broker): the next turn's home is rebuilt without them anyway.
294
+ cleanup: () => {
295
+ try {
296
+ clearGeminiMemory(home);
297
+ }
298
+ catch {
299
+ // Cleared again before the next turn, where a failure stops it.
300
+ }
301
+ if (toolsDir)
302
+ fs.rmSync(toolsDir, { recursive: true, force: true });
303
+ },
304
+ };
305
+ }
306
+ /**
307
+ * Relay's tools for a Gemini agent. In the untrusted folder relay runs Gemini in, 0.64.0 connects no
308
+ * MCP server, relay's bridge included (McpClientManager.startConfiguredMcpServers returns at once,
309
+ * packages/core/src/tools/mcp-client-manager.ts:576, and :461 for each server). Its command-based
310
+ * tool discovery has no such check (packages/core/src/tools/tool-registry.ts:376-540, run when each
311
+ * session's config is initialized, core config.ts:4126): `tools.discoveryCommand` prints the tools
312
+ * as function declarations, and `tools.callCommand <name>` runs one, its arguments as JSON on stdin,
313
+ * its stdout the result, a non-zero exit or any stderr a failure (:76-180). Both come from relay's
314
+ * own settings in its read-only home, never from the repository's, which an untrusted folder does
315
+ * not load. The model calls each as `discovered_tool_<name>` (targets/gemini.ts toolDiscovery).
316
+ *
317
+ * Both are one shim in `<home>/relay-tools`, read-only to the agent: `call` runs the helper
318
+ * (confine/gemini-tools.ts, through its own entry point GEMINI_TOOLS_MAIN) on relay's Node with an
319
+ * empty environment and --no-warnings. With --list it prints the
320
+ * turn's tools from `tools.json`, which relay wrote before Gemini started: static, so a broker that
321
+ * is gone cannot fail Gemini's session setup, which a failed discovery would; and it leaves a mark,
322
+ * which relay checks before the prompt (geminiDiscoveryCheck). Relay offers them whatever Gemini's
323
+ * version: their safety rests on relay's sandbox and broker. That check shows only that Gemini ran
324
+ * relay's discovery command for the session, not that every call will work. With a tool's name it
325
+ * calls that tool through the turn's broker, as the bridge would: the same socket, the same secret,
326
+ * the same checks of the peer's process tree and the turn (confine/broker.ts). Nothing in
327
+ * `<home>/relay-tools` is secret: `bridge.json` names the socket and the secret's file, which is the
328
+ * broker's own (Broker.secretFile), in the turn's private broker directory inside relay's sockets
329
+ * directory. Every confined turn's profile denies that directory, and only this turn's allows reading
330
+ * that one file (ConfinementPolicy.bridgeSecret), so the secret is readable only inside its turn, as
331
+ * the bridge's secret is in the bridge's environment. It is never on a command line or in an
332
+ * environment, since Gemini shows both command strings to its model in every tool's description.
333
+ * The agent's own commands can read it, as they can read the bridge's (kern.procargs2): the broker
334
+ * serves only the turn's own process tree, and only while the turn is live. The file goes with the
335
+ * broker's directory, and `cleanup` removes `<home>/relay-tools`, when the turn ends.
336
+ */
337
+ export const geminiToolsDir = (spec) => path.join(geminiHome(spec), "relay-tools");
338
+ /** Gemini's settings for relay's tools: the shim, with --list to discover them and alone to call one (it is spawned without a shell, so a path alone). */
339
+ export function geminiToolCommands(shim) {
340
+ return { discoveryCommand: `${shellQuote(shim)} --list`, callCommand: shim };
341
+ }
342
+ /**
343
+ * The helper's own entry point (confine/gemini-tools-main.ts), which imports confine/gemini-tools.js
344
+ * alone, and that only node:fs, node:net and node:path: not cli.js, whose import graph reaches
345
+ * node:sqlite, whose ExperimentalWarning before Node 24.15 put something on stderr on every call,
346
+ * which Gemini 0.64.0 reads as a failed call. `--no-warnings` as well, should a warning come anyway.
347
+ */
348
+ export const GEMINI_TOOLS_MAIN = path.resolve(import.meta.dirname, "..", "confine", "gemini-tools-main.js");
349
+ /** Writes the shim Gemini runs for relay's tools (geminiTools). It holds paths only, nothing secret. */
350
+ function writeGeminiShim(dir) {
351
+ fs.mkdirSync(dir, { mode: 0o700 });
352
+ const shim = path.join(dir, "call");
353
+ fs.writeFileSync(shim, [
354
+ "#!/bin/sh",
355
+ "# Relay's tools for this Gemini turn (relay backends/gemini.ts geminiTools): --list prints them, a tool's name calls it.",
356
+ `exec /usr/bin/env -i ${shellQuote(process.execPath)} --no-warnings ${shellQuote(GEMINI_TOOLS_MAIN)} ${shellQuote(dir)} "$@"`,
357
+ "",
358
+ ].join("\n"), { mode: 0o700 });
359
+ return shim;
360
+ }
361
+ /** Tools relay's policy denies by name (geminiPolicy); no tool of relay's may be discovered under one. */
362
+ export const GEMINI_DENIED_TOOLS = ["save_memory", "invoke_agent", "google_web_search", "web_fetch"];
363
+ /**
364
+ * Once the turn's broker is open (PreparedState.bridgeReady): the tools a bridge connection is
365
+ * offered, exactly as the broker lists them (name, description, input schema), as Gemini's function
366
+ * declarations (`tools.json`); and where the broker's socket and the secret's file are, and where
367
+ * the helper's --list leaves its mark (`bridge.json`, paths only). The mark goes in the turn's private
368
+ * temporary directory, which the turn may write and which goes with it (relay's Gemini home is
369
+ * read-only to the agent). Each tool must be one Gemini can name with its prefix and that no rule
370
+ * of relay's policy denies under that name. Returns where the mark goes.
371
+ */
372
+ export async function writeGeminiToolFiles(dir, bridge) {
373
+ const prefix = targetDef("gemini").toolDiscovery.prefix;
374
+ const declarations = (await bridge.listTools()).map((t) => {
375
+ const named = `${prefix}${t.name}`;
376
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t.name) || named.length > 64)
377
+ throw new Error(`relay cannot offer its tool ${JSON.stringify(t.name)} through Gemini's tool discovery: Gemini could not name it`);
378
+ if (GEMINI_DENIED_TOOLS.includes(named))
379
+ throw new Error(`relay's tool ${JSON.stringify(t.name)} would be discovered as ${named}, which relay's policy for Gemini denies`);
380
+ return { name: t.name, description: t.description ?? "", parametersJsonSchema: t.inputSchema };
381
+ });
382
+ fs.writeFileSync(path.join(dir, "tools.json"), JSON.stringify(declarations), { mode: 0o600 });
383
+ const listed = path.join(bridge.tmpDir, GEMINI_DISCOVERY_MARK);
384
+ fs.rmSync(listed, { force: true });
385
+ fs.writeFileSync(path.join(dir, "bridge.json"), JSON.stringify({ socket: bridge.socketPath, secret: bridge.secretFile, listed }), { mode: 0o600 });
386
+ return listed;
387
+ }
388
+ /** The file the helper's --list writes when Gemini runs relay's discovery command (confine/gemini-tools.ts). */
389
+ export const GEMINI_DISCOVERY_MARK = ".relay-tools-listed";
390
+ /**
391
+ * Removes the mark the helper's --list left while Gemini answered initialize (geminiDiscoveryCheck), so
392
+ * that only the session's own setup can leave it (PreparedState.afterInitialize). The turn's temporary
393
+ * directory is the turn's to write: anything but a file or a link there is left as it is, and counts
394
+ * as no mark.
395
+ */
396
+ export function geminiClearMark(listed) {
397
+ if (!listed)
398
+ return;
399
+ const st = fs.lstatSync(listed, { throwIfNoEntry: false });
400
+ if (st?.isFile() || st?.isSymbolicLink())
401
+ fs.rmSync(listed, { force: true });
402
+ }
403
+ /** What relay's prompt tells a Gemini agent whose session did not run relay's tool discovery, before anything else it reads. */
404
+ export const NO_DISCOVERED_TOOLS = "[relay] Before you start: relay's tools are not available to you in this turn after all. Gemini did not run relay's tool discovery when it set up this session, so you have no discovered_tool_ tools: do not try to delegate or reach other agents through relay; do the work yourself.";
405
+ /**
406
+ * Before the prompt (PreparedState.beforePrompt): whether Gemini ran relay's discovery command when
407
+ * it set up this turn's session, from the mark the helper's --list leaves. 0.64.0 and 0.65.0 run it
408
+ * twice per process: while they answer ACP initialize, for their start-up config
409
+ * (acpRpcDispatcher.ts:81 awaits config.initialize(); the discovery command comes from the same user
410
+ * settings, cli config.ts:985), and again while each session's config is initialized, before they
411
+ * answer session/new or session/load (acpSessionManager.ts newSession and loadSession await
412
+ * config.initialize()). Each initialize builds the tool registry (core config.ts:1508, :1510 in
413
+ * 0.65.0), which runs discovery (:4126, :4132). So the mark from initialize is removed before the
414
+ * session is asked for (geminiClearMark, PreparedState.afterInitialize), and only the session's own
415
+ * setup can leave it again. Where it did not, the agent is told before its prompt and the turn says
416
+ * so; the turn goes on without relay's tools. The mark shows that Gemini ran relay's discovery
417
+ * command for the session, not that every call will work. On a version relay's tools were not
418
+ * verified live on (toolDiscovery.versions), where it ran, the turn gets a short note saying so.
419
+ * `listed`: where the mark goes, or null where none was set up.
420
+ */
421
+ export function geminiDiscoveryCheck(listed, agentVersion) {
422
+ if (!listed)
423
+ return undefined;
424
+ const def = targetDef("gemini");
425
+ const verified = def.toolDiscovery.versions.join(", ");
426
+ const version = fullVersionOf(agentVersion);
427
+ const which = version ? `${def.product} ${version}` : `${def.product} (its version not reported)`;
428
+ if (!fs.lstatSync(listed, { throwIfNoEntry: false })?.isFile()) {
429
+ return {
430
+ promptPrefix: NO_DISCOVERED_TOOLS,
431
+ notes: [`${which} did not run relay's tool discovery when it set up this turn's session, so its agent had no relay tools; relay told it so before its prompt, and the turn went on without them. Relay checks this at every launch; relay's tools were checked on ${def.product} ${verified}.`],
432
+ };
433
+ }
434
+ if (!discoveryVerified(def, version))
435
+ return { notes: [`${which} is not a version relay's tools were checked on (${verified}); it ran relay's discovery command for this turn's session.`] };
436
+ return undefined;
437
+ }
438
+ /**
439
+ * Variables removed from Gemini's environment beyond credentials: every one of Gemini's own and
440
+ * of OpenTelemetry's (relay sets the ones it means), Google's credentials, project and gcloud
441
+ * settings (under child_auth "any" a target's own credentials would otherwise pass through; the
442
+ * key is relay's to hand over), the sandbox and debug switches. The endpoint variables are not
443
+ * removed: relay refuses to launch with one (the target's endpointEnv), as it does for every target.
444
+ */
445
+ const SCRUB = /^(GEMINI_|OTEL_|CLOUDSDK_|OAUTH_CALLBACK_|GOOGLE_CLOUD_|GOOGLE_GENAI_USE_)|^(GOOGLE_API_KEY|GOOGLE_APPLICATION_CREDENTIALS|CLOUD_SHELL|SANDBOX|SEATBELT_PROFILE|BUILD_SANDBOX|DEBUG|DEBUG_MODE|NO_BROWSER)$/;
446
+ /**
447
+ * Why relay may not hand Gemini a key this turn, or null: only with the person's opt-in by name,
448
+ * targets.gemini.child_auth "any" (the global child_auth does not count). The profile's refuse()
449
+ * says it before anything starts, and geminiState checks it again before it opens the key file.
450
+ */
451
+ function optInProblem(spec) {
452
+ if (spec.config.targets.gemini?.child_auth === "any")
453
+ return null;
454
+ let file;
455
+ try {
456
+ file = apiKeyFile("gemini");
457
+ }
458
+ catch {
459
+ file = "your key file";
460
+ }
461
+ return `Gemini CLI signs in only with an API key (Google no longer serves its account login to Gemini CLI), and relay hands one to it only when you ask for that by name: set targets.gemini.child_auth to "any" in relay's config (the global child_auth does not count). Relay then reads the key from ${file} and gives it to Gemini alone.`;
462
+ }
463
+ /** Whether there are administrator policies, which outrank relay's (a file in their directory). */
464
+ function adminPolicies() {
465
+ try {
466
+ return fs.readdirSync(adminPoliciesDir).some((n) => n.endsWith(".toml"));
467
+ }
468
+ catch {
469
+ return false;
470
+ }
471
+ }
472
+ /**
473
+ * What one of Gemini's approval requests asks for, in relay's terms. Gemini 0.64.0 sends no
474
+ * rawInput with a tool call (acpSession.ts, runTool): a shell command's call has kind "execute", the
475
+ * command itself as its title (ShellToolInvocation.getDisplayTitle is params.command), and as its
476
+ * one text content where it runs and why ("[in <dir_path>] (<description>)", or "[current working
477
+ * directory <cwd>] ..."). Its edits carry their paths in locations and their diff, which the
478
+ * generic reading takes. Whatever is approved, relay's sandbox stays on, and the request says so.
479
+ */
480
+ export function geminiApproval(call, spec) {
481
+ const text = (call.content ?? [])
482
+ .map((c) => c)
483
+ .map((c) => (c?.type === "content" && c.content?.type === "text" && typeof c.content.text === "string" ? c.content.text.trim() : ""))
484
+ .find(Boolean) ?? "";
485
+ const where = /^\[(?:in|current working directory) (.+?)\](?: \((.*)\))?(?: \[background\])?$/s.exec(text);
486
+ let ask = genericApproval(call);
487
+ const title = typeof call.title === "string" && call.title.trim() ? call.title : undefined;
488
+ if (!ask && call.kind === "execute" && title)
489
+ ask = { kind: "command", summary: title, ...(where?.[2] ? { reason: where[2] } : {}), detail: { tool_call: call.toolCallId } };
490
+ if (!ask)
491
+ return null;
492
+ const detail = (ask.detail ?? {});
493
+ const cwd = path.resolve(spec.cwd, where?.[1] ?? (typeof detail.cwd === "string" ? detail.cwd : "."));
494
+ const paths = ask.paths?.map((p) => path.resolve(spec.cwd, p));
495
+ return { ...ask, ...(paths ? { paths } : {}), detail: { ...detail, ...(ask.kind === "command" ? { cwd } : {}), confined: true } };
496
+ }
497
+ /**
498
+ * Gemini's model aliases (0.64.0 packages/core/src/config/models.ts: GEMINI_MODEL_ALIAS_* and the
499
+ * deprecated PREVIEW_GEMINI_MODEL_AUTO, DEFAULT_GEMINI_MODEL_AUTO): what it is configured with, never
500
+ * what serves a request, which is always a model id they resolve to.
501
+ */
502
+ export const GEMINI_ALIASES = new Set(["auto", "pro", "flash", "flash-lite", "auto-gemini-3", "auto-gemini-2.5"]);
503
+ /**
504
+ * The models that answered a Gemini prompt, from its response's `_meta.quota.model_usage` (the
505
+ * driver's promptModels), less the entries that name no served model. It names the model Gemini
506
+ * selected for each round, not the one that served it: an availability fallback taken inside a
507
+ * round (GeminiChat's retry, packages/core/src/core/geminiChat.ts:1018-1030 and :1191-1194;
508
+ * fallback/handler.ts processIntent, config.ts activateFallbackMode) is listed under the model that
509
+ * failed for that round, and only from the next round under its own name (config.getModel() after
510
+ * setModel), so a one-round prompt's fallback is not in it at all. In 0.64.0 that list counts the
511
+ * main loop only, one entry per model, in order of first use (packages/cli/src/acp/acpSession.ts:
512
+ * modelUsageMap, filled at 576-584 from the Finished events of geminiClient.sendMessageStream alone).
513
+ * Each round of the loop is keyed by `config.getModel()`, the configured id (:427), until the stream
514
+ * says which model it routed to (ModelInfo, :494-495). The stream says so only in the prompt's first
515
+ * round: ModelInfo is yielded while no model is fixed for the prompt (core/client.ts:825-828), which
516
+ * is reset only for a new prompt id (:953-958), and ACP keeps one prompt id for every round of a
517
+ * prompt (acpSession.ts:326, :434-437). So every round after a tool call is keyed by the configured
518
+ * id although the routed model answered it: "auto" (or another alias) with no pinned model, the pin
519
+ * itself where Gemini resolved it to another id (gemini-3.5-flash to gemini-3.8-flash, say,
520
+ * config/models.ts:311-317). Dropped here: an alias anywhere, and the model the session reported
521
+ * (`reported`, its configured id) after the first entry. What remains is what was routed to, or what
522
+ * an availability fallback within Google switched to. Gemini's helper calls, Flash-Lite among them,
523
+ * are never in the list: the map takes only the Finished events of the main chat's stream (turn.run
524
+ * with LlmRole.MAIN, core/client.ts:833-836), and the helpers go through BaseLlmClient, whose calls
525
+ * yield no event into it: the router's classifier (routing/strategies/classifierStrategy.ts:171-178,
526
+ * UTILITY_ROUTER), the next-speaker check (utils/nextSpeakerChecker.ts:113-119), loop detection
527
+ * (services/loopDetectionService.ts:704-712), chat compression (context/chatCompressionService.ts:
528
+ * 595-639); nor do the web tools' own calls (geminiClient.generateContent, tools/web-search.ts:95,
529
+ * tools/web-fetch.ts:475, :806).
530
+ */
531
+ export function geminiServedModels(response, reported) {
532
+ return promptModels(response).filter((m, i) => !GEMINI_ALIASES.has(m) && !(i > 0 && m === reported));
533
+ }
534
+ /**
535
+ * The directories granted to a write turn (grant.write_paths) that Gemini's own file tools may write
536
+ * in. They write only inside its workspace (write_file and edit check config.validatePathAccess,
537
+ * 0.64.0 packages/core/src/config/config.ts:3379-3438), which is the working directory and the
538
+ * directories `--include-directories` names, read from the process's arguments for every ACP session
539
+ * (packages/cli/src/acp/acpSessionManager.ts newSessionConfig, `loadCliConfig(…, this.argv, …)`;
540
+ * cli/src/config/config.ts:637-640), in an untrusted folder too (core config.ts:1459-1461 adds them
541
+ * with no trust check). Without them only shell commands could use a grant, and Gemini would ask
542
+ * about each one with a directory outside the workspace. Gemini splits the flag's value at commas and
543
+ * trims each part (coerceCommaSeparated, cli config.ts:119-129), so a granted directory whose path
544
+ * has a comma, or starts or ends with a space, is left out: relay's sandbox still lets its shell
545
+ * commands write there. Relay's sandbox is the boundary either way; this only lets Gemini's tools
546
+ * use what the sandbox allows.
547
+ */
548
+ export function geminiIncludeDirectories(spec) {
549
+ if (spec.access !== "write")
550
+ return [];
551
+ return (spec.grant?.write_paths ?? []).filter((d) => path.isAbsolute(d) && !d.includes(",") && d === d.trim());
552
+ }
553
+ /**
554
+ * The prompt as relay sends it to Gemini. 0.64.0 joins a prompt's text, trims it, and runs one that
555
+ * starts with "/" or "$" as one of its ACP commands when its first word names one (memory,
556
+ * extensions, init, restore, about, help): the model never sees it, and the turn ends with the
557
+ * command's output and an empty model_usage (packages/cli/src/acp/acpSession.ts:347-371,
558
+ * acpCommandHandler.ts:25-30, 98-103). A resume message or follow-up goes to Gemini as the caller
559
+ * wrote it, so one that starts so gets a line in front that is no command.
560
+ */
561
+ export function geminiPromptText(prompt) {
562
+ const t = prompt.trimStart();
563
+ return t.startsWith("/") || t.startsWith("$") ? `The message below is for you; it is not a Gemini CLI command.\n\n${prompt}` : prompt;
564
+ }
565
+ export const geminiProfile = {
566
+ // The model applies to every session of this process; the session's reported model is checked
567
+ // against it. Gemini has no reasoning-effort flag, so effort is not applied. Relay's tool policy
568
+ // is handed over here, not left in Gemini's home (geminiPolicy); a write turn's granted directories
569
+ // join its workspace (geminiIncludeDirectories).
570
+ args: (spec, model) => [
571
+ "--acp", "--policy", geminiPolicyFile(spec),
572
+ ...geminiIncludeDirectories(spec).flatMap((d) => ["--include-directories", d]),
573
+ ...(model ? ["--model", model] : []),
574
+ ],
575
+ promptText: geminiPromptText,
576
+ scrub: (k) => SCRUB.test(k),
577
+ prepareState: geminiState,
578
+ login: {
579
+ how: "Gemini CLI signs in with an API key only. Relay reads it from your key file and hands it to Gemini alone (in ACP authenticate), when targets.gemini.child_auth is \"any\".",
580
+ },
581
+ // Its approval mode in an untrusted folder; read back before the prompt.
582
+ mode: () => "default",
583
+ normalizeApproval: geminiApproval,
584
+ // Only the prompt's response says which models answered (_meta.quota.model_usage); the session
585
+ // reports what was asked for, or "auto". Recorded as served, as every model report is, less the
586
+ // entries that stand for the configured id (geminiServedModels).
587
+ servedModels: geminiServedModels,
588
+ // Its session lists a menu (auto, 2.5 Pro, its default Flash and Flash-Lite, previews), while
589
+ // --model takes any id (buildAvailableModels, 0.64.0): a model the menu leaves out is not refused.
590
+ acceptsUnlistedModels: true,
591
+ // 0.64.0 answers session/load and then streams the conversation, without waiting for it
592
+ // (packages/cli/src/acp/acpSessionManager.ts:284, `session.streamHistory(messages)` not awaited,
593
+ // then `return response` at :294), each update awaited in turn (acpSession.ts:249-315). So relay
594
+ // lets the replay end before it prompts. The replay writes local history, a few milliseconds' work
595
+ // even for a long session; the prompt's first words wait on a round trip to Google.
596
+ replaysAfterLoad: { quietMs: 300, maxMs: 30_000 },
597
+ refuse(spec) {
598
+ const optIn = optInProblem(spec);
599
+ if (optIn)
600
+ return optIn;
601
+ if (adminPolicies()) {
602
+ return `this Mac has Gemini CLI administrator policies (${adminPoliciesDir}), which outrank relay's own and which no setting moves, so relay cannot tell what Gemini would be allowed to do. It does not run Gemini here.`;
603
+ }
604
+ return null;
605
+ },
606
+ };
607
+ export const geminiBackend = acpBackend(geminiProfile);