Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cli/src/commands/agent_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ async fn run_supervisor(mut ctx: CommandContext, mut args: AgentHostArgs) -> Res
without_connection_token: true,
connection_token: None,
connection_token_file: None,
client_forwarding: args.client_forwarding,
},
// The backend counts as activity while it runs, so the idle timeout
// can't kill agent sessions that are still working after the last
Expand Down
18 changes: 15 additions & 3 deletions cli/src/commands/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,13 +295,20 @@ pub struct AgentHostArgs {
#[clap(long)]
pub foreground: bool,

/// Forward what clients offer, such as their Git credentials and SSH and
/// GPG agents, to the processes the agent host starts. Used by the Dev
/// Container launcher.
#[clap(long, hide = true)]
pub client_forwarding: bool,

/// Alias for `code tunnel`: expose remote editor and agent host access.
#[clap(
long,
group = "remote_host",
conflicts_with_all = [
"host", "port", "connection_token", "connection_token_file",
"without_connection_token", "replace", "new_instance", "foreground", "idle_timeout"
"without_connection_token", "replace", "new_instance", "foreground", "idle_timeout",
"client_forwarding"
]
)]
pub tunnel: bool,
Expand All @@ -313,7 +320,7 @@ pub struct AgentHostArgs {
conflicts_with_all = [
"host", "port", "connection_token", "connection_token_file",
"without_connection_token", "replace", "new_instance", "idle_timeout",
"random_name", "tunnel_id", "host_token", "cluster", "tunnel_name"
"random_name", "tunnel_id", "host_token", "cluster", "tunnel_name", "client_forwarding"
]
)]
pub github_environment: bool,
Expand Down Expand Up @@ -1324,6 +1331,7 @@ mod tests {
vec!["--host-token", "token"],
vec!["--cluster", "cluster"],
vec!["--tunnel-name", "name"],
vec!["--client-forwarding"],
] {
let mut argv = command.clone();
argv.push("--github-environment");
Expand Down Expand Up @@ -1434,6 +1442,7 @@ mod tests {
vec!["--new-instance"],
vec!["--foreground"],
vec!["--idle-timeout", "300"],
vec!["--client-forwarding"],
] {
let mut argv = command.clone();
argv.push("--tunnel");
Expand Down Expand Up @@ -1463,6 +1472,7 @@ mod tests {
"--foreground",
"--idle-timeout",
"300",
"--client-forwarding",
]);
let args = parse_agent_host_args(&argv);
assert_eq!(
Expand All @@ -1475,6 +1485,7 @@ mod tests {
args.new_instance,
args.foreground,
args.idle_timeout,
args.client_forwarding,
),
(
false,
Expand All @@ -1484,7 +1495,8 @@ mod tests {
true,
true,
true,
Some(300)
Some(300),
true
)
);
}
Expand Down
37 changes: 37 additions & 0 deletions cli/src/tunnels/agent_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ pub const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
/// CLI and may therefore advertise the management RPC method to clients.
pub const MANAGEMENT_SOCKET_ENV: &str = "VSCODE_AGENT_HOST_MANAGEMENT_SOCKET";
const GITHUB_ENVIRONMENT_OPTIONS_ENV: &str = "VSCODE_CLI_GITHUB_ENVIRONMENT_OPTIONS";
/// Set to `1` for the server of an agent host started with
/// `--client-forwarding`, and removed otherwise, so only the flag turns
/// forwarding on. Read and removed by the agent host the server starts.
const AGENT_HOST_CLIENT_FORWARDING_ENV: &str = "VSCODE_AGENT_HOST_CLIENT_FORWARDING";
const GITHUB_ENVIRONMENT_READY_PREFIX: &str = "__VSCODE_GITHUB_ENVIRONMENT_READY__:";

#[derive(Clone, Serialize)]
Expand Down Expand Up @@ -130,6 +134,9 @@ pub struct AgentHostConfig {
pub without_connection_token: bool,
pub connection_token: Option<String>,
pub connection_token_file: Option<String>,
/// Whether the agent host forwards what clients offer to the processes
/// it starts, see `code agent host --client-forwarding`.
pub client_forwarding: bool,
}

/// State of the running VS Code server process. The process itself is
Expand Down Expand Up @@ -353,6 +360,11 @@ impl AgentHostManager {
cmd.arg("--connection-token-file");
cmd.arg(ct);
}
if self.config.client_forwarding {
cmd.env(AGENT_HOST_CLIENT_FORWARDING_ENV, "1");
} else {
cmd.env_remove(AGENT_HOST_CLIENT_FORWARDING_ENV);
}
cmd.env(MANAGEMENT_SOCKET_ENV, &self.management_socket_path);
cmd.env_remove("VSCODE_DEV");

Expand Down Expand Up @@ -2388,6 +2400,7 @@ mod tests {
without_connection_token: true,
connection_token: None,
connection_token_file: None,
client_forwarding: false,
},
activity,
)
Expand Down Expand Up @@ -2467,6 +2480,30 @@ mod tests {
assert!(!argv.contains("--user-data-dir\n"));
}

