feat(ssh): use the agent AI account in new environments (#21248)

Use the agent-selected AI account for new SSH environments. Preserve
remote-machine authentication for existing environments and expose it as
an advanced option. Keep managed credentials private while preserving
supported conversation state and credential refreshes across turns.

Validated with focused route, adapter, lifecycle, and real-process tests;
final CI passed on d634944df1.
Greptile Apex reviewed that revision at 5/5 with no unresolved threads.
External neutral security reports remain documented in the pull request.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-13 13:20:13 -08:00
1 parent 2a8b485140
commit 12aa08721c
77 files changed
+6115 -3898

No files matched your search

+2 -34
View File
@@ -1,3 +1,5 @@
import { managedAiHomeEnvironment } from "@paperclipai/adapter-utils/managed-ai-runtime-env";
export { managedAiSessionFingerprintConfig } from "@paperclipai/adapter-utils/managed-ai-runtime-env";
import { environmentTaskResultSchema } from "@paperclipai/plugin-sdk";
import type { ManagedAiCredentialWritebackBinding } from "./managed-ai-credential-writeback.js";
import { OPENROUTER_ATTRIBUTION_HEADERS, openRouterClaudeHeaders } from "@paperclipai/shared/openrouter-attribution";
@@ -208,40 +210,6 @@ done`,
}
}
function managedAiHomeEnvironment(home: string): Record<string, string> {
const providerHome = path.join(home, "provider");
return {
HOME: home,
XDG_CONFIG_HOME: path.join(home, "config"),
XDG_DATA_HOME: path.join(home, "data"),
CODEX_HOME: providerHome,
GROK_HOME: providerHome,
CLAUDE_CONFIG_DIR: providerHome,
HERMES_HOME: providerHome,
};
}
/** Only the server-created credential home is volatile; retain all other config. */
export function managedAiSessionFingerprintConfig(
config: Record<string, unknown>,
managedHome: string | undefined,
): Record<string, unknown> {
if (!managedHome) return config;
const env = { ...(config.env as Record<string, unknown> | undefined) };
const stable = managedAiHomeEnvironment("<managed-ai-home>");
for (const [key, value] of Object.entries(managedAiHomeEnvironment(managedHome))) {
if (env[key] === value) env[key] = stable[key];
}
if (env.GEMINI_HOME === path.join(managedHome, "provider")) env.GEMINI_HOME = path.join("<managed-ai-home>", "provider");
const managed = config.managedAiConnection as Record<string, unknown> | undefined;
if (managed?.sessionIdentity) {
for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "OPENROUTER_API_KEY", "XAI_API_KEY", "GROK_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENCODE_AUTH_JSON", "OPENCODE_CONFIG_CONTENT"]) {
if (env[key]) env[key] = "<managed-ai-credential>";
}
}
return { ...config, env, ...(managed?.sessionIdentity ? { managedAiConnection: { ...managed, identity: managed.sessionIdentity } } : {}) };
}
export async function prepareManagedAiRuntime(
db: Db,
input: {
@@ -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."),
@@ -545,6 +546,7 @@ export function normalizeEnvironmentConfigForProbe(input: {
export async function normalizeEnvironmentConfigForPersistence(input: {
db: Db;
operation?: "create" | "update";
companyId: string;
environmentName: string;
driver: EnvironmentDriver;
@@ -583,6 +585,7 @@ export async function normalizeEnvironmentConfigForPersistence(input: {
}
return {
...stored,
...(input.operation === "create" ? { useHostAuth: stored.useHostAuth ?? false } : {}),
privateKey: null,
privateKeySecretRef: nextPrivateKeySecretRef,
} satisfies SshEnvironmentConfig;
@@ -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,
+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, RetryWorkspaceRefused } from "./heartbeat/workspace-preparation.js";
import { nativeRecoveryClaimRelinquished, ownNativeExecutionLeaseLapsed, releaseLapsedNativeRestartClaim } from "./native-runtime/native-execution-lease.js";
@@ -2715,8 +2715,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,
@@ -1,3 +1,4 @@
import { supportsPaperclipRunnerPreconfiguredHome } from "../native-runtime/provider-profile.js";
import { agentHarnessType } from "@paperclipai/shared";
import { observabilitySecretValues } from "@paperclipai/adapter-utils/agent-observability";
import { agentObservabilityService, unavailableAgentObservability, type ResolvedAgentObservability } from "../agent-observability.js";
@@ -118,9 +119,14 @@ 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;
let sshRunnerHomeMode: "isolated" | "preconfigured" | undefined;
if (agent.adapterType === "paperclip_runner" && selectedEnvironmentForConfig?.driver === "ssh" && !persistedNativeExecutionInput) {
sshRunnerHomeMode = useSshHostAuth && supportsPaperclipRunnerPreconfiguredHome(agent.adapterConfig, { companyId: agent.companyId }) ? "preconfigured" : "isolated";
}
const sourceWorkspaceConfig = agent.adapterType === "paperclip_runner"
? { ...input.config.sourceWorkspaceConfig,
homeMode: bindHeartbeatRunnerHomeMode(parseObject(agent.adapterConfig), persistedNativeExecutionInput).homeMode }
homeMode: bindHeartbeatRunnerHomeMode({ ...parseObject(agent.adapterConfig), ...(sshRunnerHomeMode ? { homeMode: sshRunnerHomeMode } : {}) }, persistedNativeExecutionInput).homeMode }
: input.config.sourceWorkspaceConfig;
const preconfiguredHome = agent.adapterType === "paperclip_runner" && sourceWorkspaceConfig.homeMode === "preconfigured";
if (preconfiguredHome && pinnedSkillTest) {
@@ -154,7 +160,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 } = input.policy;
const { secretsSvc, companySkills, appendRunEvent, finalizeAiConnectionBusyDeferral } = input.services;
let managedAiRuntime: ManagedAiRuntime | undefined;
@@ -182,6 +182,43 @@ describe.skipIf(!support.supported)("heartbeat runtime selection boundary", () =
expect(await coordinators(f.run.id)).toHaveLength(1);
});
it.each(["isolated", "preconfigured"] as const)("pins the prepared %s home mode into fresh native selection and recovery", async homeMode => {
const f = await fixture();
f.agent.adapterConfig = { ...f.agent.adapterConfig, homeMode: homeMode === "isolated" ? "preconfigured" : "isolated" };
f.input.config.runtimeConfig.homeMode = homeMode;
const selected = await selectHeartbeatRuntime(db, f.input);
if (!selected.selected || !selected.nativeExecution) throw new Error("Expected native selection");
expect("homeMode" in selected.nativeExecution ? selected.nativeExecution.homeMode : "isolated").toBe(homeMode);
const saved = await read(f.run.id);
f.input.run = saved;
f.input.session.persistedRunnerProfile = saved.runnerProfileJson ?? {};
f.input.session.persistedNativeExecutionInput = selected.nativeExecution;
f.input.config.runtimeConfig.homeMode = homeMode === "isolated" ? "preconfigured" : "isolated";
expect(await selectHeartbeatRuntime(db, f.input)).toMatchObject({ selected: true, nativeExecution: selected.nativeExecution });
expect((await read(f.run.id)).runnerProfileJson).toEqual(saved.runnerProfileJson);
});
it.each([
{ provider: "opencode", model: "openai/gpt-5" },
{ provider: "acpx", acpxAgent: "copilot", model: "gpt-5.6-luna" },
{ provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-4-6", acpxPermissionMode: "approve-reads" },
])("retains supported isolated native selection for SSH host auth: $provider $acpxAgent", async adapterConfig => {
const f = await fixture();
f.input.agent = { ...f.agent, adapterConfig };
await db.update(agents).set({ adapterConfig }).where(eq(agents.id, f.agent.id));
f.input.workspace.executionTarget = { kind: "remote", transport: "ssh", remoteCwd: "/workspace", spec: {
host: "fixture.invalid", port: 22, username: "fixture", remoteWorkspacePath: "/workspace", remoteCwd: "/workspace",
useHostAuth: true, privateKey: null, knownHosts: null, strictHostKeyChecking: true,
} };
f.input.nativeRuntimeResolution = resolveHeartbeatNativeRuntimeMode({ persisted: f.run, enabled: true, runtimeConfig: {},
adapterConfig, agent: f.input.agent, issue: f.issue, target: f.input.workspace.executionTarget, workspaceId: null });
f.input.config.runtimeConfig.homeMode = "preconfigured";
const selected = await selectHeartbeatRuntime(db, f.input);
if (!selected.selected || !selected.nativeExecution) throw new Error("Expected native selection");
expect("homeMode" in selected.nativeExecution ? selected.nativeExecution.homeMode : "isolated").toBe("isolated");
expect(selected.nativeExecution.provider.kind).toBe(adapterConfig.provider === "acpx" ? "acpx" : "opencode");
});
it("preserves immutable native recovery when current local Runner configuration is invalid", async () => {
const f = await fixture();
const selected = await selectHeartbeatRuntime(db, f.input);
@@ -67,6 +67,7 @@ import {
assertManagedProfileRecoveryBinding,
projectPaperclipRunnerTaskConfig,
resolvePaperclipRunnerNativeProviderInput,
supportsPaperclipRunnerPreconfiguredHome,
} from "../native-runtime/provider-profile.js";
import { readRemoteCodexModelCliVersion } from "../native-runtime/codex-model-fallback.js";
import {
@@ -771,7 +772,7 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele
instructionWorkingCopy: instructionCopy ? { rootPath: instructionCopy.executionRoot, entryPath: instructionCopy.entryFile, ...(isAgentDirectoryCopy(instructionCopy) ? { kind: "agent_files" as const } : {}) } : undefined,
}));
getNativeFreshSessionHandoff = nativeReviewRequest ? undefined : getFreshSessionHandoff;
const nativeProviderConfig = nativeRuntimeResolution.profile.backend === "cursor_cloud_api"
const projectedNativeProviderConfig = nativeRuntimeResolution.profile.backend === "cursor_cloud_api"
|| nativeRuntimeResolution.profile.backend === "codex_app_server"
|| (nativeRuntimeResolution.profile.backend === "acpx_runtime" && ["claude_local", "grok_local"].includes(agentHarnessType(agent.adapterType, parseObject(agent.adapterConfig))))
|| nativeRuntimeResolution.profile.backend === "opencode_server"
@@ -784,6 +785,12 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele
managedAiRuntime ? readNonEmptyString(resolvedConfig.model) ?? undefined : undefined,
)
: agent.adapterConfig;
const runnerHomeMode = runtimeConfig.homeMode === "preconfigured" && executionTarget?.kind === "remote" && executionTarget.transport === "ssh"
&& !supportsPaperclipRunnerPreconfiguredHome(projectedNativeProviderConfig, { companyId: agent.companyId })
? "isolated" : runtimeConfig.homeMode;
const nativeProviderConfig = agent.adapterType === "paperclip_runner" && runnerHomeMode !== undefined
? { ...parseObject(projectedNativeProviderConfig), homeMode: runnerHomeMode }
: projectedNativeProviderConfig;
const requestedNativeProvider = resolvePaperclipRunnerNativeProviderInput({
companyId: agent.companyId,
backend: nativeRuntimeResolution.profile.backend,
@@ -21613,7 +21613,7 @@ describe("runnerd provider runtime wiring", () => {
homeMode: "preconfigured" as const, executionMode: "default" as const, planningContext: null,
provider: { kind: "codex" as const, model: null, approvalPolicy: "never" as const }, runtimeContext: nativeRuntimeContextFixture() };
const remoteExecute = vi.fn(async (command: { args?: string[] }) => ({
exitCode: 0, timedOut: false, stderr: "", stdout: command.args?.[1]?.includes("getent passwd") ? "/home/executor\n" : "",
exitCode: 0, timedOut: false, stderr: "", stdout: command.args?.includes("paperclip-remote-home") ? "/home/executor\n" : "",
}));
await createRunnerdBackend({ db: leaseDb(remoteExecution), execution: remoteExecution, runnerInstanceId: "remote-home-manifest",
runnerEnvironment, runnerIngressAuthorized: true, runnerExecutionTarget: {
@@ -22092,7 +22092,7 @@ describe("runnerd provider runtime wiring", () => {
if (command.args?.[0] === "--version") return {
exitCode: 0, timedOut: false, stdout: "codex-cli 0.160.0", stderr: "",
};
if (command.args?.[1]?.includes("getent passwd")) return {
if (command.args?.includes("paperclip-remote-home")) return {
exitCode: 0, timedOut: false, stdout: "/home/executor\n", stderr: "",
};
if (command.args?.[2] === "paperclip-runner-launch") {
@@ -233,6 +233,7 @@ import type { NativeRunnerAttachmentDownload, NativeRunnerAttachmentStage } from
import { discoverRemoteExecutable, parseRemoteExecutableCandidate } from "./codex-model-fallback.js";
export { parseRemoteExecutableCandidate } from "./codex-model-fallback.js";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import { readRemoteUserHome } from "./remote-user-home.js";
import { NativeRunnerIngressAcquisitionError, prepareNativeRemoteRunner, createNativeRunnerExecutionDriver, resolveRemoteRunnerTransportMode } from "./native-runner-execution-driver.js";
import type { Db } from "@paperclipai/db";
import {
@@ -18048,14 +18049,7 @@ async function createRunnerdBackendWithinSessionClaim(
delete effectiveRunnerEnvironmentBase.PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME;
if (preconfiguredHome) {
if (remoteCommandRunner) {
const discovered = await remoteCommandRunner.execute({
command: "sh", args: ["-c", 'getent passwd "$(id -u)" | cut -d: -f6'],
bypassSession: true, timeoutMs: 10_000,
});
const home = discovered.stdout.trim();
if (discovered.exitCode !== 0 || discovered.timedOut || !home.startsWith("/") || /[\0\r\n]/.test(home)) {
throw new Error("runner_preconfigured_remote_home_unavailable");
}
const home = await readRemoteUserHome(remoteCommandRunner);
// Paths from the controller's account cannot select a remote account's config.
const hostPathKeys = new Set(["CODEX_HOME", "CLAUDE_CONFIG_DIR", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME"]);
const configured = configuredEnvironment(effectiveRunnerEnvironmentBase);
@@ -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);
@@ -658,6 +658,13 @@ export function resolvePaperclipRunnerProviderProfile(
};
}
export function supportsPaperclipRunnerPreconfiguredHome(adapterConfig: unknown, options: { companyId?: string } = {}): boolean {
const config = asRecord(adapterConfig);
const profile = resolvePaperclipRunnerProviderProfile(config, options);
return profile.provider === "codex" || (profile.provider === "acpx" && profile.acpxAgent === "claude"
&& (config.acpxPermissionMode === undefined || config.acpxPermissionMode === "approve-all"));
}
/**
* Project the operator-owned adapter configuration and a qualified stored
* profile into the closed native execution descriptor. Editable adapter
@@ -0,0 +1,11 @@
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
export async function readRemoteUserHome(runner: Pick<CommandManagedRuntimeRunner, "execute">): Promise<string> {
const result = await runner.execute({ command: "sh", args: ["-c", 'printf "%s\\n" "$HOME"', "paperclip-remote-home"],
bypassSession: true, timeoutMs: 10_000 });
const home = result.stdout.trim();
if (result.exitCode !== 0 || result.timedOut || !home.startsWith("/") || /[\0\r\n]/.test(home)) {
throw new Error("runner_preconfigured_remote_home_unavailable");
}
return home;
}
@@ -330,6 +330,31 @@ describe("Codex selected native account verification", () => {
expect(await readFile(join(home, "account-store.json"), "utf8")).toBe(auth);
} finally { await rm(home, { recursive: true, force: true }); }
});
it.each(["valid", "invalid home"])("probes the native SSH user's login without reading controller credentials (%s)", async mode => {
vi.stubEnv("HOME", "/controller-only/home");
vi.stubEnv("CODEX_HOME", "/controller-only/codex");
vi.stubEnv("OPENAI_API_KEY", "fixture-controller-key");
const readCredential = vi.spyOn(localCredentialFile, "readLocalAiCredentialFile");
sshExecute.mockImplementation(async command => ({ exitCode: 0, timedOut: false, stderr: "", stdout: command.args?.includes("paperclip-remote-home") ? (mode === "valid" ? "/home/remote-user\n" : "relative-home\n") : "" }));
nativeProbe.mockImplementation(async input => {
expect(input.environment.HOME).toBe("/home/remote-user");
expect(input.environment.CODEX_HOME).toBeUndefined();
expect(input.environment.OPENAI_API_KEY).toBeUndefined();
expect(input.transportOptions.homeMode).toBe("preconfigured");
expect(input.transportOptions.sourceCodexHome).toBe("");
expect(input.onCodexCredentialRefresh).toBeUndefined();
await input.onCleanupConfirmed();
return receipt("codex", "gpt-6.1-sol");
});
const result = await testNativeRunnerAuthentication({ ...sshContext, config: { homeMode: "preconfigured", env: { CODEX_HOME: "/controller-only/configured-home" } } }, "codex", "gpt-6.1-sol");
expect(result.status).toBe(mode === "valid" ? "pass" : "fail");
expect(readCredential).not.toHaveBeenCalled();
if (mode === "valid") expect(nativeProbe).toHaveBeenCalledOnce();
else expect(nativeProbe).not.toHaveBeenCalled();
expect(sshExecute.mock.calls.some(([command]) => JSON.stringify(command).includes("controller-only"))).toBe(false);
readCredential.mockRestore();
});
it.each(["linux-arm64", "linux-x64"])("uses task staging and the selected %s SSH daemon without a provider pack", async target => {
const selectedBinary = `/fixture/bin/${target}/paperclip-runnerd`;
selectedRemoteRunner.mockResolvedValue(selectedBinary);
@@ -9,6 +9,7 @@ import { ADAPTER_AUTH_MISSING_CHECK_CODE } from "@paperclipai/shared";
import { NativeEnvironmentProbeCleanupError, probeNativeRunnerEnvironment, resolveSourceCodexHome } from "../../vendor/paperclip-runner/index.js";
import { resolvePaperclipRunnerBinary, resolveRemotePaperclipRunnerBinary } from "./native-codex-runner.js";
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
import { readRemoteUserHome } from "./remote-user-home.js";
import { createNativeSshCommandRunner } from "./native-ssh-command-runner.js";
import { resolvePaperclipRunnerTransport } from "@paperclipai/adapter-utils/runner-connectivity";
import { createNativeRunnerExecutionDriver } from "./native-runner-execution-driver.js";
@@ -97,6 +98,12 @@ async function probeRemoteNativeCodex(options: {
const { createRemoteNativeArtifactPreparation, createRemoteRunnerProcessLauncher, stageRemoteRunnerFile, readRemoteRunnerState } = await import("./native-session-executor.js");
const runner = target.transport === "ssh" ? createNativeSshCommandRunner({ spec: target.spec, defaultCwd: target.remoteCwd }) : target.runner;
if (!runner) throw new Error("runner_transport_ineligible: remote process runner is unavailable");
const preconfigured = target.transport === "ssh" && options.context.config.homeMode === "preconfigured";
const environment = { ...options.environment };
if (preconfigured) {
delete environment.CODEX_HOME;
environment.HOME = await readRemoteUserHome(runner);
}
const id = crypto.randomUUID();
const runnerInstanceId = `setup-${id}`;
const ingress = target.transport === "sandbox" && target.effectiveCapabilities?.runnerWebSocketIngress === true;
@@ -122,14 +129,15 @@ async function probeRemoteNativeCodex(options: {
};
const runtimeDirectory = await realpath(await mkdtemp(join(tmpdir(), "paperclip-native-setup-")));
return probePreparedNativeRuntime(runtimeDirectory, async () => {
const sourceCodexHome = await prepareProbeCodexSource(runtimeDirectory, options.sourceCodexHome, options.sourceAuthJson);
const sourceCodexHome = preconfigured ? "" : await prepareProbeCodexSource(runtimeDirectory, options.sourceCodexHome, options.sourceAuthJson);
let remoteDirectoryCreated = false;
let signalSpawned!: () => void;
const spawned = new Promise<void>(resolve => { signalSpawned = resolve; });
return { runtimeDirectory: runtimeDirectory, provider: "codex", model: options.model, reasoningEffort: options.reasoningEffort,
workingDirectory: remoteWorkspace, environment: options.environment, timeoutMs: options.timeoutMs,
workingDirectory: remoteWorkspace, environment, timeoutMs: options.timeoutMs,
transportOptions: {
externallySandboxed: target.transport === "sandbox",
...(preconfigured ? { homeMode: "preconfigured" as const } : {}),
runnerBinary: controllerRunnerBinary, codexCommand: remoteCodexBinary, sourceCodexHome,
runnerFilesystemRoot: remoteFilesystemRoot,
prpIdentity: { runnerInstanceId, runId: id, environmentLeaseId: `setup-${id}`, normalizedSessionId: `setup-${id}`, turnId: `turn-${id}`, itemId: `item-${id}` },
@@ -157,6 +165,7 @@ async function probeRemoteNativeCodex(options: {
runnerProcessLauncher: createRemoteRunnerProcessLauncher({ target, runner, remoteBinary, stateDirectory: remoteStateDirectory,
onRunnerProcessSpawned: signalSpawned, processIdentityPath: posix.join(remoteStateDirectory, "runner-process.identity"), diagnosticsDirectory: posix.join(remoteRoot, "diagnostics"), runnerInstanceId,
ensureArtifact: async () => {
if (preconfigured) return;
for (const name of ["auth.json", "config.toml"] as const) {
const sourcePath = join(runtimeDirectory, "codex-home", name);
try { await stat(sourcePath); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
@@ -205,7 +214,7 @@ export async function testNativeRunnerAuthentication(context: AdapterEnvironment
let runtimeDirectory: string | undefined;
let sourceAuthJson: string | undefined;
try {
if (provider === "codex") {
if (provider === "codex" && !(context.executionTarget?.kind === "remote" && context.executionTarget.transport === "ssh" && context.config.homeMode === "preconfigured")) {
const { buildNativeProviderEnvironment } = await import("./native-session-executor.js");
sourceCodexHome = context.managedAiCredentialHome ?? resolveSourceCodexHome(buildNativeProviderEnvironment(environment));
}