|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import { exec, execSync, spawn, type ChildProcess } from 'node:child_process'; |
|
|
import os from 'node:os'; |
|
|
import path from 'node:path'; |
|
|
import fs from 'node:fs'; |
|
|
import { readFile } from 'node:fs/promises'; |
|
|
import { fileURLToPath } from 'node:url'; |
|
|
import { quote, parse } from 'shell-quote'; |
|
|
import { |
|
|
USER_SETTINGS_DIR, |
|
|
SETTINGS_DIRECTORY_NAME, |
|
|
} from '../config/settings.js'; |
|
|
import { promisify } from 'node:util'; |
|
|
import type { Config, SandboxConfig } from '@google/gemini-cli-core'; |
|
|
import { FatalSandboxError } from '@google/gemini-cli-core'; |
|
|
import { ConsolePatcher } from '../ui/utils/ConsolePatcher.js'; |
|
|
|
|
|
const execAsync = promisify(exec); |
|
|
|
|
|
function getContainerPath(hostPath: string): string { |
|
|
if (os.platform() !== 'win32') { |
|
|
return hostPath; |
|
|
} |
|
|
|
|
|
const withForwardSlashes = hostPath.replace(/\\/g, '/'); |
|
|
const match = withForwardSlashes.match(/^([A-Z]):\/(.*)/i); |
|
|
if (match) { |
|
|
return `/${match[1].toLowerCase()}/${match[2]}`; |
|
|
} |
|
|
return hostPath; |
|
|
} |
|
|
|
|
|
const LOCAL_DEV_SANDBOX_IMAGE_NAME = 'gemini-cli-sandbox'; |
|
|
const SANDBOX_NETWORK_NAME = 'gemini-cli-sandbox'; |
|
|
const SANDBOX_PROXY_NAME = 'gemini-cli-sandbox-proxy'; |
|
|
const BUILTIN_SEATBELT_PROFILES = [ |
|
|
'permissive-open', |
|
|
'permissive-closed', |
|
|
'permissive-proxied', |
|
|
'restrictive-open', |
|
|
'restrictive-closed', |
|
|
'restrictive-proxied', |
|
|
]; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function shouldUseCurrentUserInSandbox(): Promise<boolean> { |
|
|
const envVar = process.env['SANDBOX_SET_UID_GID']?.toLowerCase().trim(); |
|
|
|
|
|
if (envVar === '1' || envVar === 'true') { |
|
|
return true; |
|
|
} |
|
|
if (envVar === '0' || envVar === 'false') { |
|
|
return false; |
|
|
} |
|
|
|
|
|
|
|
|
if (os.platform() === 'linux') { |
|
|
try { |
|
|
const osReleaseContent = await readFile('/etc/os-release', 'utf8'); |
|
|
if ( |
|
|
osReleaseContent.includes('ID=debian') || |
|
|
osReleaseContent.includes('ID=ubuntu') || |
|
|
osReleaseContent.match(/^ID_LIKE=.*debian.*/m) || |
|
|
osReleaseContent.match(/^ID_LIKE=.*ubuntu.*/m) |
|
|
) { |
|
|
|
|
|
console.error( |
|
|
'INFO: Defaulting to use current user UID/GID for Debian/Ubuntu-based Linux.', |
|
|
); |
|
|
return true; |
|
|
} |
|
|
} catch (_err) { |
|
|
|
|
|
|
|
|
console.warn( |
|
|
'Warning: Could not read /etc/os-release to auto-detect Debian/Ubuntu for UID/GID default.', |
|
|
); |
|
|
} |
|
|
} |
|
|
return false; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
function parseImageName(image: string): string { |
|
|
const [fullName, tag] = image.split(':'); |
|
|
const name = fullName.split('/').at(-1) ?? 'unknown-image'; |
|
|
return tag ? `${name}-${tag}` : name; |
|
|
} |
|
|
|
|
|
function ports(): string[] { |
|
|
return (process.env['SANDBOX_PORTS'] ?? '') |
|
|
.split(',') |
|
|
.filter((p) => p.trim()) |
|
|
.map((p) => p.trim()); |
|
|
} |
|
|
|
|
|
function entrypoint(workdir: string, cliArgs: string[]): string[] { |
|
|
const isWindows = os.platform() === 'win32'; |
|
|
const containerWorkdir = getContainerPath(workdir); |
|
|
const shellCmds = []; |
|
|
const pathSeparator = isWindows ? ';' : ':'; |
|
|
|
|
|
let pathSuffix = ''; |
|
|
if (process.env['PATH']) { |
|
|
const paths = process.env['PATH'].split(pathSeparator); |
|
|
for (const p of paths) { |
|
|
const containerPath = getContainerPath(p); |
|
|
if ( |
|
|
containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase()) |
|
|
) { |
|
|
pathSuffix += `:${containerPath}`; |
|
|
} |
|
|
} |
|
|
} |
|
|
if (pathSuffix) { |
|
|
shellCmds.push(`export PATH="$PATH${pathSuffix}";`); |
|
|
} |
|
|
|
|
|
let pythonPathSuffix = ''; |
|
|
if (process.env['PYTHONPATH']) { |
|
|
const paths = process.env['PYTHONPATH'].split(pathSeparator); |
|
|
for (const p of paths) { |
|
|
const containerPath = getContainerPath(p); |
|
|
if ( |
|
|
containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase()) |
|
|
) { |
|
|
pythonPathSuffix += `:${containerPath}`; |
|
|
} |
|
|
} |
|
|
} |
|
|
if (pythonPathSuffix) { |
|
|
shellCmds.push(`export PYTHONPATH="$PYTHONPATH${pythonPathSuffix}";`); |
|
|
} |
|
|
|
|
|
const projectSandboxBashrc = path.join( |
|
|
SETTINGS_DIRECTORY_NAME, |
|
|
'sandbox.bashrc', |
|
|
); |
|
|
if (fs.existsSync(projectSandboxBashrc)) { |
|
|
shellCmds.push(`source ${getContainerPath(projectSandboxBashrc)};`); |
|
|
} |
|
|
|
|
|
ports().forEach((p) => |
|
|
shellCmds.push( |
|
|
`socat TCP4-LISTEN:${p},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${p} 2> /dev/null &`, |
|
|
), |
|
|
); |
|
|
|
|
|
const quotedCliArgs = cliArgs.slice(2).map((arg) => quote([arg])); |
|
|
const cliCmd = |
|
|
process.env['NODE_ENV'] === 'development' |
|
|
? process.env['DEBUG'] |
|
|
? 'npm run debug --' |
|
|
: 'npm rebuild && npm run start --' |
|
|
: process.env['DEBUG'] |
|
|
? `node --inspect-brk=0.0.0.0:${process.env['DEBUG_PORT'] || '9229'} $(which gemini)` |
|
|
: 'gemini'; |
|
|
|
|
|
const args = [...shellCmds, cliCmd, ...quotedCliArgs]; |
|
|
return ['bash', '-c', args.join(' ')]; |
|
|
} |
|
|
|
|
|
export async function start_sandbox( |
|
|
config: SandboxConfig, |
|
|
nodeArgs: string[] = [], |
|
|
cliConfig?: Config, |
|
|
cliArgs: string[] = [], |
|
|
) { |
|
|
const patcher = new ConsolePatcher({ |
|
|
debugMode: cliConfig?.getDebugMode() || !!process.env['DEBUG'], |
|
|
stderr: true, |
|
|
}); |
|
|
patcher.patch(); |
|
|
|
|
|
try { |
|
|
if (config.command === 'sandbox-exec') { |
|
|
|
|
|
if (process.env['BUILD_SANDBOX']) { |
|
|
throw new FatalSandboxError( |
|
|
'Cannot BUILD_SANDBOX when using macOS Seatbelt', |
|
|
); |
|
|
} |
|
|
|
|
|
const profile = (process.env['SEATBELT_PROFILE'] ??= 'permissive-open'); |
|
|
let profileFile = fileURLToPath( |
|
|
new URL(`sandbox-macos-${profile}.sb`, import.meta.url), |
|
|
); |
|
|
|
|
|
if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) { |
|
|
profileFile = path.join( |
|
|
SETTINGS_DIRECTORY_NAME, |
|
|
`sandbox-macos-${profile}.sb`, |
|
|
); |
|
|
} |
|
|
if (!fs.existsSync(profileFile)) { |
|
|
throw new FatalSandboxError( |
|
|
`Missing macos seatbelt profile file '${profileFile}'`, |
|
|
); |
|
|
} |
|
|
|
|
|
console.error(`using macos seatbelt (profile: ${profile}) ...`); |
|
|
|
|
|
const nodeOptions = [ |
|
|
...(process.env['DEBUG'] ? ['--inspect-brk'] : []), |
|
|
...nodeArgs, |
|
|
].join(' '); |
|
|
|
|
|
const args = [ |
|
|
'-D', |
|
|
`TARGET_DIR=${fs.realpathSync(process.cwd())}`, |
|
|
'-D', |
|
|
`TMP_DIR=${fs.realpathSync(os.tmpdir())}`, |
|
|
'-D', |
|
|
`HOME_DIR=${fs.realpathSync(os.homedir())}`, |
|
|
'-D', |
|
|
`CACHE_DIR=${fs.realpathSync(execSync(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`, |
|
|
]; |
|
|
|
|
|
|
|
|
|
|
|
const MAX_INCLUDE_DIRS = 5; |
|
|
const targetDir = fs.realpathSync(cliConfig?.getTargetDir() || ''); |
|
|
const includedDirs: string[] = []; |
|
|
|
|
|
if (cliConfig) { |
|
|
const workspaceContext = cliConfig.getWorkspaceContext(); |
|
|
const directories = workspaceContext.getDirectories(); |
|
|
|
|
|
|
|
|
for (const dir of directories) { |
|
|
const realDir = fs.realpathSync(dir); |
|
|
if (realDir !== targetDir) { |
|
|
includedDirs.push(realDir); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
for (let i = 0; i < MAX_INCLUDE_DIRS; i++) { |
|
|
let dirPath = '/dev/null'; |
|
|
|
|
|
if (i < includedDirs.length) { |
|
|
dirPath = includedDirs[i]; |
|
|
} |
|
|
|
|
|
args.push('-D', `INCLUDE_DIR_${i}=${dirPath}`); |
|
|
} |
|
|
|
|
|
const finalArgv = cliArgs; |
|
|
|
|
|
args.push( |
|
|
'-f', |
|
|
profileFile, |
|
|
'sh', |
|
|
'-c', |
|
|
[ |
|
|
`SANDBOX=sandbox-exec`, |
|
|
`NODE_OPTIONS="${nodeOptions}"`, |
|
|
...finalArgv.map((arg) => quote([arg])), |
|
|
].join(' '), |
|
|
); |
|
|
|
|
|
const proxyCommand = process.env['GEMINI_SANDBOX_PROXY_COMMAND']; |
|
|
let proxyProcess: ChildProcess | undefined = undefined; |
|
|
let sandboxProcess: ChildProcess | undefined = undefined; |
|
|
const sandboxEnv = { ...process.env }; |
|
|
if (proxyCommand) { |
|
|
const proxy = |
|
|
process.env['HTTPS_PROXY'] || |
|
|
process.env['https_proxy'] || |
|
|
process.env['HTTP_PROXY'] || |
|
|
process.env['http_proxy'] || |
|
|
'http://localhost:8877'; |
|
|
sandboxEnv['HTTPS_PROXY'] = proxy; |
|
|
sandboxEnv['https_proxy'] = proxy; |
|
|
sandboxEnv['HTTP_PROXY'] = proxy; |
|
|
sandboxEnv['http_proxy'] = proxy; |
|
|
const noProxy = process.env['NO_PROXY'] || process.env['no_proxy']; |
|
|
if (noProxy) { |
|
|
sandboxEnv['NO_PROXY'] = noProxy; |
|
|
sandboxEnv['no_proxy'] = noProxy; |
|
|
} |
|
|
proxyProcess = spawn(proxyCommand, { |
|
|
stdio: ['ignore', 'pipe', 'pipe'], |
|
|
shell: true, |
|
|
detached: true, |
|
|
}); |
|
|
|
|
|
const stopProxy = () => { |
|
|
console.log('stopping proxy ...'); |
|
|
if (proxyProcess?.pid) { |
|
|
process.kill(-proxyProcess.pid, 'SIGTERM'); |
|
|
} |
|
|
}; |
|
|
process.on('exit', stopProxy); |
|
|
process.on('SIGINT', stopProxy); |
|
|
process.on('SIGTERM', stopProxy); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
proxyProcess.stderr?.on('data', (data) => { |
|
|
console.error(data.toString()); |
|
|
}); |
|
|
proxyProcess.on('close', (code, signal) => { |
|
|
if (sandboxProcess?.pid) { |
|
|
process.kill(-sandboxProcess.pid, 'SIGTERM'); |
|
|
} |
|
|
throw new FatalSandboxError( |
|
|
`Proxy command '${proxyCommand}' exited with code ${code}, signal ${signal}`, |
|
|
); |
|
|
}); |
|
|
console.log('waiting for proxy to start ...'); |
|
|
await execAsync( |
|
|
`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`, |
|
|
); |
|
|
} |
|
|
|
|
|
sandboxProcess = spawn(config.command, args, { |
|
|
stdio: 'inherit', |
|
|
}); |
|
|
await new Promise((resolve) => sandboxProcess?.on('close', resolve)); |
|
|
return; |
|
|
} |
|
|
|
|
|
console.error(`hopping into sandbox (command: ${config.command}) ...`); |
|
|
|
|
|
|
|
|
const gcPath = fs.realpathSync(process.argv[1]); |
|
|
|
|
|
const projectSandboxDockerfile = path.join( |
|
|
SETTINGS_DIRECTORY_NAME, |
|
|
'sandbox.Dockerfile', |
|
|
); |
|
|
const isCustomProjectSandbox = fs.existsSync(projectSandboxDockerfile); |
|
|
|
|
|
const image = config.image; |
|
|
const workdir = path.resolve(process.cwd()); |
|
|
const containerWorkdir = getContainerPath(workdir); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (process.env['BUILD_SANDBOX']) { |
|
|
if (!gcPath.includes('gemini-cli/packages/')) { |
|
|
throw new FatalSandboxError( |
|
|
'Cannot build sandbox using installed gemini binary; ' + |
|
|
'run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary.', |
|
|
); |
|
|
} else { |
|
|
console.error('building sandbox ...'); |
|
|
const gcRoot = gcPath.split('/packages/')[0]; |
|
|
|
|
|
let buildArgs = ''; |
|
|
const projectSandboxDockerfile = path.join( |
|
|
SETTINGS_DIRECTORY_NAME, |
|
|
'sandbox.Dockerfile', |
|
|
); |
|
|
if (isCustomProjectSandbox) { |
|
|
console.error(`using ${projectSandboxDockerfile} for sandbox`); |
|
|
buildArgs += `-f ${path.resolve(projectSandboxDockerfile)} -i ${image}`; |
|
|
} |
|
|
execSync( |
|
|
`cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`, |
|
|
{ |
|
|
stdio: 'inherit', |
|
|
env: { |
|
|
...process.env, |
|
|
GEMINI_SANDBOX: config.command, |
|
|
}, |
|
|
}, |
|
|
); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
if (!(await ensureSandboxImageIsPresent(config.command, image))) { |
|
|
const remedy = |
|
|
image === LOCAL_DEV_SANDBOX_IMAGE_NAME |
|
|
? '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.' |
|
|
: 'Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists.'; |
|
|
throw new FatalSandboxError( |
|
|
`Sandbox image '${image}' is missing or could not be pulled. ${remedy}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const args = ['run', '-i', '--rm', '--init', '--workdir', containerWorkdir]; |
|
|
|
|
|
|
|
|
if (process.env['SANDBOX_FLAGS']) { |
|
|
const flags = parse(process.env['SANDBOX_FLAGS'], process.env).filter( |
|
|
(f): f is string => typeof f === 'string', |
|
|
); |
|
|
args.push(...flags); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.stdin.isTTY) { |
|
|
args.push('-t'); |
|
|
} |
|
|
|
|
|
|
|
|
args.push('--volume', `${workdir}:${containerWorkdir}`); |
|
|
|
|
|
|
|
|
|
|
|
const userSettingsDirOnHost = USER_SETTINGS_DIR; |
|
|
const userSettingsDirInSandbox = getContainerPath( |
|
|
`/home/node/${SETTINGS_DIRECTORY_NAME}`, |
|
|
); |
|
|
if (!fs.existsSync(userSettingsDirOnHost)) { |
|
|
fs.mkdirSync(userSettingsDirOnHost); |
|
|
} |
|
|
args.push( |
|
|
'--volume', |
|
|
`${userSettingsDirOnHost}:${userSettingsDirInSandbox}`, |
|
|
); |
|
|
if (userSettingsDirInSandbox !== userSettingsDirOnHost) { |
|
|
args.push( |
|
|
'--volume', |
|
|
`${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
args.push('--volume', `${os.tmpdir()}:${getContainerPath(os.tmpdir())}`); |
|
|
|
|
|
|
|
|
const gcloudConfigDir = path.join(os.homedir(), '.config', 'gcloud'); |
|
|
if (fs.existsSync(gcloudConfigDir)) { |
|
|
args.push( |
|
|
'--volume', |
|
|
`${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['GOOGLE_APPLICATION_CREDENTIALS']) { |
|
|
const adcFile = process.env['GOOGLE_APPLICATION_CREDENTIALS']; |
|
|
if (fs.existsSync(adcFile)) { |
|
|
args.push('--volume', `${adcFile}:${getContainerPath(adcFile)}:ro`); |
|
|
args.push( |
|
|
'--env', |
|
|
`GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`, |
|
|
); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['SANDBOX_MOUNTS']) { |
|
|
for (let mount of process.env['SANDBOX_MOUNTS'].split(',')) { |
|
|
if (mount.trim()) { |
|
|
|
|
|
let [from, to, opts] = mount.trim().split(':'); |
|
|
to = to || from; |
|
|
opts = opts || 'ro'; |
|
|
mount = `${from}:${to}:${opts}`; |
|
|
|
|
|
if (!path.isAbsolute(from)) { |
|
|
throw new FatalSandboxError( |
|
|
`Path '${from}' listed in SANDBOX_MOUNTS must be absolute`, |
|
|
); |
|
|
} |
|
|
|
|
|
if (!fs.existsSync(from)) { |
|
|
throw new FatalSandboxError( |
|
|
`Missing mount path '${from}' listed in SANDBOX_MOUNTS`, |
|
|
); |
|
|
} |
|
|
console.error(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`); |
|
|
args.push('--volume', mount); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
ports().forEach((p) => args.push('--publish', `${p}:${p}`)); |
|
|
|
|
|
|
|
|
if (process.env['DEBUG']) { |
|
|
const debugPort = process.env['DEBUG_PORT'] || '9229'; |
|
|
args.push(`--publish`, `${debugPort}:${debugPort}`); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const proxyCommand = process.env['GEMINI_SANDBOX_PROXY_COMMAND']; |
|
|
|
|
|
if (proxyCommand) { |
|
|
let proxy = |
|
|
process.env['HTTPS_PROXY'] || |
|
|
process.env['https_proxy'] || |
|
|
process.env['HTTP_PROXY'] || |
|
|
process.env['http_proxy'] || |
|
|
'http://localhost:8877'; |
|
|
proxy = proxy.replace('localhost', SANDBOX_PROXY_NAME); |
|
|
if (proxy) { |
|
|
args.push('--env', `HTTPS_PROXY=${proxy}`); |
|
|
args.push('--env', `https_proxy=${proxy}`); |
|
|
args.push('--env', `HTTP_PROXY=${proxy}`); |
|
|
args.push('--env', `http_proxy=${proxy}`); |
|
|
} |
|
|
const noProxy = process.env['NO_PROXY'] || process.env['no_proxy']; |
|
|
if (noProxy) { |
|
|
args.push('--env', `NO_PROXY=${noProxy}`); |
|
|
args.push('--env', `no_proxy=${noProxy}`); |
|
|
} |
|
|
|
|
|
|
|
|
if (proxy) { |
|
|
execSync( |
|
|
`${config.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config.command} network create --internal ${SANDBOX_NETWORK_NAME}`, |
|
|
); |
|
|
args.push('--network', SANDBOX_NETWORK_NAME); |
|
|
|
|
|
|
|
|
|
|
|
if (proxyCommand) { |
|
|
execSync( |
|
|
`${config.command} network inspect ${SANDBOX_PROXY_NAME} || ${config.command} network create ${SANDBOX_PROXY_NAME}`, |
|
|
); |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
const imageName = parseImageName(image); |
|
|
let index = 0; |
|
|
const containerNameCheck = execSync( |
|
|
`${config.command} ps -a --format "{{.Names}}"`, |
|
|
) |
|
|
.toString() |
|
|
.trim(); |
|
|
while (containerNameCheck.includes(`${imageName}-${index}`)) { |
|
|
index++; |
|
|
} |
|
|
const containerName = `${imageName}-${index}`; |
|
|
args.push('--name', containerName, '--hostname', containerName); |
|
|
|
|
|
|
|
|
if (process.env['GEMINI_API_KEY']) { |
|
|
args.push('--env', `GEMINI_API_KEY=${process.env['GEMINI_API_KEY']}`); |
|
|
} |
|
|
if (process.env['GOOGLE_API_KEY']) { |
|
|
args.push('--env', `GOOGLE_API_KEY=${process.env['GOOGLE_API_KEY']}`); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['GOOGLE_GENAI_USE_VERTEXAI']) { |
|
|
args.push( |
|
|
'--env', |
|
|
`GOOGLE_GENAI_USE_VERTEXAI=${process.env['GOOGLE_GENAI_USE_VERTEXAI']}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['GOOGLE_GENAI_USE_GCA']) { |
|
|
args.push( |
|
|
'--env', |
|
|
`GOOGLE_GENAI_USE_GCA=${process.env['GOOGLE_GENAI_USE_GCA']}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['GOOGLE_CLOUD_PROJECT']) { |
|
|
args.push( |
|
|
'--env', |
|
|
`GOOGLE_CLOUD_PROJECT=${process.env['GOOGLE_CLOUD_PROJECT']}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['GOOGLE_CLOUD_LOCATION']) { |
|
|
args.push( |
|
|
'--env', |
|
|
`GOOGLE_CLOUD_LOCATION=${process.env['GOOGLE_CLOUD_LOCATION']}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['GEMINI_MODEL']) { |
|
|
args.push('--env', `GEMINI_MODEL=${process.env['GEMINI_MODEL']}`); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['TERM']) { |
|
|
args.push('--env', `TERM=${process.env['TERM']}`); |
|
|
} |
|
|
if (process.env['COLORTERM']) { |
|
|
args.push('--env', `COLORTERM=${process.env['COLORTERM']}`); |
|
|
} |
|
|
|
|
|
|
|
|
for (const envVar of [ |
|
|
'GEMINI_CLI_IDE_SERVER_PORT', |
|
|
'GEMINI_CLI_IDE_WORKSPACE_PATH', |
|
|
'TERM_PROGRAM', |
|
|
]) { |
|
|
if (process.env[envVar]) { |
|
|
args.push('--env', `${envVar}=${process.env[envVar]}`); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if ( |
|
|
process.env['VIRTUAL_ENV'] |
|
|
?.toLowerCase() |
|
|
.startsWith(workdir.toLowerCase()) |
|
|
) { |
|
|
const sandboxVenvPath = path.resolve( |
|
|
SETTINGS_DIRECTORY_NAME, |
|
|
'sandbox.venv', |
|
|
); |
|
|
if (!fs.existsSync(sandboxVenvPath)) { |
|
|
fs.mkdirSync(sandboxVenvPath, { recursive: true }); |
|
|
} |
|
|
args.push( |
|
|
'--volume', |
|
|
`${sandboxVenvPath}:${getContainerPath(process.env['VIRTUAL_ENV'])}`, |
|
|
); |
|
|
args.push( |
|
|
'--env', |
|
|
`VIRTUAL_ENV=${getContainerPath(process.env['VIRTUAL_ENV'])}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
if (process.env['SANDBOX_ENV']) { |
|
|
for (let env of process.env['SANDBOX_ENV'].split(',')) { |
|
|
if ((env = env.trim())) { |
|
|
if (env.includes('=')) { |
|
|
console.error(`SANDBOX_ENV: ${env}`); |
|
|
args.push('--env', env); |
|
|
} else { |
|
|
throw new FatalSandboxError( |
|
|
'SANDBOX_ENV must be a comma-separated list of key=value pairs', |
|
|
); |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
const existingNodeOptions = process.env['NODE_OPTIONS'] || ''; |
|
|
const allNodeOptions = [ |
|
|
...(existingNodeOptions ? [existingNodeOptions] : []), |
|
|
...nodeArgs, |
|
|
].join(' '); |
|
|
|
|
|
if (allNodeOptions.length > 0) { |
|
|
args.push('--env', `NODE_OPTIONS="${allNodeOptions}"`); |
|
|
} |
|
|
|
|
|
|
|
|
args.push('--env', `SANDBOX=${containerName}`); |
|
|
|
|
|
|
|
|
if (config.command === 'podman') { |
|
|
const emptyAuthFilePath = path.join(os.tmpdir(), 'empty_auth.json'); |
|
|
fs.writeFileSync(emptyAuthFilePath, '{}', 'utf-8'); |
|
|
args.push('--authfile', emptyAuthFilePath); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
let userFlag = ''; |
|
|
const finalEntrypoint = entrypoint(workdir, cliArgs); |
|
|
|
|
|
if (process.env['GEMINI_CLI_INTEGRATION_TEST'] === 'true') { |
|
|
args.push('--user', 'root'); |
|
|
userFlag = '--user root'; |
|
|
} else if (await shouldUseCurrentUserInSandbox()) { |
|
|
|
|
|
|
|
|
args.push('--user', 'root'); |
|
|
|
|
|
const uid = execSync('id -u').toString().trim(); |
|
|
const gid = execSync('id -g').toString().trim(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const username = 'gemini'; |
|
|
const homeDir = getContainerPath(os.homedir()); |
|
|
|
|
|
const setupUserCommands = [ |
|
|
|
|
|
`groupadd -f -g ${gid} ${username}`, |
|
|
|
|
|
`id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`, |
|
|
].join(' && '); |
|
|
|
|
|
const originalCommand = finalEntrypoint[2]; |
|
|
const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''"); |
|
|
|
|
|
|
|
|
const suCommand = `su -p ${username} -c '${escapedOriginalCommand}'`; |
|
|
|
|
|
|
|
|
finalEntrypoint[2] = `${setupUserCommands} && ${suCommand}`; |
|
|
|
|
|
|
|
|
userFlag = `--user ${uid}:${gid}`; |
|
|
|
|
|
args.push('--env', `HOME=${os.homedir()}`); |
|
|
} |
|
|
|
|
|
|
|
|
args.push(image); |
|
|
|
|
|
|
|
|
args.push(...finalEntrypoint); |
|
|
|
|
|
|
|
|
let proxyProcess: ChildProcess | undefined = undefined; |
|
|
let sandboxProcess: ChildProcess | undefined = undefined; |
|
|
|
|
|
if (proxyCommand) { |
|
|
|
|
|
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}`; |
|
|
proxyProcess = spawn(proxyContainerCommand, { |
|
|
stdio: ['ignore', 'pipe', 'pipe'], |
|
|
shell: true, |
|
|
detached: true, |
|
|
}); |
|
|
|
|
|
const stopProxy = () => { |
|
|
console.log('stopping proxy container ...'); |
|
|
execSync(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`); |
|
|
}; |
|
|
process.on('exit', stopProxy); |
|
|
process.on('SIGINT', stopProxy); |
|
|
process.on('SIGTERM', stopProxy); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
proxyProcess.stderr?.on('data', (data) => { |
|
|
console.error(data.toString().trim()); |
|
|
}); |
|
|
proxyProcess.on('close', (code, signal) => { |
|
|
if (sandboxProcess?.pid) { |
|
|
process.kill(-sandboxProcess.pid, 'SIGTERM'); |
|
|
} |
|
|
throw new FatalSandboxError( |
|
|
`Proxy container command '${proxyContainerCommand}' exited with code ${code}, signal ${signal}`, |
|
|
); |
|
|
}); |
|
|
console.log('waiting for proxy to start ...'); |
|
|
await execAsync( |
|
|
`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`, |
|
|
); |
|
|
|
|
|
|
|
|
await execAsync( |
|
|
`${config.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`, |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
sandboxProcess = spawn(config.command, args, { |
|
|
stdio: 'inherit', |
|
|
}); |
|
|
|
|
|
sandboxProcess.on('error', (err) => { |
|
|
console.error('Sandbox process error:', err); |
|
|
}); |
|
|
|
|
|
await new Promise<void>((resolve) => { |
|
|
sandboxProcess?.on('close', (code, signal) => { |
|
|
if (code !== 0) { |
|
|
console.log( |
|
|
`Sandbox process exited with code: ${code}, signal: ${signal}`, |
|
|
); |
|
|
} |
|
|
resolve(); |
|
|
}); |
|
|
}); |
|
|
} finally { |
|
|
patcher.cleanup(); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
async function imageExists(sandbox: string, image: string): Promise<boolean> { |
|
|
return new Promise((resolve) => { |
|
|
const args = ['images', '-q', image]; |
|
|
const checkProcess = spawn(sandbox, args); |
|
|
|
|
|
let stdoutData = ''; |
|
|
if (checkProcess.stdout) { |
|
|
checkProcess.stdout.on('data', (data) => { |
|
|
stdoutData += data.toString(); |
|
|
}); |
|
|
} |
|
|
|
|
|
checkProcess.on('error', (err) => { |
|
|
console.warn( |
|
|
`Failed to start '${sandbox}' command for image check: ${err.message}`, |
|
|
); |
|
|
resolve(false); |
|
|
}); |
|
|
|
|
|
checkProcess.on('close', (code) => { |
|
|
|
|
|
|
|
|
if (code !== 0) { |
|
|
|
|
|
} |
|
|
resolve(stdoutData.trim() !== ''); |
|
|
}); |
|
|
}); |
|
|
} |
|
|
|
|
|
async function pullImage(sandbox: string, image: string): Promise<boolean> { |
|
|
console.info(`Attempting to pull image ${image} using ${sandbox}...`); |
|
|
return new Promise((resolve) => { |
|
|
const args = ['pull', image]; |
|
|
const pullProcess = spawn(sandbox, args, { stdio: 'pipe' }); |
|
|
|
|
|
let stderrData = ''; |
|
|
|
|
|
const onStdoutData = (data: Buffer) => { |
|
|
console.info(data.toString().trim()); |
|
|
}; |
|
|
|
|
|
const onStderrData = (data: Buffer) => { |
|
|
stderrData += data.toString(); |
|
|
console.error(data.toString().trim()); |
|
|
}; |
|
|
|
|
|
const onError = (err: Error) => { |
|
|
console.warn( |
|
|
`Failed to start '${sandbox} pull ${image}' command: ${err.message}`, |
|
|
); |
|
|
cleanup(); |
|
|
resolve(false); |
|
|
}; |
|
|
|
|
|
const onClose = (code: number | null) => { |
|
|
if (code === 0) { |
|
|
console.info(`Successfully pulled image ${image}.`); |
|
|
cleanup(); |
|
|
resolve(true); |
|
|
} else { |
|
|
console.warn( |
|
|
`Failed to pull image ${image}. '${sandbox} pull ${image}' exited with code ${code}.`, |
|
|
); |
|
|
if (stderrData.trim()) { |
|
|
|
|
|
} |
|
|
cleanup(); |
|
|
resolve(false); |
|
|
} |
|
|
}; |
|
|
|
|
|
const cleanup = () => { |
|
|
if (pullProcess.stdout) { |
|
|
pullProcess.stdout.removeListener('data', onStdoutData); |
|
|
} |
|
|
if (pullProcess.stderr) { |
|
|
pullProcess.stderr.removeListener('data', onStderrData); |
|
|
} |
|
|
pullProcess.removeListener('error', onError); |
|
|
pullProcess.removeListener('close', onClose); |
|
|
if (pullProcess.connected) { |
|
|
pullProcess.disconnect(); |
|
|
} |
|
|
}; |
|
|
|
|
|
if (pullProcess.stdout) { |
|
|
pullProcess.stdout.on('data', onStdoutData); |
|
|
} |
|
|
if (pullProcess.stderr) { |
|
|
pullProcess.stderr.on('data', onStderrData); |
|
|
} |
|
|
pullProcess.on('error', onError); |
|
|
pullProcess.on('close', onClose); |
|
|
}); |
|
|
} |
|
|
|
|
|
async function ensureSandboxImageIsPresent( |
|
|
sandbox: string, |
|
|
image: string, |
|
|
): Promise<boolean> { |
|
|
console.info(`Checking for sandbox image: ${image}`); |
|
|
if (await imageExists(sandbox, image)) { |
|
|
console.info(`Sandbox image ${image} found locally.`); |
|
|
return true; |
|
|
} |
|
|
|
|
|
console.info(`Sandbox image ${image} not found locally.`); |
|
|
if (image === LOCAL_DEV_SANDBOX_IMAGE_NAME) { |
|
|
|
|
|
return false; |
|
|
} |
|
|
|
|
|
if (await pullImage(sandbox, image)) { |
|
|
|
|
|
if (await imageExists(sandbox, image)) { |
|
|
console.info(`Sandbox image ${image} is now available after pulling.`); |
|
|
return true; |
|
|
} else { |
|
|
console.warn( |
|
|
`Sandbox image ${image} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`, |
|
|
); |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
console.error( |
|
|
`Failed to obtain sandbox image ${image} after check and pull attempt.`, |
|
|
); |
|
|
return false; |
|
|
} |
|
|
|