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);
},
};
});