#[cfg(unix)]
#[tokio::test]
async fn client_forwarding_reaches_only_the_server_of_a_forwarding_agent_host() {
let mut seen = Vec::new();
for client_forwarding in [true, false] {
let dir = tempfile::tempdir().unwrap();
let mut manager = make_test_manager(dir.path());
Arc::get_mut(&mut manager).unwrap().config.client_forwarding = client_forwarding;
let env = dir.path().join("env");
let server = start_fake_server(
&manager,
dir.path(),
&format!(
"printf '%s' \"${{{AGENT_HOST_CLIENT_FORWARDING_ENV}-unset}}\" > '{}'",
env.display()
),
)
.await;
server.await.unwrap();
seen.push(std::fs::read_to_string(env).unwrap());
}
assert_eq!(seen, ["1", "unset"]);
}

#[cfg(unix)]
#[tokio::test]
async fn github_environment_waits_for_remote_readiness_and_forwards_bootstrap() {
Expand Down
10 changes: 10 additions & 0 deletions src/vs/platform/agentHost/common/agentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ export interface IAgentHostIpcConnectionOptions {
readonly env?: Readonly<Record<string, string | null>>;
/** Kept separate so the server can apply resolver precedence using its own environment casing. */
readonly debugEnv?: Readonly<Record<string, string | null>>;
/** Asks a server to start its agent host with {@link AgentHostClientForwardingEnvVar}. */
readonly clientForwarding?: boolean;
}

/** Configuration key that controls whether AHP JSONL logs are written for agent host transports. */
Expand Down Expand Up @@ -284,6 +286,14 @@ export const AgentHostSessionReleaseRetryMsEnvVar = 'VSCODE_AGENT_HOST_SESSION_R
/** Overrides how long a changeset read waits for the file snapshots of a running Codex turn. Primarily used by integration tests. */
export const AgentHostCodexTurnEditsWaitMsEnvVar = 'VSCODE_AGENT_HOST_CODEX_TURN_EDITS_WAIT_MS';

/**
* Set to `1` to have the agent host forward what clients advertising `vscode.clientForwarding` offer to the processes
* it starts. The VS Code CLI sets it for the server of `code agent host --client-forwarding`, as the Dev Container
* launcher starts it, and a server for the agent host it starts when an editor window asks for it with
* {@link IAgentHostIpcConnectionOptions.clientForwarding}. The agent host removes it from its environment.
*/
export const AgentHostClientForwardingEnvVar = 'VSCODE_AGENT_HOST_CLIENT_FORWARDING';

/**
* Resolves the effective enable state for a Claude/Codex provider from the
* env-var value forwarded by the starter. Recognized values (case- and
Expand Down
10 changes: 4 additions & 6 deletions src/vs/platform/agentHost/node/agentHostClientForwarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { createDecorator } from '../../instantiation/common/instantiation.js';
import { ILogService } from '../../log/common/log.js';
import { ITelemetryService } from '../../telemetry/common/telemetry.js';
import { clientGitCredentialOperationValidator, type ClientForwardingDescription, type ClientForwardingSocket, type ClientGitConfig, type ClientGitCredentialOperation, type ClientGpgKeys } from '../common/clientForwardingProtocol.js';
import { AgentHostClientForwardingEnvVar } from '../common/agentService.js';
import { ClientForwardingTelemetry, getClientForwardingSetup, getGitCredentialOutcome, type ClientForwardingGitConfigSetup, type ClientForwardingGitIdentitySetup, type ClientForwardingSocketOutcome, type IClientForwardingSetupState } from './agentHostClientForwardingTelemetry.js';
import { parseGpgDirs, useKeyboxdPattern } from './clientForwardingHost.js';
import { applyClientGitConfig, IClientGitConfigTarget } from './clientGitConfig.js';
Expand All @@ -30,9 +31,6 @@ import { SessionConfigKey } from '../common/sessionConfigKeys.js';
import { ActionType } from '../common/state/sessionActions.js';
import { shellEscape } from './sshRemoteAgentHostHelpers.js';

/** Set to `1` by a launcher, e.g., for Dev Containers, to have the agent host forward what its clients offer. */
export const AGENT_HOST_CLIENT_FORWARDING_ENV = 'VSCODE_AGENT_HOST_CLIENT_FORWARDING';

export const IAgentHostClientForwardingService = createDecorator<IAgentHostClientForwardingService>('agentHostClientForwardingService');

/**
Expand All @@ -42,7 +40,7 @@ export const IAgentHostClientForwardingService = createDecorator<IAgentHostClien
*/
export interface IAgentHostClientForwardingService {
readonly _serviceBrand: undefined;
/** Whether the agent host was started to forward its clients', see {@link AGENT_HOST_CLIENT_FORWARDING_ENV}. */
/** Whether the agent host was started to forward its clients', see {@link AgentHostClientForwardingEnvVar}. */
readonly enabled: boolean;
/** Serves the client's forwarding until disposed; the newest client offering something serves it. */
registerClient(client: IAgentHostForwardingClient): IDisposable;
Expand Down Expand Up @@ -181,9 +179,9 @@ export class AgentHostClientForwardingService extends Disposable implements IAge
) {
super();
this._telemetry = new ClientForwardingTelemetry(telemetryService, _logService);
this.enabled = _environment[AGENT_HOST_CLIENT_FORWARDING_ENV] === '1';
this.enabled = _environment[AgentHostClientForwardingEnvVar] === '1';
// Not for the processes this agent host starts.
delete _environment[AGENT_HOST_CLIENT_FORWARDING_ENV];
delete _environment[AgentHostClientForwardingEnvVar];
this._originalSshAgentSocket = _environment.SSH_AUTH_SOCK;
this._register(toDisposable(() => {
for (const connection of this._connections.values()) {
Expand Down
46 changes: 26 additions & 20 deletions src/vs/platform/agentHost/node/devContainerAgentHostService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,26 +42,27 @@ import { getAppNodeModulesUri } from './appNodeModules.js';
import { toWslcCommand } from './devContainerEngine.js';
import { hasDevContainerEnvironmentVolume, IPreparedDevContainerEnvironment, prepareDevContainerEnvironment, readDevContainerEnvironmentTestConfiguration, removeDevContainerEnvironment } from './devContainerEnvironments.js';
import { checked, getDevContainerSampleVolumeLabel, IPreparedDevContainerSample, prepareDevContainerSample } from './devContainerSamples.js';
import { AGENT_HOST_CLIENT_FORWARDING_ENV } from './agentHostClientForwarding.js';
import { IDevContainerSandboxConfiguration, isDevContainerSandboxSupported, parseDevContainerSandboxConfiguration, prepareDevContainerSandboxConfiguration } from './devContainerSandbox.js';
import { buildCreateDevContainerCacheCommand, buildLinkDevContainerServerCacheCommand, canAddDevContainerServerCacheMount, devContainerServerCacheMount, getDevContainerCliCachePath, getDevContainerServerCachePath } from './devContainerServerCache.js';
import { DevContainerShell, IDevContainerShellResult } from './devContainerShell.js';
import { IDevContainerSecurityOptions, IDevContainerStateErrorValues, IDevContainerStateLinkProgress, buildLinkDevContainerStateCommand, devContainerStateIdLabel, findDevContainerStateMount, getDefaultDevContainerIdLabels, getDevContainerId, getDevContainerSecurityOptions, getDevContainerStateLinkSkippedMessage, getDevContainerStateMount, getDevContainerStateMountTarget, getDevContainerStateTargetKind, getDevContainerStateVolumeLabels, getDevContainerStateVolumeName, getDevContainerUpErrorCause, isDevContainerRunning, isDevContainerStateVolumeFor, parseLinkDevContainerStateOutput, sanitizeDevContainerStateErrorMessage } from './devContainerState.js';
import { prepareOwnerOnlyDirectory } from './localAgentHostMetadata.js';
import { ensureRemoteAgentHostCliInstalled } from './remoteAgentHostCliInstaller.js';
import {
AgentHostStartError,
COLD_AGENT_HOST_REGISTRATION_TIMEOUT_MS,
DETECT_MUSL_COMMAND,
ISshExec,
buildAgentHostSpawnCommand,
buildAgentRelayCommand,
cliVersionSupportsClientForwarding,
filterLiveAgentHostEndpoints,
formatAgentHostUrlHost,
getRemoteCLIDataDir,
resolveRemotePlatform,
runAgentEndpoints,
shellEscape,
waitForNewStandaloneEndpoint,
waitForStartedStandaloneEndpoint,
} from './sshRemoteAgentHostHelpers.js';

const LOG_PREFIX = '[DevContainerAgentHost]';
Expand Down Expand Up @@ -472,31 +473,36 @@ export abstract class DevContainerAgentHostService extends Disposable implements
const live = await filterLiveAgentHostEndpoints(exec, initial.endpoints);
let endpoint = selectAgentHostEndpoint(live, this._productService.quality, undefined);
if (!endpoint) {
const sessionId = this._telemetryService.sessionId;
// Lets the Agent Host forward the Git configuration, identity, credentials and agents of clients offering them.
const spawnCommand = `${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(sessionId)} ${AGENT_HOST_CLIENT_FORWARDING_ENV}=1 ${buildAgentHostSpawnCommand(
// The Agent Host keeps this command running, so it cannot share the startup shell.
const start = (forwarding: boolean) => this._createExec(config.connectionId, execSelector, tokenSource.token, sandboxEnvironment)(`${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(this._telemetryService.sessionId)} ${buildAgentHostSpawnCommand(
cliBin,
serverDataFolderName,
initial.userDataPath,
telemetryLevelToAgentHostValue(this._telemetryService.telemetryLevel),
)}`;
// The Agent Host keeps this command running, so it cannot share the startup shell.
void this._createExec(config.connectionId, execSelector, tokenSource.token, sandboxEnvironment)(spawnCommand, { ignoreExitCode: true }).catch(error => {
this._logService.warn(`${LOG_PREFIX} Agent Host spawn command failed`, error);
});
this._logService.info(`${LOG_PREFIX} Waiting for the new agent host to register...`);
endpoint = await waitForNewStandaloneEndpoint(
exec,
cliBin,
cliDataDir,
initial.userDataPath,
live,
{
{ clientForwarding: forwarding },
)}`, { ignoreExitCode: true });
const waitForRegistration = (started: ReturnType<typeof start>) => {
this._logService.info(`${LOG_PREFIX} Waiting for the new agent host to register...`);
return waitForStartedStandaloneEndpoint(started, exec, cliBin, cliDataDir, initial.userDataPath, live, {
timeoutMs: COLD_AGENT_HOST_REGISTRATION_TIMEOUT_MS,
token: tokenSource.token,
progress: elapsedMs => this._logService.info(`${LOG_PREFIX} Waiting for the new agent host to register... (${Math.floor(elapsedMs / 1000)} seconds elapsed)`),
},
);
});
};
// The client's own CLI and the latest one dev builds use have the option; an older fallback CLI does not.
const clientForwarding = cliInstallation.fallbackVersion === undefined || cliVersionSupportsClientForwarding(cliInstallation.fallbackVersion);
if (!clientForwarding) {
this._logService.warn(`${LOG_PREFIX} Fallback CLI ${cliInstallation.fallbackVersion} cannot start an Agent Host that forwards Git credentials and agents`);
}
try {
endpoint = await waitForRegistration(start(clientForwarding));
} catch (error) {
if (!clientForwarding || !(error instanceof AgentHostStartError) || !error.rejectsClientForwarding) {
throw error;
}
this._logService.warn(`${LOG_PREFIX} The CLI does not support --client-forwarding; starting an Agent Host that does not forward Git credentials and agents`);
endpoint = await waitForRegistration(start(false));
}
}

const relayCommand = `${VSCODE_REMOTE_CONTAINERS_SESSION_ENV}=${shellEscape(this._telemetryService.sessionId)} ${buildAgentRelayCommand(cliBin, cliDataDir, endpoint.instanceId, initial.userDataPath)}`;
Expand Down
12 changes: 7 additions & 5 deletions src/vs/platform/agentHost/node/remoteAgentHostCliInstaller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export interface IRemoteAgentHostCliInstallOptions {
export interface IRemoteAgentHostCliInstallResult {
readonly cliBin: string;
readonly installed: boolean;
/** The `--version` output of a fallback CLI, which is not built from the client's commit. */
readonly fallbackVersion?: string;
}

/**
Expand Down Expand Up @@ -116,8 +118,8 @@ async function ensurePinnedCliInstalled(
options.logService.warn(`${logPrefix} Could not install matching CLI for commit ${commit}: ${message}. Looking for a fallback CLI...`);
const fallback = await findFallbackCli(exec, options);
if (fallback) {
options.logService.warn(`${logPrefix} Using fallback CLI at ${fallback} (does not match desktop commit ${commit}).`);
return { cliBin: fallback, installed: false };
options.logService.warn(`${logPrefix} Using fallback CLI at ${fallback.cliBin} (${fallback.version}, does not match desktop commit ${commit}).`);
return { cliBin: fallback.cliBin, installed: false, fallbackVersion: fallback.version };
}
throw error;
}
Expand Down Expand Up @@ -156,7 +158,7 @@ async function ensureLooseCliInstalled(
return { cliBin, installed: true };
}

async function findFallbackCli(exec: ISshExec, options: IRemoteAgentHostCliInstallOptions): Promise<string | undefined> {
async function findFallbackCli(exec: ISshExec, options: IRemoteAgentHostCliInstallOptions): Promise<{ readonly cliBin: string; readonly version: string } | undefined> {
const logPrefix = options.logPrefix ?? '[RemoteAgentHostCliInstaller]';
const { stdout } = await exec(buildFindFallbackCLICommand(options.serverDataFolderName, options.quality), { ignoreExitCode: true });
const rawCandidates = stdout.split('\n').map(candidate => candidate.trim()).filter(candidate => candidate.length > 0);
Expand All @@ -165,9 +167,9 @@ async function findFallbackCli(exec: ISshExec, options: IRemoteAgentHostCliInsta
options.logService.info(`${logPrefix} Ignoring fallback CLI candidate with unexpected path shape: ${candidate}`);
continue;
}
const { code } = await exec(`${candidate} --version`, { ignoreExitCode: true });
const { code, stdout: version } = await exec(`${candidate} --version`, { ignoreExitCode: true });
if (code === 0) {
return candidate;
return { cliBin: candidate, version: version.trim() };
}
options.logService.info(`${logPrefix} Fallback CLI candidate ${candidate} failed --version check (exit ${code}).`);
}
Expand Down
Loading
Loading