refactor(core): Improve environment variable handling in shell execution (#14742)

Co-authored-by: Jack Wotherspoon <jackwoth@google.com>
Co-authored-by: christine betts <chrstn@uw.edu>
This commit is contained in:
Gal Zahavi
2025-12-08 16:22:46 -08:00
committed by GitHub
parent ec9a8c7a72
commit 171103aedc
2 changed files with 230 additions and 3 deletions
@@ -148,6 +148,58 @@ const getFullBufferText = (terminal: pkg.Terminal): string => {
return lines.join('\n');
};
function getSanitizedEnv(): NodeJS.ProcessEnv {
const isRunningInGithub =
process.env['GITHUB_SHA'] || process.env['SURFACE'] === 'Github';
if (!isRunningInGithub) {
// For local runs, we want to preserve the user's full environment.
return { ...process.env };
}
// For CI runs (GitHub), we sanitize the environment for security.
const env: NodeJS.ProcessEnv = {};
const essentialVars = [
// Cross-platform
'PATH',
// Windows specific
'Path',
'SYSTEMROOT',
'SystemRoot',
'COMSPEC',
'ComSpec',
'PATHEXT',
'WINDIR',
'TEMP',
'TMP',
'USERPROFILE',
'SYSTEMDRIVE',
'SystemDrive',
// Unix/Linux/macOS specific
'HOME',
'LANG',
'SHELL',
'TMPDIR',
'USER',
'LOGNAME',
];
for (const key of essentialVars) {
if (process.env[key] !== undefined) {
env[key] = process.env[key];
}
}
// Always carry over test-specific variables for our own integration tests.
for (const key in process.env) {
if (key.startsWith('GEMINI_CLI_TEST')) {
env[key] = process.env[key];
}
}
return env;
}
/**
* A centralized service for executing shell commands with robust process
* management, cross-platform compatibility, and streaming output capabilities.
@@ -249,7 +301,7 @@ export class ShellExecutionService {
shell: false,
detached: !isWindows,
env: {
...process.env,
...getSanitizedEnv(),
GEMINI_CLI: '1',
TERM: 'xterm-256color',
PAGER: 'cat',
@@ -463,7 +515,7 @@ export class ShellExecutionService {
cols,
rows,
env: {
...process.env,
...getSanitizedEnv(),
GEMINI_CLI: '1',
TERM: 'xterm-256color',
PAGER: shellExecutionConfig.pager ?? 'cat',