Preserve SSH conversations and select authentication before pools

Keep only account-scoped Codex conversation and native index state between in-place SSH turns. Refresh current credentials and managed files for each turn, copy authentication back before cleanup, and start a named fresh session when saved state is unavailable or the account changes.

Resolve SSH authentication before pool selection and native home selection. Preserve admitted native recovery inputs. Update transport test fixtures for the stdin command envelope and refresh the committed SDK source pins.

Validated 164 execution/routing/probe tests, 91 CI regression tests, 58 SDK support tests, and Codex, Grok and server typechecks. Physical shell tests cover two turns, refresh, account changes, old saved parameters, and failure cleanup.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip committed 2026-11-12 17:42:03 -08:00
1 parent 8490bf9df2
commit 03e654e870
14 files changed
+293 -18

No files matched your search

@@ -27,6 +27,8 @@ import { legacyExecutionNeedsReconciliation } from "../services/legacy-execution
import { getServerAdapter, registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
import { waitForPendingRunFailureReports } from "../services/run-failure-report.js";
import { dotRunnerBroker } from "../services/dot-runner-broker.js";
import { environmentService } from "../services/environments.js";
import * as executionConfiguration from "../services/heartbeat/execution-configuration.js";
const captureRunFailure = vi.hoisted(() => vi.fn());
vi.mock("../sentry.js", async (importOriginal) => ({
@@ -446,6 +448,52 @@ describe("durable, authorized connection routing", () => {
expect(resolveTaskSessionConfigFreshness({ hasTaskSession: true, configuredModel: String(selected.runtimeConfig.model), taskSessionParams: { __paperclipConfiguredModel: selected.runtimeConfig.model, __paperclipConfigFingerprint: previous.fingerprint, __paperclipConfigFingerprintVersion: previous.version, __paperclipConfigCategoryFingerprints: previous.categoryFingerprints }, configMetadata: current, compatibleConfigMetadata }).reset).toBe(false);
} finally { await before.cleanup(); await after.cleanup(); }
});
it.each([
{ useHostAuth: undefined, nativeHomeMode: undefined }, { useHostAuth: true, nativeHomeMode: undefined },
{ useHostAuth: false, nativeHomeMode: undefined }, { useHostAuth: false, nativeHomeMode: "preconfigured" },
])("applies SSH authentication before selecting a busy pool (%j)", async ({ useHostAuth, nativeHomeMode }) => {
const original = await instanceSettingsService(db).getExperimental();
await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true, enableNativeRunner: true, enableEnvironments: true, enableWorktreeRunExecution: true });
const pool = await makePool({ members: [members[0]!] });
const environment = await environmentService(db).create(companyId, { name: `SSH routing fixture ${useHostAuth} ${nativeHomeMode}`, driver: "ssh", status: "active", envVars: {}, config: {
host: "ssh.example.test", username: "fixture", remoteWorkspacePath: "/workspace", ...(useHostAuth === undefined ? {} : { useHostAuth }),
} });
const configured = { provider: "acpx", acpxAgent: "claude", model: "fixture-host-model", ...(nativeHomeMode ? { homeMode: nativeHomeMode } : {}) };
const [agent] = await db.insert(agents).values({ companyId, name: "SSH routing fixture", status: "idle", adapterType: "paperclip_runner",
adapterConfig: configured, defaultEnvironmentId: environment.id,
runtimeConfig: { aiConnection: { mode: "router", connectionId: pool.id }, heartbeat: { enabled: false, wakeOnDemand: true } } }).returning();
const [issue] = await db.insert(issues).values({ companyId, title: "SSH pool routing fixture", status: "todo", assigneeAgentId: agent.id, responsibleUserId: "alice", createdByUserId: "alice" }).returning();
proposal.mockClear();
proposal.mockImplementation(async () => ({ kind: "exhausted", retryAt: new Date(Date.now() + 60_000).toISOString(), skipped: {} }));
const preparation = vi.spyOn(executionConfiguration, "prepareHeartbeatExecutionConfiguration").mockRejectedValue(new Error("fixture stopped before provider configuration"));
const heartbeat = heartbeatService(db, { pluginWorkerManager: worker, runtimeEnv: {} });
try {
const run = await heartbeat.wakeup(agent.id, { source: "assignment", reason: "issue_assigned", triggerDetail: "system",
payload: { issueId: issue.id }, contextSnapshot: { issueId: issue.id, responsibleUserId: "alice" } });
expect(run).not.toBeNull();
await heartbeat.drainActiveRunExecutions();
const saved = await heartbeat.getRun(run!.id);
if (useHostAuth === false) {
expect(proposal).toHaveBeenCalled();
expect(preparation).not.toHaveBeenCalled();
expect(saved?.errorCode).toBe("ai_connection_pool_exhausted");
} else {
expect(proposal).not.toHaveBeenCalled();
expect(saved?.contextSnapshot?.aiRouterSelection).toBeUndefined();
expect(saved?.error).toContain("fixture stopped before provider configuration");
expect(preparation).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ config: expect.objectContaining({
aiBinding: undefined, sourceWorkspaceConfig: expect.objectContaining(configured),
}) }));
}
} finally {
await db.update(agents).set({ status: "paused" }).where(eq(agents.id, agent.id));
await heartbeat.drainActiveRunExecutions();
preparation.mockRestore();
proposal.mockImplementation(defaultProposal);
await instanceSettingsService(db).updateExperimental(original);
}
}, 30_000);
it("admits a healthy pool member when the saved Grok connection is held", async () => {
const original = await instanceSettingsService(db).getExperimental();
await instanceSettingsService(db).updateExperimental({ enableAiConnectionRouters: true,
@@ -25,7 +25,7 @@ import * as assignedMcp from "../services/native-runtime/assigned-mcp-tools.js";
import * as sentry from "../sentry.js";
import { waitForPendingRunFailureReports } from "../services/run-failure-report.js";
import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js";
import { selectHeartbeatEnvironment, type HeartbeatEnvironmentSelectionInput } from "../services/heartbeat/environment-selection.js";
import { selectHeartbeatEnvironment, resolveSshAuthenticationBeforeRouting, type HeartbeatEnvironmentSelectionInput } from "../services/heartbeat/environment-selection.js";
import { environmentService } from "../services/environments.js";
import { executionWorkspaceService } from "../services/execution-workspaces.js";
import { buildExecutionWorkspaceAdapterConfig } from "../services/execution-workspace-policy.js";
@@ -41,6 +41,21 @@ function deferred<T>() {
const skillFailures = vi.hoisted(() => new Map<string, string>());
const skillWaits = vi.hoisted(() => new Map<string, () => Promise<void>>());
describe("SSH authentication before account routing", () => {
it.each([
{ agentDefaultEnvironmentId: "agent", lowTrustIssueEnvironmentId: null, executionMode: "any", expectedId: "agent", expected: "host" },
{ agentDefaultEnvironmentId: null, lowTrustIssueEnvironmentId: null, executionMode: "any", expectedId: "instance", expected: "host" },
{ agentDefaultEnvironmentId: "agent", lowTrustIssueEnvironmentId: "sandbox", executionMode: "any", expectedId: "sandbox", expected: null },
{ agentDefaultEnvironmentId: "agent", lowTrustIssueEnvironmentId: null, executionMode: "kubernetes", expectedId: null, expected: null },
] as const)("honors environment precedence and forced execution policy: %j", async value => {
const get = vi.fn(async () => ({ defaultEnvironmentId: "instance", general: { executionMode: value.executionMode } }));
const getById = vi.fn(async (id: string) => ({ id, driver: id === "sandbox" ? "sandbox" : "ssh", config: {} } as Environment));
expect(await resolveSshAuthenticationBeforeRouting({ ...value, instanceSettings: { get }, environmentsSvc: { getById } })).toBe(value.expected);
if (value.expectedId) expect(getById).toHaveBeenCalledExactlyOnceWith(value.expectedId);
else expect(getById).not.toHaveBeenCalled();
});
});
describe("Runner home mode during recovery preparation", () => {
const fingerprint = (effectiveAdapterConfig: Record<string, unknown>) => buildEffectiveRunSessionConfigMetadata({
adapterType: "paperclip_runner", effectiveAdapterConfig, agentRuntimeConfig: {}, issueOverrides: null,
@@ -24,7 +24,7 @@ vi.mock("node:child_process", async importOriginal => {
spawn: (file: string, args: string[], options: Parameters<typeof actual.spawn>[2]) => {
if (file !== "ssh") return actual.spawn(file, args, options);
mocks.wire.push({ file, args, stdin: true });
return actual.spawn(process.execPath, ["-e", 'process.stdout.write(require("node:fs").readFileSync(0,"utf8"))'], options);
return actual.spawn(process.execPath, ["-e", 'const wire = require("node:fs").readFileSync(0); process.stdout.write(wire.subarray(wire.indexOf(10) + 1))'], options);
},
};
});
+1 -1
View File
@@ -3391,7 +3391,7 @@ export function agentRoutes(
});
type = selection.adapterType;
adapterConfigForTest = { ...selection.adapterConfig,
...(type === "paperclip_runner" && requestedEnvironment?.driver === "ssh" && requestedEnvironment.config.useHostAuth !== false ? { homeMode: "preconfigured" } : {}) };
...(type === "paperclip_runner" && requestedEnvironment?.driver === "ssh" ? { homeMode: requestedEnvironment.config.useHostAuth === false ? "isolated" : "preconfigured" } : {}) };
if (requestedEnvironment) await assertAdapterTestEnvironmentForCompany(companyId, requestedEnvironment.id, type);
const adapter = requireServerAdapter(type);
if (!retainsSavedExecution) await assertSelectableAdapterType(type, adapterConfigForTest, companyId);
+11 -2
View File
@@ -58,7 +58,7 @@ import { readRecoverableRunLog } from "./native-runtime/native-run-log-recovery.
import { observabilitySecretValues } from "@paperclipai/adapter-utils/agent-observability";
import { prepareHeartbeatSession, resolveHeartbeatAdapterSession } from "./heartbeat/session-preparation.js";
import { prepareHeartbeatTaskContext } from "./heartbeat/task-context.js";
import { selectHeartbeatEnvironment } from "./heartbeat/environment-selection.js";
import { selectHeartbeatEnvironment, resolveSshAuthenticationBeforeRouting } from "./heartbeat/environment-selection.js";
import { reconcileMuseNativeTerminalRun } from "./native-runtime/muse-terminal-reconciliation.js";
import { prepareHeartbeatWorkspace } from "./heartbeat/workspace-preparation.js";
import { nativeRecoveryClaimRelinquished, ownNativeExecutionLeaseLapsed, releaseLapsedNativeRestartClaim } from "./native-runtime/native-execution-lease.js";
@@ -2666,8 +2666,17 @@ export function heartbeatService(
if ("homeMode" in homeConfig) config = { ...config, homeMode: homeConfig.homeMode };
}
const persistedRouterPoolId = routerHasPersistedInput ? readNonEmptyString(parseObject(context.aiRouterSelection).poolId) : null;
const sshAuthentication = routerHasPersistedInput ? null : await resolveSshAuthenticationBeforeRouting({
agentDefaultEnvironmentId: agent.defaultEnvironmentId,
lowTrustIssueEnvironmentId: trustPreset.kind === "low_trust_review"
? parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings, { includeEnvironmentId: true })?.environmentId ?? null : null,
environmentsSvc, instanceSettings,
});
if (agent.adapterType === "paperclip_runner" && sshAuthentication) {
config = { ...config, homeMode: sshAuthentication === "host" ? "preconfigured" : "isolated" };
}
const preconfiguredHome = agent.adapterType === "paperclip_runner" && config.homeMode === "preconfigured";
const requestedAiBinding = preconfiguredHome ? undefined : persistedRouterPoolId ? { mode: "router" as const, connectionId: persistedRouterPoolId } : agent.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(agent.runtimeConfig.aiConnection) : undefined;
const requestedAiBinding = preconfiguredHome || sshAuthentication === "host" ? undefined : persistedRouterPoolId ? { mode: "router" as const, connectionId: persistedRouterPoolId } : agent.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(agent.runtimeConfig.aiConnection) : undefined;
let aiBinding = requestedAiBinding?.mode === "router" ? undefined : requestedAiBinding;
const originalAiIssueOverrides = issueAssigneeOverrides;
if (requestedAiBinding?.mode === "router") {
@@ -3,7 +3,7 @@ import { heartbeatExternalProvider, nativeExecutionUsesTaskWorkspace } from "./e
import { heartbeatRuns, issues, type Db, type agents } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import { readGitCacheExpiration } from "../git-workspace-restoration.js";
import type { ExecutionWorkspace, IssueExecutionWorkspaceSettings, ProjectExecutionWorkspacePolicy } from "@paperclipai/shared";
import type { ExecutionWorkspace, InstanceSettings, IssueExecutionWorkspaceSettings, ProjectExecutionWorkspacePolicy } from "@paperclipai/shared";
import { parseObject } from "../../adapters/utils.js";
import { logger } from "../../middleware/logger.js";
import { parseNativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
@@ -39,6 +39,23 @@ import { resolveNativeRecoveryExecutionWorkspaceBinding, resolveExecutionWorkspa
type Issue = typeof issues.$inferSelect;
export async function resolveSshAuthenticationBeforeRouting(input: {
agentDefaultEnvironmentId: string | null;
lowTrustIssueEnvironmentId: string | null;
environmentsSvc: Pick<ReturnType<typeof environmentService>, "getById">;
instanceSettings: { get(): Promise<{
defaultEnvironmentId: InstanceSettings["defaultEnvironmentId"];
general: Pick<InstanceSettings["general"], "executionMode">;
}> };
}): Promise<"host" | "managed" | null> {
const settings = await input.instanceSettings.get();
if (isExecutionForcedToKubernetes({ executionMode: settings.general.executionMode })) return null;
const id = input.lowTrustIssueEnvironmentId ?? input.agentDefaultEnvironmentId ?? settings.defaultEnvironmentId;
if (!id) return null;
const environment = await input.environmentsSvc.getById(id);
return environment?.driver === "ssh" ? environment.config.useHostAuth === false ? "managed" : "host" : null;
}
/** Selects policy and reuse inputs; lease acquisition and cleanup belong to the executor. */
export interface HeartbeatEnvironmentSelectionInput {
run: Pick<typeof heartbeatRuns.$inferSelect,
@@ -102,7 +102,7 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
const useSshHostAuth = selectedEnvironmentForConfig?.driver === "ssh" && selectedEnvironmentForConfig.config.useHostAuth !== false && !persistedNativeExecutionInput;
const sourceWorkspaceConfig = agent.adapterType === "paperclip_runner"
? { ...input.config.sourceWorkspaceConfig,
homeMode: bindHeartbeatRunnerHomeMode({ ...parseObject(agent.adapterConfig), ...(useSshHostAuth ? { homeMode: "preconfigured" } : {}) }, persistedNativeExecutionInput).homeMode }
homeMode: bindHeartbeatRunnerHomeMode({ ...parseObject(agent.adapterConfig), ...(selectedEnvironmentForConfig?.driver === "ssh" && !persistedNativeExecutionInput ? { homeMode: useSshHostAuth ? "preconfigured" : "isolated" } : {}) }, persistedNativeExecutionInput).homeMode }
: input.config.sourceWorkspaceConfig;
const preconfiguredHome = agent.adapterType === "paperclip_runner" && sourceWorkspaceConfig.homeMode === "preconfigured";
if (preconfiguredHome && pinnedSkillTest) {
@@ -58,7 +58,7 @@ describe("native SSH deliverable output budget", () => {
});
it("still delivers every byte when SSH consumes the upload", async () => {
await writeFile(join(root, "ssh"), `#!${process.execPath}\nconst hash = require('node:crypto').createHash('sha256');\nprocess.stdin.on('data', chunk => hash.update(chunk));\nprocess.stdin.on('end', () => process.stdout.write(hash.digest('hex')));\n`);
await writeFile(join(root, "ssh"), `#!${process.execPath}\nconst chunks = [];\nprocess.stdin.on('data', chunk => chunks.push(chunk));\nprocess.stdin.on('end', () => { const wire = Buffer.concat(chunks); const end = wire.indexOf(10); if (end < 0) process.exit(1); process.stdout.write(require('node:crypto').createHash('sha256').update(wire.subarray(end + 1)).digest('hex')); });\n`);
const stdin = "synthetic upload bytes\0".repeat(32_768);
const result = await createRunner().execute({ command: "node", args: ["unused"], stdin, timeoutMs: 5000 });
expect(result.exitCode).toBe(0);