@google/gemini-cli 0.1.17-nightly.250808.60362e03 → 0.1.18

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 (130) hide show
  1. package/README.md +0 -10
  2. package/dist/google-gemini-cli-0.1.17.tgz +0 -0
  3. package/dist/package.json +2 -4
  4. package/dist/src/acp/acpPeer.js +64 -72
  5. package/dist/src/acp/acpPeer.js.map +1 -1
  6. package/dist/src/config/config.js +38 -67
  7. package/dist/src/config/config.js.map +1 -1
  8. package/dist/src/config/settings.d.ts +1 -5
  9. package/dist/src/config/settings.js +1 -17
  10. package/dist/src/config/settings.js.map +1 -1
  11. package/dist/src/gemini.js +27 -3
  12. package/dist/src/gemini.js.map +1 -1
  13. package/dist/src/generated/git-commit.d.ts +1 -1
  14. package/dist/src/generated/git-commit.js +1 -1
  15. package/dist/src/nonInteractiveCli.js +1 -0
  16. package/dist/src/nonInteractiveCli.js.map +1 -1
  17. package/dist/src/services/BuiltinCommandLoader.js +2 -1
  18. package/dist/src/services/BuiltinCommandLoader.js.map +1 -1
  19. package/dist/src/ui/App.js +13 -44
  20. package/dist/src/ui/App.js.map +1 -1
  21. package/dist/src/ui/commands/setupGithubCommand.js +18 -57
  22. package/dist/src/ui/commands/setupGithubCommand.js.map +1 -1
  23. package/dist/src/ui/components/AsciiArt.d.ts +0 -1
  24. package/dist/src/ui/components/AsciiArt.js +0 -10
  25. package/dist/src/ui/components/AsciiArt.js.map +1 -1
  26. package/dist/src/ui/components/AuthInProgress.js +3 -3
  27. package/dist/src/ui/components/AuthInProgress.js.map +1 -1
  28. package/dist/src/ui/components/ContextSummaryDisplay.js +24 -21
  29. package/dist/src/ui/components/ContextSummaryDisplay.js.map +1 -1
  30. package/dist/src/ui/components/Footer.js +5 -14
  31. package/dist/src/ui/components/Footer.js.map +1 -1
  32. package/dist/src/ui/components/Header.d.ts +1 -0
  33. package/dist/src/ui/components/Header.js +5 -13
  34. package/dist/src/ui/components/Header.js.map +1 -1
  35. package/dist/src/ui/components/IDEContextDetailDisplay.js +1 -14
  36. package/dist/src/ui/components/IDEContextDetailDisplay.js.map +1 -1
  37. package/dist/src/ui/components/InputPrompt.js +3 -3
  38. package/dist/src/ui/components/InputPrompt.js.map +1 -1
  39. package/dist/src/ui/components/LoadingIndicator.js +5 -10
  40. package/dist/src/ui/components/LoadingIndicator.js.map +1 -1
  41. package/dist/src/ui/components/SuggestionsDisplay.js +1 -1
  42. package/dist/src/ui/components/SuggestionsDisplay.js.map +1 -1
  43. package/dist/src/ui/components/messages/ToolConfirmationMessage.js +9 -29
  44. package/dist/src/ui/components/messages/ToolConfirmationMessage.js.map +1 -1
  45. package/dist/src/ui/hooks/atCommandProcessor.js +4 -7
  46. package/dist/src/ui/hooks/atCommandProcessor.js.map +1 -1
  47. package/dist/src/ui/hooks/useAtCompletion.js +1 -4
  48. package/dist/src/ui/hooks/useAtCompletion.js.map +1 -1
  49. package/dist/src/ui/hooks/useGeminiStream.d.ts +1 -1
  50. package/dist/src/ui/hooks/useGeminiStream.js +1 -2
  51. package/dist/src/ui/hooks/useGeminiStream.js.map +1 -1
  52. package/dist/src/ui/hooks/usePhraseCycler.js +2 -1
  53. package/dist/src/ui/hooks/usePhraseCycler.js.map +1 -1
  54. package/dist/src/ui/hooks/useReactToolScheduler.js +12 -12
  55. package/dist/src/ui/hooks/useReactToolScheduler.js.map +1 -1
  56. package/dist/src/ui/themes/ansi-light.js +1 -2
  57. package/dist/src/ui/themes/ansi-light.js.map +1 -1
  58. package/dist/src/ui/themes/ansi.js +1 -2
  59. package/dist/src/ui/themes/ansi.js.map +1 -1
  60. package/dist/src/ui/themes/atom-one-dark.js +1 -2
  61. package/dist/src/ui/themes/atom-one-dark.js.map +1 -1
  62. package/dist/src/ui/themes/ayu-light.js +1 -2
  63. package/dist/src/ui/themes/ayu-light.js.map +1 -1
  64. package/dist/src/ui/themes/ayu.js +1 -2
  65. package/dist/src/ui/themes/ayu.js.map +1 -1
  66. package/dist/src/ui/themes/default-light.js +1 -2
  67. package/dist/src/ui/themes/default-light.js.map +1 -1
  68. package/dist/src/ui/themes/default.js +1 -2
  69. package/dist/src/ui/themes/default.js.map +1 -1
  70. package/dist/src/ui/themes/dracula.js +1 -2
  71. package/dist/src/ui/themes/dracula.js.map +1 -1
  72. package/dist/src/ui/themes/github-dark.js +1 -2
  73. package/dist/src/ui/themes/github-dark.js.map +1 -1
  74. package/dist/src/ui/themes/github-light.js +1 -2
  75. package/dist/src/ui/themes/github-light.js.map +1 -1
  76. package/dist/src/ui/themes/googlecode.js +1 -2
  77. package/dist/src/ui/themes/googlecode.js.map +1 -1
  78. package/dist/src/ui/themes/no-color.js +1 -30
  79. package/dist/src/ui/themes/no-color.js.map +1 -1
  80. package/dist/src/ui/themes/shades-of-purple.js +1 -2
  81. package/dist/src/ui/themes/shades-of-purple.js.map +1 -1
  82. package/dist/src/ui/themes/theme-manager.d.ts +0 -6
  83. package/dist/src/ui/themes/theme-manager.js +0 -7
  84. package/dist/src/ui/themes/theme-manager.js.map +1 -1
  85. package/dist/src/ui/themes/theme.d.ts +2 -45
  86. package/dist/src/ui/themes/theme.js +107 -92
  87. package/dist/src/ui/themes/theme.js.map +1 -1
  88. package/dist/src/ui/themes/xcode.js +1 -2
  89. package/dist/src/ui/themes/xcode.js.map +1 -1
  90. package/dist/src/ui/types.d.ts +1 -1
  91. package/dist/src/ui/utils/ConsolePatcher.d.ts +0 -1
  92. package/dist/src/ui/utils/ConsolePatcher.js +0 -3
  93. package/dist/src/ui/utils/ConsolePatcher.js.map +1 -1
  94. package/dist/src/ui/utils/commandUtils.d.ts +0 -1
  95. package/dist/src/ui/utils/commandUtils.js +1 -22
  96. package/dist/src/ui/utils/commandUtils.js.map +1 -1
  97. package/dist/src/utils/gitUtils.d.ts +1 -21
  98. package/dist/src/utils/gitUtils.js +3 -70
  99. package/dist/src/utils/gitUtils.js.map +1 -1
  100. package/dist/src/utils/sandbox.js +405 -416
  101. package/dist/src/utils/sandbox.js.map +1 -1
  102. package/dist/tsconfig.tsbuildinfo +1 -1
  103. package/package.json +3 -5
  104. package/dist/src/commands/mcp/add.d.ts +0 -7
  105. package/dist/src/commands/mcp/add.js +0 -155
  106. package/dist/src/commands/mcp/add.js.map +0 -1
  107. package/dist/src/commands/mcp/list.d.ts +0 -8
  108. package/dist/src/commands/mcp/list.js +0 -110
  109. package/dist/src/commands/mcp/list.js.map +0 -1
  110. package/dist/src/commands/mcp/remove.d.ts +0 -7
  111. package/dist/src/commands/mcp/remove.js +0 -44
  112. package/dist/src/commands/mcp/remove.js.map +0 -1
  113. package/dist/src/commands/mcp.d.ts +0 -7
  114. package/dist/src/commands/mcp.js +0 -23
  115. package/dist/src/commands/mcp.js.map +0 -1
  116. package/dist/src/ui/IdeIntegrationNudge.d.ts +0 -13
  117. package/dist/src/ui/IdeIntegrationNudge.js +0 -31
  118. package/dist/src/ui/IdeIntegrationNudge.js.map +0 -1
  119. package/dist/src/ui/components/ContextUsageDisplay.d.ts +0 -9
  120. package/dist/src/ui/components/ContextUsageDisplay.js +0 -14
  121. package/dist/src/ui/components/ContextUsageDisplay.js.map +0 -1
  122. package/dist/src/ui/semantic-colors.d.ts +0 -7
  123. package/dist/src/ui/semantic-colors.js +0 -24
  124. package/dist/src/ui/semantic-colors.js.map +0 -1
  125. package/dist/src/ui/themes/semantic-tokens.d.ts +0 -37
  126. package/dist/src/ui/themes/semantic-tokens.js +0 -94
  127. package/dist/src/ui/themes/semantic-tokens.js.map +0 -1
  128. package/dist/src/ui/utils/isNarrowWidth.d.ts +0 -6
  129. package/dist/src/ui/utils/isNarrowWidth.js +0 -9
  130. package/dist/src/ui/utils/isNarrowWidth.js.map +0 -1
