Use agent AI accounts in SSH environments

Stage the selected agent account in a private remote home and restore refreshed credentials before cleanup. Preserve remote authentication for existing SSH environments and expose it as an advanced option.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip committed 2026-11-12 17:08:59 -08:00
1 parent 2dcfdabc79
commit 8490bf9df2
41 files changed
+4471 -3774

No files matched your search

@@ -575,6 +575,24 @@ describe("agent test-environment route", () => {
expect(mockCopilotModels).not.toHaveBeenCalled();
});
it.each([undefined, true, false])("uses the selected SSH authentication source for probes (%s)", async useHostAuth => {
const environmentId = "11111111-1111-4111-8111-111111111111";
mockEnvironmentService.getById.mockResolvedValue({ id: environmentId, name: "SSH", driver: "ssh",
config: { ...(useHostAuth !== undefined ? { useHostAuth } : {}), host: "fixture.invalid", username: "fixture", remoteWorkspacePath: "/workspace" } });
const target = { kind: "remote", transport: "ssh", remoteCwd: "/workspace", spec: { host: "fixture.invalid", port: 22, username: "fixture", remoteCwd: "/workspace", remoteWorkspacePath: "/workspace", useHostAuth } };
mockResolveEnvironmentExecutionTarget.mockResolvedValue(target);
const response = await request(await createApp()).post("/api/companies/company-1/adapters/external_test/test-environment")
.send({ adapterConfig: {}, environmentId });
if (useHostAuth === false) {
expect(response.status, JSON.stringify(response.body)).toBe(422);
expect(response.body.code).toBe("ssh_ai_connection_required");
expect(testEnvironmentSpy).not.toHaveBeenCalled();
} else {
expect(response.status, JSON.stringify(response.body)).toBe(200);
expect(testEnvironmentSpy).toHaveBeenCalledWith(expect.objectContaining({ executionTarget: target }));
}
});
it("tests the instance default sandbox when the agent inherits its environment", async () => {
const environmentId = "11111111-1111-4111-8111-111111111111";
mockInstanceSettingsService.get.mockResolvedValue({ defaultEnvironmentId: environmentId });
@@ -3,6 +3,17 @@ import { HttpError } from "../errors.js";
import { normalizeEnvironmentConfig, parseEnvironmentDriverConfig } from "../services/environment-config.ts";
describe("environment config helpers", () => {
it.each([undefined, true, false])("preserves SSH authentication compatibility when useHostAuth is %s", useHostAuth => {
const config = normalizeEnvironmentConfig({ driver: "ssh", config: {
host: "ssh.example.test", username: "fixture", remoteWorkspacePath: "/workspace",
...(useHostAuth !== undefined ? { useHostAuth } : {}),
} });
expect(config.useHostAuth).toBe(useHostAuth);
expect(Object.hasOwn(config, "useHostAuth")).toBe(useHostAuth !== undefined);
expect(() => normalizeEnvironmentConfig({ driver: "ssh", config: { ...config, useHostAuth: "false" } })).toThrow(HttpError);
});
it("normalizes SSH config into its canonical stored shape", () => {
const config = normalizeEnvironmentConfig({
driver: "ssh",
@@ -333,7 +333,7 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (
}
});
async function configuration(f: Awaited<ReturnType<typeof seed>>, config: Record<string, unknown>, snapshot: Record<string, unknown> = {}, type = "paperclip_runner", explicitTaskDirectory = false, requestedExecutionWorkspaceMode: HeartbeatExecutionConfigurationInput["policy"]["requestedExecutionWorkspaceMode"] = "shared_workspace", selectedEnvironmentForConfig: HeartbeatExecutionConfigurationInput["environment"]["selectedEnvironmentForConfig"] = null, pinnedSkillTest?: HeartbeatExecutionConfigurationInput["task"]["pinnedSkillTest"], adoptingLiveRunner = false) {
async function configuration(f: Awaited<ReturnType<typeof seed>>, config: Record<string, unknown>, snapshot: Record<string, unknown> = {}, type = "paperclip_runner", explicitTaskDirectory = false, requestedExecutionWorkspaceMode: HeartbeatExecutionConfigurationInput["policy"]["requestedExecutionWorkspaceMode"] = "shared_workspace", selectedEnvironmentForConfig: HeartbeatExecutionConfigurationInput["environment"]["selectedEnvironmentForConfig"] = null, pinnedSkillTest?: HeartbeatExecutionConfigurationInput["task"]["pinnedSkillTest"], adoptingLiveRunner = false, aiBinding?: HeartbeatExecutionConfigurationInput["config"]["aiBinding"]) {
const [agent] = await db.update(agents).set({ adapterType: type, adapterConfig: config }).where(eq(agents.id, f.agentId)).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, scopeKind: "issue", status: "running", contextSnapshot: snapshot }).returning();
const resolvedInstanceSettings = await instanceSettingsService(db).get();
@@ -344,7 +344,7 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (
task: { issueId: f.issueId, context: { ...snapshot, issueId: f.issueId }, responsibleUserId: null, pinnedSkillTest, adoptingLiveRunner,
acceptedPlanContinuationWake: false, acceptedPlanWakeRoutingDecision: null,
taskProjectContext: null, routineEnvContext: { routineId: null, env: null, responsibleUserId: null } },
config: { sourceWorkspaceConfig: config, aiBinding: undefined },
config: { sourceWorkspaceConfig: config, aiBinding },
policy: { trustPreset: { kind: "standard", preset: "standard", boundary: null, sourcePresets: {} }, useIsolatedTaskDirectory: false, explicitTaskDirectory, requestedExecutionWorkspaceMode },
environment: { selectedEnvironmentId: environment.id, selectedEnvironmentForConfig: environment,
resolvedInstanceSettings, persistedNativeExecutionInput: adoptingLiveRunner
@@ -356,6 +356,31 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (
}) };
}
it.each([undefined, true, false])("defaults existing SSH environments to remote authentication and honors the saved choice (saved=%s)", async useHostAuth => {
const f = await seed(true);
const environment = { ...await environmentService(db).ensureLocalEnvironment(), driver: "ssh", config: { ...(useHostAuth !== undefined ? { useHostAuth } : {}), host: "fixture.invalid", username: "fixture", remoteWorkspacePath: "/workspace" } } as Environment;
const binding = aiConnectionBindingSchema.parse((await db.select().from(agents).where(eq(agents.id, f.agentId)))[0]!.runtimeConfig!.aiConnection);
const prepare = vi.spyOn(aiRuntime, "prepareManagedAiRuntime").mockRejectedValue(new Error("fixture managed account reached"));
const opening = await configuration(f, { provider: "codex" }, {}, "paperclip_runner", false, "shared_workspace", environment, undefined, false, binding);
if (useHostAuth !== false) {
const result = await opening.prepare();
expect(result.prepared).toBe(true);
if (!result.prepared) throw new Error("SSH configuration failed");
expect(result.runtimeConfig.homeMode).toBe("preconfigured");
expect(prepare).not.toHaveBeenCalled();
} else {
await expect(opening.prepare()).rejects.toThrow("fixture managed account reached");
expect(prepare).toHaveBeenCalledOnce();
}
});
it("requires an agent AI account for a new SSH environment when remote authentication is off", async () => {
const f = await seed();
const environment = { ...await environmentService(db).ensureLocalEnvironment(), driver: "ssh", config: { useHostAuth: false } } as Environment;
const opening = await configuration(f, { provider: "codex" }, {}, "paperclip_runner", false, "shared_workspace", environment);
await expect(opening.prepare()).rejects.toMatchObject({ resultJson: { configurationIncomplete: { reason: "ssh_ai_connection_required" } } });
});
it("delivers the Studio pin instead of ordinary assignments and recovers that exact native selection", async () => {
const f = await seed(), skills = companySkillService(db);
const selected = await skills.createLocalSkill(f.companyId, { name: "Unassigned Studio skill", markdown: "# Studio\nOriginal selected bytes.\n" });
+13 -3
View File
@@ -3262,6 +3262,7 @@ export function agentRoutes(
return { connectionId: selection.connection.id };
}
const testEnvironment = testEnvironmentId ? await environmentsSvc.getById(testEnvironmentId) : null;
if (testEnvironment?.driver === "ssh" && testEnvironment.config.useHostAuth !== false) return { connectionId: selection.connection.id };
if (adapterType === "paperclip_runner" && config.homeMode === "preconfigured" && testEnvironment
&& await pluginEnvironmentRunnerTaskDriver(db, testEnvironment)) {
throw unprocessable(pluginRunnerAiConnectionRequiredMessage(true), { code: PLUGIN_RUNNER_AI_CONNECTION_REQUIRED });
@@ -3299,7 +3300,7 @@ export function agentRoutes(
await assertCanCreateAgentsForCompany(req, companyId);
const requestedBinding = req.body.aiConnection ? aiRuntimeConnectionBindingSchema.parse(req.body.aiConnection) : undefined;
const aiBinding = requestedBinding?.mode === "router" ? undefined : requestedBinding;
let aiBinding = requestedBinding?.mode === "router" ? undefined : requestedBinding;
if (aiBinding && req.body.testCredentials && Object.keys(req.body.testCredentials).length) throw unprocessable("A managed connection test cannot override its credentials");
const inputAdapterConfig = aiBinding ? { ...req.body.adapterConfig, env: stripAiAuthBindings(req.body.adapterConfig?.env) } : (req.body?.adapterConfig ?? {}) as Record<string, unknown>;
const savedAgentId = typeof req.body.agentId === "string" ? req.body.agentId : null;
@@ -3312,7 +3313,7 @@ export function agentRoutes(
await assertCanConfigureAgentSetup(req, savedAgent);
}
const testingSetup = savedAgent ? isAgentSetupDraft(savedAgent) : false;
const poolBinding = requestedBinding ?? (savedAgent?.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(savedAgent.runtimeConfig.aiConnection) : undefined);
let poolBinding = requestedBinding ?? (savedAgent?.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(savedAgent.runtimeConfig.aiConnection) : undefined);
const prospectiveCursorDefault = type === "cursor_cloud" && !savedAgent
&& (req.body.runner === undefined || req.body.runner === "auto")
&& managedCursorApiDefaultEnabled((await instanceSettings.get()).experimental);
@@ -3347,6 +3348,14 @@ export function agentRoutes(
const requestedEnvironment = requestedEnvironmentId
? await assertAdapterTestEnvironmentBinding(companyId, requestedEnvironmentId)
: null;
if (requestedEnvironment?.driver === "ssh" && requestedEnvironment.config.useHostAuth !== false) {
aiBinding = undefined;
poolBinding = undefined;
}
if (requestedEnvironment?.driver === "ssh" && requestedEnvironment.config.useHostAuth === false) {
if (!aiBinding && poolBinding?.mode !== "router") aiBinding = poolBinding;
if (!aiBinding && !poolBinding) throw unprocessable("Select an AI account for this agent or enable authentication configured on the remote machine in the SSH environment's advanced settings.", { code: "ssh_ai_connection_required" });
}
// Agent reads redact every plain environment value. When this is a saved
// agent test, restore those display-only placeholders from the
// server-side config before validating or resolving secrets; otherwise
@@ -3381,7 +3390,8 @@ export function agentRoutes(
defaultEnvironmentId: requestedEnvironmentId,
});
type = selection.adapterType;
adapterConfigForTest = selection.adapterConfig;
adapterConfigForTest = { ...selection.adapterConfig,
...(type === "paperclip_runner" && requestedEnvironment?.driver === "ssh" && requestedEnvironment.config.useHostAuth !== false ? { homeMode: "preconfigured" } : {}) };
if (requestedEnvironment) await assertAdapterTestEnvironmentForCompany(companyId, requestedEnvironment.id, type);
const adapter = requireServerAdapter(type);
if (!retainsSavedExecution) await assertSelectableAdapterType(type, adapterConfigForTest, companyId);
@@ -38,6 +38,7 @@ const secretRefSchema = z.object({
}).strict();
const sshEnvironmentConfigSchema = z.object({
useHostAuth: z.boolean().optional(),
host: z.string({ error: "SSH environments require a host." }).trim().min(1, "SSH environments require a host."),
port: z.coerce.number().int().min(1).max(65535).default(22),
username: z.string({ error: "SSH environments require a username." }).trim().min(1, "SSH environments require a username."),
@@ -699,6 +699,7 @@ export async function resolveEnvironmentExecutionTarget(input: {
leaseId: input.leaseId ?? null,
remoteCwd,
spec: {
useHostAuth: parsed.config.useHostAuth !== false,
host: parsed.config.host,
port: parsed.config.port,
username: parsed.config.username,
@@ -99,9 +99,10 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
const time = createHeartbeatPreparationTiming(run.id);
const { issueId, context, responsibleUserId, acceptedPlanContinuationWake, acceptedPlanWakeRoutingDecision, taskProjectContext, routineEnvContext, pinnedSkillTest } = input.task;
const { selectedEnvironmentId, selectedEnvironmentForConfig, resolvedInstanceSettings, persistedNativeExecutionInput } = input.environment;
const useSshHostAuth = selectedEnvironmentForConfig?.driver === "ssh" && selectedEnvironmentForConfig.config.useHostAuth !== false && !persistedNativeExecutionInput;
const sourceWorkspaceConfig = agent.adapterType === "paperclip_runner"
? { ...input.config.sourceWorkspaceConfig,
homeMode: bindHeartbeatRunnerHomeMode(parseObject(agent.adapterConfig), persistedNativeExecutionInput).homeMode }
homeMode: bindHeartbeatRunnerHomeMode({ ...parseObject(agent.adapterConfig), ...(useSshHostAuth ? { homeMode: "preconfigured" } : {}) }, persistedNativeExecutionInput).homeMode }
: input.config.sourceWorkspaceConfig;
const preconfiguredHome = agent.adapterType === "paperclip_runner" && sourceWorkspaceConfig.homeMode === "preconfigured";
if (preconfiguredHome && pinnedSkillTest) {
@@ -135,7 +136,12 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
// The executor keeps these values in its failure redactor before any later
// preparation step can fail. Subsequent provider/identity values extend it.
onFailureSecretsResolved(() => []);
const aiBinding = preconfiguredHome ? undefined : input.config.aiBinding;
const aiBinding = preconfiguredHome || useSshHostAuth ? undefined : input.config.aiBinding;
if (selectedEnvironmentForConfig?.driver === "ssh" && selectedEnvironmentForConfig.config.useHostAuth === false && !aiBinding && !persistedNativeExecutionInput) {
throw new ConfigurationIncompleteFailure("Select an AI account for this agent or enable authentication configured on the remote machine in the SSH environment's advanced settings.", {
configurationIncomplete: { reason: "ssh_ai_connection_required", actionUrl: `/agents/${agent.id}/runtime` },
});
}
const { trustPreset, useIsolatedTaskDirectory, explicitTaskDirectory, requestedExecutionWorkspaceMode } = input.policy;
const { secretsSvc, companySkills, appendRunEvent, finalizeAiConnectionBusyDeferral } = input.services;
let managedAiRuntime: ManagedAiRuntime | undefined;