@@ -11,7 +11,6 @@ import { readFile } from 'node:fs/promises';
11
11
  import { quote, parse } from 'shell-quote';
12
12
  import { USER_SETTINGS_DIR, SETTINGS_DIRECTORY_NAME, } from '../config/settings.js';
13
13
  import { promisify } from 'util';
14
- import { ConsolePatcher } from '../ui/utils/ConsolePatcher.js';
15
14
  const execAsync = promisify(exec);
16
15
  function getContainerPath(hostPath) {
17
16
  if (os.platform() !== 'win32') {
@@ -144,428 +143,99 @@ function entrypoint(workdir) {
144
143
  return ['bash', '-c', args.join(' ')];
145
144
  }
146
145
  export async function start_sandbox(config, nodeArgs = [], cliConfig) {
147
- const patcher = new ConsolePatcher({
148
- debugMode: cliConfig?.getDebugMode() || !!process.env.DEBUG,
149
- stderr: true,
150
- });
151
- patcher.patch();
152
- try {
153
- if (config.command === 'sandbox-exec') {
154
- // disallow BUILD_SANDBOX
155
- if (process.env.BUILD_SANDBOX) {
156
- console.error('ERROR: cannot BUILD_SANDBOX when using macOS Seatbelt');
157
- process.exit(1);
158
- }
159
- const profile = (process.env.SEATBELT_PROFILE ??= 'permissive-open');
160
- let profileFile = new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
161
- .pathname;
162
- // if profile name is not recognized, then look for file under project settings directory
163
- if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
164
- profileFile = path.join(SETTINGS_DIRECTORY_NAME, `sandbox-macos-${profile}.sb`);
165
- }
166
- if (!fs.existsSync(profileFile)) {
167
- console.error(`ERROR: missing macos seatbelt profile file '${profileFile}'`);
168
- process.exit(1);
169
- }
170
- // Log on STDERR so it doesn't clutter the output on STDOUT
171
- console.error(`using macos seatbelt (profile: ${profile}) ...`);
172
- // if DEBUG is set, convert to --inspect-brk in NODE_OPTIONS
173
- const nodeOptions = [
174
- ...(process.env.DEBUG ? ['--inspect-brk'] : []),
175
- ...nodeArgs,
176
- ].join(' ');
177
- const args = [
178
- '-D',
179
- `TARGET_DIR=${fs.realpathSync(process.cwd())}`,
180
- '-D',
181
- `TMP_DIR=${fs.realpathSync(os.tmpdir())}`,
182
- '-D',
183
- `HOME_DIR=${fs.realpathSync(os.homedir())}`,
184
- '-D',
185
- `CACHE_DIR=${fs.realpathSync(execSync(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`,
186
- ];
187
- // Add included directories from the workspace context
188
- // Always add 5 INCLUDE_DIR parameters to ensure .sb files can reference them
189
- const MAX_INCLUDE_DIRS = 5;
190
- const targetDir = fs.realpathSync(cliConfig?.getTargetDir() || '');
191
- const includedDirs = [];
192
- if (cliConfig) {
193
- const workspaceContext = cliConfig.getWorkspaceContext();
194
- const directories = workspaceContext.getDirectories();
195
- // Filter out TARGET_DIR
196
- for (const dir of directories) {
197
- const realDir = fs.realpathSync(dir);
198
- if (realDir !== targetDir) {
199
- includedDirs.push(realDir);
200
- }
201
- }
202
- }
203
- for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
204
- let dirPath = '/dev/null'; // Default to a safe path that won't cause issues
205
- if (i < includedDirs.length) {
206
- dirPath = includedDirs[i];
207
- }
208
- args.push('-D', `INCLUDE_DIR_${i}=${dirPath}`);
209
- }
210
- args.push('-f', profileFile, 'sh', '-c', [
211
- `SANDBOX=sandbox-exec`,
212
- `NODE_OPTIONS="${nodeOptions}"`,
213
- ...process.argv.map((arg) => quote([arg])),
214
- ].join(' '));
215
- // start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
216
- const proxyCommand = process.env.GEMINI_SANDBOX_PROXY_COMMAND;
217
- let proxyProcess = undefined;
218
- let sandboxProcess = undefined;
219
- const sandboxEnv = { ...process.env };
220
- if (proxyCommand) {
221
- const proxy = process.env.HTTPS_PROXY ||
222
- process.env.https_proxy ||
223
- process.env.HTTP_PROXY ||
224
- process.env.http_proxy ||
225
- 'http://localhost:8877';
226
- sandboxEnv['HTTPS_PROXY'] = proxy;
227
- sandboxEnv['https_proxy'] = proxy; // lower-case can be required, e.g. for curl
228
- sandboxEnv['HTTP_PROXY'] = proxy;
229
- sandboxEnv['http_proxy'] = proxy;
230
- const noProxy = process.env.NO_PROXY || process.env.no_proxy;
231
- if (noProxy) {
232
- sandboxEnv['NO_PROXY'] = noProxy;
233
- sandboxEnv['no_proxy'] = noProxy;
234
- }
235
- proxyProcess = spawn(proxyCommand, {
236
- stdio: ['ignore', 'pipe', 'pipe'],
237
- shell: true,
238
- detached: true,
239
- });
240
- // install handlers to stop proxy on exit/signal
241
- const stopProxy = () => {
242
- console.log('stopping proxy ...');
243
- if (proxyProcess?.pid) {
244
- process.kill(-proxyProcess.pid, 'SIGTERM');
245
- }
246
- };
247
- process.on('exit', stopProxy);
248
- process.on('SIGINT', stopProxy);
249
- process.on('SIGTERM', stopProxy);
250
- // commented out as it disrupts ink rendering
251
- // proxyProcess.stdout?.on('data', (data) => {
252
- // console.info(data.toString());
253
- // });
254
- proxyProcess.stderr?.on('data', (data) => {
255
- console.error(data.toString());
256
- });
257
- proxyProcess.on('close', (code, signal) => {
258
- console.error(`ERROR: proxy command '${proxyCommand}' exited with code ${code}, signal ${signal}`);
259
- if (sandboxProcess?.pid) {
260
- process.kill(-sandboxProcess.pid, 'SIGTERM');
261
- }
262
- process.exit(1);
263
- });
264
- console.log('waiting for proxy to start ...');
265
- await execAsync(`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`);
266
- }
267
- // spawn child and let it inherit stdio
268
- sandboxProcess = spawn(config.command, args, {
269
- stdio: 'inherit',
270
- });
271
- await new Promise((resolve) => sandboxProcess?.on('close', resolve));
272
- return;
273
- }
274
- console.error(`hopping into sandbox (command: ${config.command}) ...`);
275
- // determine full path for gemini-cli to distinguish linked vs installed setting
276
- const gcPath = fs.realpathSync(process.argv[1]);
277
- const projectSandboxDockerfile = path.join(SETTINGS_DIRECTORY_NAME, 'sandbox.Dockerfile');
278
- const isCustomProjectSandbox = fs.existsSync(projectSandboxDockerfile);
279
- const image = config.image;
280
- const workdir = path.resolve(process.cwd());
281
- const containerWorkdir = getContainerPath(workdir);
282
- // if BUILD_SANDBOX is set, then call scripts/build_sandbox.js under gemini-cli repo
283
- //
284
- // note this can only be done with binary linked from gemini-cli repo
146
+ if (config.command === 'sandbox-exec') {
147
+ // disallow BUILD_SANDBOX
285
148
  if (process.env.BUILD_SANDBOX) {
286
- if (!gcPath.includes('gemini-cli/packages/')) {
287
- console.error('ERROR: cannot build sandbox using installed gemini binary; ' +
288
- 'run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary.');
289
- process.exit(1);
290
- }
291
- else {
292
- console.error('building sandbox ...');
293
- const gcRoot = gcPath.split('/packages/')[0];
294
- // if project folder has sandbox.Dockerfile under project settings folder, use that
295
- let buildArgs = '';
296
- const projectSandboxDockerfile = path.join(SETTINGS_DIRECTORY_NAME, 'sandbox.Dockerfile');
297
- if (isCustomProjectSandbox) {
298
- console.error(`using ${projectSandboxDockerfile} for sandbox`);
299
- buildArgs += `-f ${path.resolve(projectSandboxDockerfile)} -i ${image}`;
300
- }
301
- execSync(`cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`, {
302
- stdio: 'inherit',
303
- env: {
304
- ...process.env,
305
- GEMINI_SANDBOX: config.command, // in case sandbox is enabled via flags (see config.ts under cli package)
306
- },
307
- });
308
- }
309
- }
310
- // stop if image is missing
311
- if (!(await ensureSandboxImageIsPresent(config.command, image))) {
312
- const remedy = image === LOCAL_DEV_SANDBOX_IMAGE_NAME
313
- ? 'Try running `npm run build:all` or `npm run build:sandbox` under the gemini-cli repo to build it locally, or check the image name and your network connection.'
314
- : 'Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists.';
315
- console.error(`ERROR: Sandbox image '${image}' is missing or could not be pulled. ${remedy}`);
149
+ console.error('ERROR: cannot BUILD_SANDBOX when using macOS Seatbelt');
316
150
  process.exit(1);
317
151
  }
318
- // use interactive mode and auto-remove container on exit
319
- // run init binary inside container to forward signals & reap zombies
320
- const args = ['run', '-i', '--rm', '--init', '--workdir', containerWorkdir];
321
- // add custom flags from SANDBOX_FLAGS
322
- if (process.env.SANDBOX_FLAGS) {
323
- const flags = parse(process.env.SANDBOX_FLAGS, process.env).filter((f) => typeof f === 'string');
324
- args.push(...flags);
325
- }
326
- // add TTY only if stdin is TTY as well, i.e. for piped input don't init TTY in container
327
- if (process.stdin.isTTY) {
328
- args.push('-t');
329
- }
330
- // mount current directory as working directory in sandbox (set via --workdir)
331
- args.push('--volume', `${workdir}:${containerWorkdir}`);
332
- // mount user settings directory inside container, after creating if missing
333
- // note user/home changes inside sandbox and we mount at BOTH paths for consistency
334
- const userSettingsDirOnHost = USER_SETTINGS_DIR;
335
- const userSettingsDirInSandbox = getContainerPath(`/home/node/${SETTINGS_DIRECTORY_NAME}`);
336
- if (!fs.existsSync(userSettingsDirOnHost)) {
337
- fs.mkdirSync(userSettingsDirOnHost);
152
+ const profile = (process.env.SEATBELT_PROFILE ??= 'permissive-open');
153
+ let profileFile = new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
154
+ .pathname;
155
+ // if profile name is not recognized, then look for file under project settings directory
156
+ if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
157
+ profileFile = path.join(SETTINGS_DIRECTORY_NAME, `sandbox-macos-${profile}.sb`);
338
158
  }
339
- args.push('--volume', `${userSettingsDirOnHost}:${userSettingsDirInSandbox}`);
340
- if (userSettingsDirInSandbox !== userSettingsDirOnHost) {
341
- args.push('--volume', `${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`);
342
- }
343
- // mount os.tmpdir() as os.tmpdir() inside container
344
- args.push('--volume', `${os.tmpdir()}:${getContainerPath(os.tmpdir())}`);
345
- // mount gcloud config directory if it exists
346
- const gcloudConfigDir = path.join(os.homedir(), '.config', 'gcloud');
347
- if (fs.existsSync(gcloudConfigDir)) {
348
- args.push('--volume', `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`);
349
- }
350
- // mount ADC file if GOOGLE_APPLICATION_CREDENTIALS is set
351
- if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
352
- const adcFile = process.env.GOOGLE_APPLICATION_CREDENTIALS;
353
- if (fs.existsSync(adcFile)) {
354
- args.push('--volume', `${adcFile}:${getContainerPath(adcFile)}:ro`);
355
- args.push('--env', `GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`);
356
- }
159
+ if (!fs.existsSync(profileFile)) {
160
+ console.error(`ERROR: missing macos seatbelt profile file '${profileFile}'`);
161
+ process.exit(1);
357
162
  }
358
- // mount paths listed in SANDBOX_MOUNTS
359
- if (process.env.SANDBOX_MOUNTS) {
360
- for (let mount of process.env.SANDBOX_MOUNTS.split(',')) {
361
- if (mount.trim()) {
362
- // parse mount as from:to:opts
363
- let [from, to, opts] = mount.trim().split(':');
364
- to = to || from; // default to mount at same path inside container
365
- opts = opts || 'ro'; // default to read-only
366
- mount = `${from}:${to}:${opts}`;
367
- // check that from path is absolute
368
- if (!path.isAbsolute(from)) {
369
- console.error(`ERROR: path '${from}' listed in SANDBOX_MOUNTS must be absolute`);
370
- process.exit(1);
371
- }
372
- // check that from path exists on host
373
- if (!fs.existsSync(from)) {
374
- console.error(`ERROR: missing mount path '${from}' listed in SANDBOX_MOUNTS`);
375
- process.exit(1);
376
- }
377
- console.error(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
378
- args.push('--volume', mount);
163
+ // Log on STDERR so it doesn't clutter the output on STDOUT
164
+ console.error(`using macos seatbelt (profile: ${profile}) ...`);
165
+ // if DEBUG is set, convert to --inspect-brk in NODE_OPTIONS
166
+ const nodeOptions = [
167
+ ...(process.env.DEBUG ? ['--inspect-brk'] : []),
168
+ ...nodeArgs,
169
+ ].join(' ');
170
+ const args = [
171
+ '-D',
172
+ `TARGET_DIR=${fs.realpathSync(process.cwd())}`,
173
+ '-D',
174
+ `TMP_DIR=${fs.realpathSync(os.tmpdir())}`,
175
+ '-D',
176
+ `HOME_DIR=${fs.realpathSync(os.homedir())}`,
177
+ '-D',
178
+ `CACHE_DIR=${fs.realpathSync(execSync(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`,
179
+ ];
180
+ // Add included directories from the workspace context
181
+ // Always add 5 INCLUDE_DIR parameters to ensure .sb files can reference them
182
+ const MAX_INCLUDE_DIRS = 5;
183
+ const targetDir = fs.realpathSync(cliConfig?.getTargetDir() || '');
184
+ const includedDirs = [];
185
+ if (cliConfig) {
186
+ const workspaceContext = cliConfig.getWorkspaceContext();
187
+ const directories = workspaceContext.getDirectories();
188
+ // Filter out TARGET_DIR
189
+ for (const dir of directories) {
190
+ const realDir = fs.realpathSync(dir);
191
+ if (realDir !== targetDir) {
192
+ includedDirs.push(realDir);
379
193
  }
380
194
  }
381
195
  }
382
- // expose env-specified ports on the sandbox
383
- ports().forEach((p) => args.push('--publish', `${p}:${p}`));
384
- // if DEBUG is set, expose debugging port
385
- if (process.env.DEBUG) {
386
- const debugPort = process.env.DEBUG_PORT || '9229';
387
- args.push(`--publish`, `${debugPort}:${debugPort}`);
196
+ for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
197
+ let dirPath = '/dev/null'; // Default to a safe path that won't cause issues
198
+ if (i < includedDirs.length) {
199
+ dirPath = includedDirs[i];
200
+ }
201
+ args.push('-D', `INCLUDE_DIR_${i}=${dirPath}`);
388
202
  }
389
- // copy proxy environment variables, replacing localhost with SANDBOX_PROXY_NAME
390
- // copy as both upper-case and lower-case as is required by some utilities
391
- // GEMINI_SANDBOX_PROXY_COMMAND implies HTTPS_PROXY unless HTTP_PROXY is set
203
+ args.push('-f', profileFile, 'sh', '-c', [
204
+ `SANDBOX=sandbox-exec`,
205
+ `NODE_OPTIONS="${nodeOptions}"`,
206
+ ...process.argv.map((arg) => quote([arg])),
207
+ ].join(' '));
208
+ // start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
392
209
  const proxyCommand = process.env.GEMINI_SANDBOX_PROXY_COMMAND;
210
+ let proxyProcess = undefined;
211
+ let sandboxProcess = undefined;
212
+ const sandboxEnv = { ...process.env };
393
213
  if (proxyCommand) {
394
- let proxy = process.env.HTTPS_PROXY ||
214
+ const proxy = process.env.HTTPS_PROXY ||
395
215
  process.env.https_proxy ||
396
216
  process.env.HTTP_PROXY ||
397
217
  process.env.http_proxy ||
398
218
  'http://localhost:8877';
399
- proxy = proxy.replace('localhost', SANDBOX_PROXY_NAME);
400
- if (proxy) {
401
- args.push('--env', `HTTPS_PROXY=${proxy}`);
402
- args.push('--env', `https_proxy=${proxy}`); // lower-case can be required, e.g. for curl
403
- args.push('--env', `HTTP_PROXY=${proxy}`);
404
- args.push('--env', `http_proxy=${proxy}`);
405
- }
219
+ sandboxEnv['HTTPS_PROXY'] = proxy;
220
+ sandboxEnv['https_proxy'] = proxy; // lower-case can be required, e.g. for curl
221
+ sandboxEnv['HTTP_PROXY'] = proxy;
222
+ sandboxEnv['http_proxy'] = proxy;
406
223
  const noProxy = process.env.NO_PROXY || process.env.no_proxy;
407
224
  if (noProxy) {
408
- args.push('--env', `NO_PROXY=${noProxy}`);
409
- args.push('--env', `no_proxy=${noProxy}`);
410
- }
411
- // if using proxy, switch to internal networking through proxy
412
- if (proxy) {
413
- execSync(`${config.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config.command} network create --internal ${SANDBOX_NETWORK_NAME}`);
414
- args.push('--network', SANDBOX_NETWORK_NAME);
415
- // if proxy command is set, create a separate network w/ host access (i.e. non-internal)
416
- // we will run proxy in its own container connected to both host network and internal network
417
- // this allows proxy to work even on rootless podman on macos with host<->vm<->container isolation
418
- if (proxyCommand) {
419
- execSync(`${config.command} network inspect ${SANDBOX_PROXY_NAME} || ${config.command} network create ${SANDBOX_PROXY_NAME}`);
420
- }
421
- }
422
- }
423
- // name container after image, plus numeric suffix to avoid conflicts
424
- const imageName = parseImageName(image);
425
- let index = 0;
426
- const containerNameCheck = execSync(`${config.command} ps -a --format "{{.Names}}"`)
427
- .toString()
428
- .trim();
429
- while (containerNameCheck.includes(`${imageName}-${index}`)) {
430
- index++;
431
- }
432
- const containerName = `${imageName}-${index}`;
433
- args.push('--name', containerName, '--hostname', containerName);
434
- // copy GEMINI_API_KEY(s)
435
- if (process.env.GEMINI_API_KEY) {
436
- args.push('--env', `GEMINI_API_KEY=${process.env.GEMINI_API_KEY}`);
437
- }
438
- if (process.env.GOOGLE_API_KEY) {
439
- args.push('--env', `GOOGLE_API_KEY=${process.env.GOOGLE_API_KEY}`);
440
- }
441
- // copy GOOGLE_GENAI_USE_VERTEXAI
442
- if (process.env.GOOGLE_GENAI_USE_VERTEXAI) {
443
- args.push('--env', `GOOGLE_GENAI_USE_VERTEXAI=${process.env.GOOGLE_GENAI_USE_VERTEXAI}`);
444
- }
445
- // copy GOOGLE_GENAI_USE_GCA
446
- if (process.env.GOOGLE_GENAI_USE_GCA) {
447
- args.push('--env', `GOOGLE_GENAI_USE_GCA=${process.env.GOOGLE_GENAI_USE_GCA}`);
448
- }
449
- // copy GOOGLE_CLOUD_PROJECT
450
- if (process.env.GOOGLE_CLOUD_PROJECT) {
451
- args.push('--env', `GOOGLE_CLOUD_PROJECT=${process.env.GOOGLE_CLOUD_PROJECT}`);
452
- }
453
- // copy GOOGLE_CLOUD_LOCATION
454
- if (process.env.GOOGLE_CLOUD_LOCATION) {
455
- args.push('--env', `GOOGLE_CLOUD_LOCATION=${process.env.GOOGLE_CLOUD_LOCATION}`);
456
- }
457
- // copy GEMINI_MODEL
458
- if (process.env.GEMINI_MODEL) {
459
- args.push('--env', `GEMINI_MODEL=${process.env.GEMINI_MODEL}`);
460
- }
461
- // copy TERM and COLORTERM to try to maintain terminal setup
462
- if (process.env.TERM) {
463
- args.push('--env', `TERM=${process.env.TERM}`);
464
- }
465
- if (process.env.COLORTERM) {
466
- args.push('--env', `COLORTERM=${process.env.COLORTERM}`);
467
- }
468
- // copy VIRTUAL_ENV if under working directory
469
- // also mount-replace VIRTUAL_ENV directory with <project_settings>/sandbox.venv
470
- // sandbox can then set up this new VIRTUAL_ENV directory using sandbox.bashrc (see below)
471
- // directory will be empty if not set up, which is still preferable to having host binaries
472
- if (process.env.VIRTUAL_ENV?.toLowerCase().startsWith(workdir.toLowerCase())) {
473
- const sandboxVenvPath = path.resolve(SETTINGS_DIRECTORY_NAME, 'sandbox.venv');
474
- if (!fs.existsSync(sandboxVenvPath)) {
475
- fs.mkdirSync(sandboxVenvPath, { recursive: true });
476
- }
477
- args.push('--volume', `${sandboxVenvPath}:${getContainerPath(process.env.VIRTUAL_ENV)}`);
478
- args.push('--env', `VIRTUAL_ENV=${getContainerPath(process.env.VIRTUAL_ENV)}`);
479
- }
480
- // copy additional environment variables from SANDBOX_ENV
481
- if (process.env.SANDBOX_ENV) {
482
- for (let env of process.env.SANDBOX_ENV.split(',')) {
483
- if ((env = env.trim())) {
484
- if (env.includes('=')) {
485
- console.error(`SANDBOX_ENV: ${env}`);
486
- args.push('--env', env);
487
- }
488
- else {
489
- console.error('ERROR: SANDBOX_ENV must be a comma-separated list of key=value pairs');
490
- process.exit(1);
491
- }
492
- }
225
+ sandboxEnv['NO_PROXY'] = noProxy;
226
+ sandboxEnv['no_proxy'] = noProxy;
493
227
  }
494
- }
495
- // copy NODE_OPTIONS
496
- const existingNodeOptions = process.env.NODE_OPTIONS || '';
497
- const allNodeOptions = [
498
- ...(existingNodeOptions ? [existingNodeOptions] : []),
499
- ...nodeArgs,
500
- ].join(' ');
501
- if (allNodeOptions.length > 0) {
502
- args.push('--env', `NODE_OPTIONS="${allNodeOptions}"`);
503
- }
504
- // set SANDBOX as container name
505
- args.push('--env', `SANDBOX=${containerName}`);
506
- // for podman only, use empty --authfile to skip unnecessary auth refresh overhead
507
- if (config.command === 'podman') {
508
- const emptyAuthFilePath = path.join(os.tmpdir(), 'empty_auth.json');
509
- fs.writeFileSync(emptyAuthFilePath, '{}', 'utf-8');
510
- args.push('--authfile', emptyAuthFilePath);
511
- }
512
- // Determine if the current user's UID/GID should be passed to the sandbox.
513
- // See shouldUseCurrentUserInSandbox for more details.
514
- let userFlag = '';
515
- const finalEntrypoint = entrypoint(workdir);
516
- if (process.env.GEMINI_CLI_INTEGRATION_TEST === 'true') {
517
- args.push('--user', 'root');
518
- userFlag = '--user root';
519
- }
520
- else if (await shouldUseCurrentUserInSandbox()) {
521
- // For the user-creation logic to work, the container must start as root.
522
- // The entrypoint script then handles dropping privileges to the correct user.
523
- args.push('--user', 'root');
524
- const uid = execSync('id -u').toString().trim();
525
- const gid = execSync('id -g').toString().trim();
526
- // Instead of passing --user to the main sandbox container, we let it
527
- // start as root, then create a user with the host's UID/GID, and
528
- // finally switch to that user to run the gemini process. This is
529
- // necessary on Linux to ensure the user exists within the
530
- // container's /etc/passwd file, which is required by os.userInfo().
531
- const username = 'gemini';
532
- const homeDir = getContainerPath(os.homedir());
533
- const setupUserCommands = [
534
- // Use -f with groupadd to avoid errors if the group already exists.
535
- `groupadd -f -g ${gid} ${username}`,
536
- // Create user only if it doesn't exist. Use -o for non-unique UID.
537
- `id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`,
538
- ].join(' && ');
539
- const originalCommand = finalEntrypoint[2];
540
- const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''");
541
- // Use `su -p` to preserve the environment.
542
- const suCommand = `su -p ${username} -c '${escapedOriginalCommand}'`;
543
- // The entrypoint is always `['bash', '-c', '<command>']`, so we modify the command part.
544
- finalEntrypoint[2] = `${setupUserCommands} && ${suCommand}`;
545
- // We still need userFlag for the simpler proxy container, which does not have this issue.
546
- userFlag = `--user ${uid}:${gid}`;
547
- // When forcing a UID in the sandbox, $HOME can be reset to '/', so we copy $HOME as well.
548
- args.push('--env', `HOME=${os.homedir()}`);
549
- }
550
- // push container image name
551
- args.push(image);
552
- // push container entrypoint (including args)
553
- args.push(...finalEntrypoint);
554
- // start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
555
- let proxyProcess = undefined;
556
- let sandboxProcess = undefined;
557
- if (proxyCommand) {
558
- // run proxyCommand in its own container
559
- const proxyContainerCommand = `${config.command} run --rm --init ${userFlag} --name ${SANDBOX_PROXY_NAME} --network ${SANDBOX_PROXY_NAME} -p 8877:8877 -v ${process.cwd()}:${workdir} --workdir ${workdir} ${image} ${proxyCommand}`;
560
- proxyProcess = spawn(proxyContainerCommand, {
228
+ proxyProcess = spawn(proxyCommand, {
561
229
  stdio: ['ignore', 'pipe', 'pipe'],
562
230
  shell: true,
563
231
  detached: true,
564
232
  });
565
233
  // install handlers to stop proxy on exit/signal
566
234
  const stopProxy = () => {
567
- console.log('stopping proxy container ...');
568
- execSync(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`);
235
+ console.log('stopping proxy ...');
236
+ if (proxyProcess?.pid) {
237
+ process.kill(-proxyProcess.pid, 'SIGTERM');
238
+ }
569
239
  };
570
240
  process.on('exit', stopProxy);
571
241
  process.on('SIGINT', stopProxy);
@@ -575,10 +245,10 @@ export async function start_sandbox(config, nodeArgs = [], cliConfig) {
575
245
  // console.info(data.toString());
576
246
  // });
577
247
  proxyProcess.stderr?.on('data', (data) => {
578
- console.error(data.toString().trim());
248
+ console.error(data.toString());
579
249
  });
580
250
  proxyProcess.on('close', (code, signal) => {
581
- console.error(`ERROR: proxy container command '${proxyContainerCommand}' exited with code ${code}, signal ${signal}`);
251
+ console.error(`ERROR: proxy command '${proxyCommand}' exited with code ${code}, signal ${signal}`);
582
252
  if (sandboxProcess?.pid) {
583
253
  process.kill(-sandboxProcess.pid, 'SIGTERM');
584
254
  }
@@ -586,29 +256,348 @@ export async function start_sandbox(config, nodeArgs = [], cliConfig) {
586
256
  });
587
257
  console.log('waiting for proxy to start ...');
588
258
  await execAsync(`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`);
589
- // connect proxy container to sandbox network
590
- // (workaround for older versions of docker that don't support multiple --network args)
591
- await execAsync(`${config.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`);
592
259
  }
593
260
  // spawn child and let it inherit stdio
594
261
  sandboxProcess = spawn(config.command, args, {
595
262
  stdio: 'inherit',
596
263
  });
597
- sandboxProcess.on('error', (err) => {
598
- console.error('Sandbox process error:', err);
599
- });
600
- await new Promise((resolve) => {
601
- sandboxProcess?.on('close', (code, signal) => {
602
- if (code !== 0) {
603
- console.log(`Sandbox process exited with code: ${code}, signal: ${signal}`);
604
- }
605
- resolve();
264
+ await new Promise((resolve) => sandboxProcess?.on('close', resolve));
265
+ return;
266
+ }
267
+ console.error(`hopping into sandbox (command: ${config.command}) ...`);
268
+ // determine full path for gemini-cli to distinguish linked vs installed setting
269
+ const gcPath = fs.realpathSync(process.argv[1]);
270
+ const projectSandboxDockerfile = path.join(SETTINGS_DIRECTORY_NAME, 'sandbox.Dockerfile');
271
+ const isCustomProjectSandbox = fs.existsSync(projectSandboxDockerfile);
272
+ const image = config.image;
273
+ const workdir = path.resolve(process.cwd());
274
+ const containerWorkdir = getContainerPath(workdir);
275
+ // if BUILD_SANDBOX is set, then call scripts/build_sandbox.js under gemini-cli repo
276
+ //
277
+ // note this can only be done with binary linked from gemini-cli repo
278
+ if (process.env.BUILD_SANDBOX) {
279
+ if (!gcPath.includes('gemini-cli/packages/')) {
280
+ console.error('ERROR: cannot build sandbox using installed gemini binary; ' +
281
+ 'run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary.');
282
+ process.exit(1);
283
+ }
284
+ else {
285
+ console.error('building sandbox ...');
286
+ const gcRoot = gcPath.split('/packages/')[0];
287
+ // if project folder has sandbox.Dockerfile under project settings folder, use that
288
+ let buildArgs = '';
289
+ const projectSandboxDockerfile = path.join(SETTINGS_DIRECTORY_NAME, 'sandbox.Dockerfile');
290
+ if (isCustomProjectSandbox) {
291
+ console.error(`using ${projectSandboxDockerfile} for sandbox`);
292
+ buildArgs += `-f ${path.resolve(projectSandboxDockerfile)} -i ${image}`;
293
+ }
294
+ execSync(`cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`, {
295
+ stdio: 'inherit',
296
+ env: {
297
+ ...process.env,
298
+ GEMINI_SANDBOX: config.command, // in case sandbox is enabled via flags (see config.ts under cli package)
299
+ },
606
300
  });
607
- });
301
+ }
302
+ }
303
+ // stop if image is missing
304
+ if (!(await ensureSandboxImageIsPresent(config.command, image))) {
305
+ const remedy = image === LOCAL_DEV_SANDBOX_IMAGE_NAME
306
+ ? 'Try running `npm run build:all` or `npm run build:sandbox` under the gemini-cli repo to build it locally, or check the image name and your network connection.'
307
+ : 'Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists.';
308
+ console.error(`ERROR: Sandbox image '${image}' is missing or could not be pulled. ${remedy}`);
309
+ process.exit(1);
310
+ }
311
+ // use interactive mode and auto-remove container on exit
312
+ // run init binary inside container to forward signals & reap zombies
313
+ const args = ['run', '-i', '--rm', '--init', '--workdir', containerWorkdir];
314
+ // add custom flags from SANDBOX_FLAGS
315
+ if (process.env.SANDBOX_FLAGS) {
316
+ const flags = parse(process.env.SANDBOX_FLAGS, process.env).filter((f) => typeof f === 'string');
317
+ args.push(...flags);
318
+ }
319
+ // add TTY only if stdin is TTY as well, i.e. for piped input don't init TTY in container
320
+ if (process.stdin.isTTY) {
321
+ args.push('-t');
322
+ }
323
+ // mount current directory as working directory in sandbox (set via --workdir)
324
+ args.push('--volume', `${workdir}:${containerWorkdir}`);
325
+ // mount user settings directory inside container, after creating if missing
326
+ // note user/home changes inside sandbox and we mount at BOTH paths for consistency
327
+ const userSettingsDirOnHost = USER_SETTINGS_DIR;
328
+ const userSettingsDirInSandbox = getContainerPath(`/home/node/${SETTINGS_DIRECTORY_NAME}`);
329
+ if (!fs.existsSync(userSettingsDirOnHost)) {
330
+ fs.mkdirSync(userSettingsDirOnHost);
331
+ }
332
+ args.push('--volume', `${userSettingsDirOnHost}:${userSettingsDirInSandbox}`);
333
+ if (userSettingsDirInSandbox !== userSettingsDirOnHost) {
334
+ args.push('--volume', `${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`);
335
+ }
336
+ // mount os.tmpdir() as os.tmpdir() inside container
337
+ args.push('--volume', `${os.tmpdir()}:${getContainerPath(os.tmpdir())}`);
338
+ // mount gcloud config directory if it exists
339
+ const gcloudConfigDir = path.join(os.homedir(), '.config', 'gcloud');
340
+ if (fs.existsSync(gcloudConfigDir)) {
341
+ args.push('--volume', `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`);
342
+ }
343
+ // mount ADC file if GOOGLE_APPLICATION_CREDENTIALS is set
344
+ if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
345
+ const adcFile = process.env.GOOGLE_APPLICATION_CREDENTIALS;
346
+ if (fs.existsSync(adcFile)) {
347
+ args.push('--volume', `${adcFile}:${getContainerPath(adcFile)}:ro`);
348
+ args.push('--env', `GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`);
349
+ }
350
+ }
351
+ // mount paths listed in SANDBOX_MOUNTS
352
+ if (process.env.SANDBOX_MOUNTS) {
353
+ for (let mount of process.env.SANDBOX_MOUNTS.split(',')) {
354
+ if (mount.trim()) {
355
+ // parse mount as from:to:opts
356
+ let [from, to, opts] = mount.trim().split(':');
357
+ to = to || from; // default to mount at same path inside container
358
+ opts = opts || 'ro'; // default to read-only
359
+ mount = `${from}:${to}:${opts}`;
360
+ // check that from path is absolute
361
+ if (!path.isAbsolute(from)) {
362
+ console.error(`ERROR: path '${from}' listed in SANDBOX_MOUNTS must be absolute`);
363
+ process.exit(1);
364
+ }
365
+ // check that from path exists on host
366
+ if (!fs.existsSync(from)) {
367
+ console.error(`ERROR: missing mount path '${from}' listed in SANDBOX_MOUNTS`);
368
+ process.exit(1);
369
+ }
370
+ console.error(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
371
+ args.push('--volume', mount);
372
+ }
373
+ }
374
+ }
375
+ // expose env-specified ports on the sandbox
376
+ ports().forEach((p) => args.push('--publish', `${p}:${p}`));
377
+ // if DEBUG is set, expose debugging port
378
+ if (process.env.DEBUG) {
379
+ const debugPort = process.env.DEBUG_PORT || '9229';
380
+ args.push(`--publish`, `${debugPort}:${debugPort}`);
381
+ }
382
+ // copy proxy environment variables, replacing localhost with SANDBOX_PROXY_NAME
383
+ // copy as both upper-case and lower-case as is required by some utilities
384
+ // GEMINI_SANDBOX_PROXY_COMMAND implies HTTPS_PROXY unless HTTP_PROXY is set
385
+ const proxyCommand = process.env.GEMINI_SANDBOX_PROXY_COMMAND;
386
+ if (proxyCommand) {
387
+ let proxy = process.env.HTTPS_PROXY ||
388
+ process.env.https_proxy ||
389
+ process.env.HTTP_PROXY ||
390
+ process.env.http_proxy ||
391
+ 'http://localhost:8877';
392
+ proxy = proxy.replace('localhost', SANDBOX_PROXY_NAME);
393
+ if (proxy) {
394
+ args.push('--env', `HTTPS_PROXY=${proxy}`);
395
+ args.push('--env', `https_proxy=${proxy}`); // lower-case can be required, e.g. for curl
396
+ args.push('--env', `HTTP_PROXY=${proxy}`);
397
+ args.push('--env', `http_proxy=${proxy}`);
398
+ }
399
+ const noProxy = process.env.NO_PROXY || process.env.no_proxy;
400
+ if (noProxy) {
401
+ args.push('--env', `NO_PROXY=${noProxy}`);
402
+ args.push('--env', `no_proxy=${noProxy}`);
403
+ }
404
+ // if using proxy, switch to internal networking through proxy
405
+ if (proxy) {
406
+ execSync(`${config.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config.command} network create --internal ${SANDBOX_NETWORK_NAME}`);
407
+ args.push('--network', SANDBOX_NETWORK_NAME);
408
+ // if proxy command is set, create a separate network w/ host access (i.e. non-internal)
409
+ // we will run proxy in its own container connected to both host network and internal network
410
+ // this allows proxy to work even on rootless podman on macos with host<->vm<->container isolation
411
+ if (proxyCommand) {
412
+ execSync(`${config.command} network inspect ${SANDBOX_PROXY_NAME} || ${config.command} network create ${SANDBOX_PROXY_NAME}`);
413
+ }
414
+ }
415
+ }
416
+ // name container after image, plus numeric suffix to avoid conflicts
417
+ const imageName = parseImageName(image);
418
+ let index = 0;
419
+ const containerNameCheck = execSync(`${config.command} ps -a --format "{{.Names}}"`)
420
+ .toString()
421
+ .trim();
422
+ while (containerNameCheck.includes(`${imageName}-${index}`)) {
423
+ index++;
608
424
  }
609
- finally {
610
- patcher.cleanup();
425
+ const containerName = `${imageName}-${index}`;
426
+ args.push('--name', containerName, '--hostname', containerName);
427
+ // copy GEMINI_API_KEY(s)
428
+ if (process.env.GEMINI_API_KEY) {
429
+ args.push('--env', `GEMINI_API_KEY=${process.env.GEMINI_API_KEY}`);
611
430
  }
431
+ if (process.env.GOOGLE_API_KEY) {
432
+ args.push('--env', `GOOGLE_API_KEY=${process.env.GOOGLE_API_KEY}`);
433
+ }
434
+ // copy GOOGLE_GENAI_USE_VERTEXAI
435
+ if (process.env.GOOGLE_GENAI_USE_VERTEXAI) {
436
+ args.push('--env', `GOOGLE_GENAI_USE_VERTEXAI=${process.env.GOOGLE_GENAI_USE_VERTEXAI}`);
437
+ }
438
+ // copy GOOGLE_GENAI_USE_GCA
439
+ if (process.env.GOOGLE_GENAI_USE_GCA) {
440
+ args.push('--env', `GOOGLE_GENAI_USE_GCA=${process.env.GOOGLE_GENAI_USE_GCA}`);
441
+ }
442
+ // copy GOOGLE_CLOUD_PROJECT
443
+ if (process.env.GOOGLE_CLOUD_PROJECT) {
444
+ args.push('--env', `GOOGLE_CLOUD_PROJECT=${process.env.GOOGLE_CLOUD_PROJECT}`);
445
+ }
446
+ // copy GOOGLE_CLOUD_LOCATION
447
+ if (process.env.GOOGLE_CLOUD_LOCATION) {
448
+ args.push('--env', `GOOGLE_CLOUD_LOCATION=${process.env.GOOGLE_CLOUD_LOCATION}`);
449
+ }
450
+ // copy GEMINI_MODEL
451
+ if (process.env.GEMINI_MODEL) {
452
+ args.push('--env', `GEMINI_MODEL=${process.env.GEMINI_MODEL}`);
453
+ }
454
+ // copy TERM and COLORTERM to try to maintain terminal setup
455
+ if (process.env.TERM) {
456
+ args.push('--env', `TERM=${process.env.TERM}`);
457
+ }
458
+ if (process.env.COLORTERM) {
459
+ args.push('--env', `COLORTERM=${process.env.COLORTERM}`);
460
+ }
461
+ // copy VIRTUAL_ENV if under working directory
462
+ // also mount-replace VIRTUAL_ENV directory with <project_settings>/sandbox.venv
463
+ // sandbox can then set up this new VIRTUAL_ENV directory using sandbox.bashrc (see below)
464
+ // directory will be empty if not set up, which is still preferable to having host binaries
465
+ if (process.env.VIRTUAL_ENV?.toLowerCase().startsWith(workdir.toLowerCase())) {
466
+ const sandboxVenvPath = path.resolve(SETTINGS_DIRECTORY_NAME, 'sandbox.venv');
467
+ if (!fs.existsSync(sandboxVenvPath)) {
468
+ fs.mkdirSync(sandboxVenvPath, { recursive: true });
469
+ }
470
+ args.push('--volume', `${sandboxVenvPath}:${getContainerPath(process.env.VIRTUAL_ENV)}`);
471
+ args.push('--env', `VIRTUAL_ENV=${getContainerPath(process.env.VIRTUAL_ENV)}`);
472
+ }
473
+ // copy additional environment variables from SANDBOX_ENV
474
+ if (process.env.SANDBOX_ENV) {
475
+ for (let env of process.env.SANDBOX_ENV.split(',')) {
476
+ if ((env = env.trim())) {
477
+ if (env.includes('=')) {
478
+ console.error(`SANDBOX_ENV: ${env}`);
479
+ args.push('--env', env);
480
+ }
481
+ else {
482
+ console.error('ERROR: SANDBOX_ENV must be a comma-separated list of key=value pairs');
483
+ process.exit(1);
484
+ }
485
+ }
486
+ }
487
+ }
488
+ // copy NODE_OPTIONS
489
+ const existingNodeOptions = process.env.NODE_OPTIONS || '';
490
+ const allNodeOptions = [
491
+ ...(existingNodeOptions ? [existingNodeOptions] : []),
492
+ ...nodeArgs,
493
+ ].join(' ');
494
+ if (allNodeOptions.length > 0) {
495
+ args.push('--env', `NODE_OPTIONS="${allNodeOptions}"`);
496
+ }
497
+ // set SANDBOX as container name
498
+ args.push('--env', `SANDBOX=${containerName}`);
499
+ // for podman only, use empty --authfile to skip unnecessary auth refresh overhead
500
+ if (config.command === 'podman') {
501
+ const emptyAuthFilePath = path.join(os.tmpdir(), 'empty_auth.json');
502
+ fs.writeFileSync(emptyAuthFilePath, '{}', 'utf-8');
503
+ args.push('--authfile', emptyAuthFilePath);
504
+ }
505
+ // Determine if the current user's UID/GID should be passed to the sandbox.
506
+ // See shouldUseCurrentUserInSandbox for more details.
507
+ let userFlag = '';
508
+ const finalEntrypoint = entrypoint(workdir);
509
+ if (process.env.GEMINI_CLI_INTEGRATION_TEST === 'true') {
510
+ args.push('--user', 'root');
511
+ userFlag = '--user root';
512
+ }
513
+ else if (await shouldUseCurrentUserInSandbox()) {
514
+ // For the user-creation logic to work, the container must start as root.
515
+ // The entrypoint script then handles dropping privileges to the correct user.
516
+ args.push('--user', 'root');
517
+ const uid = execSync('id -u').toString().trim();
518
+ const gid = execSync('id -g').toString().trim();
519
+ // Instead of passing --user to the main sandbox container, we let it
520
+ // start as root, then create a user with the host's UID/GID, and
521
+ // finally switch to that user to run the gemini process. This is
522
+ // necessary on Linux to ensure the user exists within the
523
+ // container's /etc/passwd file, which is required by os.userInfo().
524
+ const username = 'gemini';
525
+ const homeDir = getContainerPath(os.homedir());
526
+ const setupUserCommands = [
527
+ // Use -f with groupadd to avoid errors if the group already exists.
528
+ `groupadd -f -g ${gid} ${username}`,
529
+ // Create user only if it doesn't exist. Use -o for non-unique UID.
530
+ `id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`,
531
+ ].join(' && ');
532
+ const originalCommand = finalEntrypoint[2];
533
+ const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''");
534
+ // Use `su -p` to preserve the environment.
535
+ const suCommand = `su -p ${username} -c '${escapedOriginalCommand}'`;
536
+ // The entrypoint is always `['bash', '-c', '<command>']`, so we modify the command part.
537
+ finalEntrypoint[2] = `${setupUserCommands} && ${suCommand}`;
538
+ // We still need userFlag for the simpler proxy container, which does not have this issue.
539
+ userFlag = `--user ${uid}:${gid}`;
540
+ // When forcing a UID in the sandbox, $HOME can be reset to '/', so we copy $HOME as well.
541
+ args.push('--env', `HOME=${os.homedir()}`);
542
+ }
543
+ // push container image name
544
+ args.push(image);
545
+ // push container entrypoint (including args)
546
+ args.push(...finalEntrypoint);
547
+ // start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
548
+ let proxyProcess = undefined;
549
+ let sandboxProcess = undefined;
550
+ if (proxyCommand) {
551
+ // run proxyCommand in its own container
552
+ const proxyContainerCommand = `${config.command} run --rm --init ${userFlag} --name ${SANDBOX_PROXY_NAME} --network ${SANDBOX_PROXY_NAME} -p 8877:8877 -v ${process.cwd()}:${workdir} --workdir ${workdir} ${image} ${proxyCommand}`;
553
+ proxyProcess = spawn(proxyContainerCommand, {
554
+ stdio: ['ignore', 'pipe', 'pipe'],
555
+ shell: true,
556
+ detached: true,
557
+ });
558
+ // install handlers to stop proxy on exit/signal
559
+ const stopProxy = () => {
560
+ console.log('stopping proxy container ...');
561
+ execSync(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`);
562
+ };
563
+ process.on('exit', stopProxy);
564
+ process.on('SIGINT', stopProxy);
565
+ process.on('SIGTERM', stopProxy);
566
+ // commented out as it disrupts ink rendering
567
+ // proxyProcess.stdout?.on('data', (data) => {
568
+ // console.info(data.toString());
569
+ // });
570
+ proxyProcess.stderr?.on('data', (data) => {
571
+ console.error(data.toString().trim());
572
+ });
573
+ proxyProcess.on('close', (code, signal) => {
574
+ console.error(`ERROR: proxy container command '${proxyContainerCommand}' exited with code ${code}, signal ${signal}`);
575
+ if (sandboxProcess?.pid) {
576
+ process.kill(-sandboxProcess.pid, 'SIGTERM');
577
+ }
578
+ process.exit(1);
579
+ });
580
+ console.log('waiting for proxy to start ...');
581
+ await execAsync(`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`);
582
+ // connect proxy container to sandbox network
583
+ // (workaround for older versions of docker that don't support multiple --network args)
584
+ await execAsync(`${config.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`);
585
+ }
586
+ // spawn child and let it inherit stdio
587
+ sandboxProcess = spawn(config.command, args, {
588
+ stdio: 'inherit',
589
+ });
590
+ sandboxProcess.on('error', (err) => {
591
+ console.error('Sandbox process error:', err);
592
+ });
593
+ await new Promise((resolve) => {
594
+ sandboxProcess?.on('close', (code, signal) => {
595
+ if (code !== 0) {
596
+ console.log(`Sandbox process exited with code: ${code}, signal: ${signal}`);
597
+ }
598
+ resolve();
599
+ });
600
+ });
612
601
  }
613
602
  // Helper functions to ensure sandbox image is present
614
603
  async function imageExists(sandbox, image) {