mirror of
https://github.com/alkimake/paperclip.git
synced 2026-06-16 19:00:38 +09:00
Add SSH environment support (#4358)
## Thinking Path > - Paperclip orchestrates AI agents for zero-human companies > - The environments subsystem already models execution environments, but before this branch there was no end-to-end SSH-backed runtime path for agents to actually run work against a remote box > - That meant agents could be configured around environment concepts without a reliable way to execute adapter sessions remotely, sync workspace state, and preserve run context across supported adapters > - We also need environment selection to participate in normal Paperclip control-plane behavior: agent defaults, project/issue selection, route validation, and environment probing > - Because this capability is still experimental, the UI surface should be easy to hide and easy to remove later without undoing the underlying implementation > - This pull request adds SSH environment execution support across the runtime, adapters, routes, schema, and tests, then puts the visible environment-management UI behind an experimental flag > - The benefit is that we can validate real SSH-backed agent execution now while keeping the user-facing controls safely gated until the feature is ready to come out of experimentation ## What Changed - Added SSH-backed execution target support in the shared adapter runtime, including remote workspace preparation, skill/runtime asset sync, remote session handling, and workspace restore behavior after runs. - Added SSH execution coverage for supported local adapters, plus remote execution tests across Claude, Codex, Cursor, Gemini, OpenCode, and Pi. - Added environment selection and environment-management backend support needed for SSH execution, including route/service work, validation, probing, and agent default environment persistence. - Added CLI support for SSH environment lab verification and updated related docs/tests. - Added the `enableEnvironments` experimental flag and gated the environment UI behind it on company settings, agent configuration, and project configuration surfaces. ## Verification - `pnpm exec vitest run packages/adapters/claude-local/src/server/execute.remote.test.ts packages/adapters/cursor-local/src/server/execute.remote.test.ts packages/adapters/gemini-local/src/server/execute.remote.test.ts packages/adapters/opencode-local/src/server/execute.remote.test.ts packages/adapters/pi-local/src/server/execute.remote.test.ts` - `pnpm exec vitest run server/src/__tests__/environment-routes.test.ts` - `pnpm exec vitest run server/src/__tests__/instance-settings-routes.test.ts` - `pnpm exec vitest run ui/src/lib/new-agent-hire-payload.test.ts ui/src/lib/new-agent-runtime-config.test.ts` - `pnpm -r typecheck` - `pnpm build` - Manual verification on a branch-local dev server: - enabled the experimental flag - created an SSH environment - created a Linux Claude agent using that environment - confirmed a run executed on the Linux box and synced workspace changes back ## Risks - Medium: this touches runtime execution flow across multiple adapters, so regressions would likely show up in remote session setup, workspace sync, or environment selection precedence. - The UI flag reduces exposure, but the underlying runtime and route changes are still substantial and rely on migration correctness. - The change set is broad across adapters, control-plane services, migrations, and UI gating, so review should pay close attention to environment-selection precedence and remote workspace lifecycle behavior. ## Model Used - OpenAI Codex via Paperclip's local Codex adapter, GPT-5-class coding model with tool use and code execution in the local repo workspace. The local adapter does not surface a more specific public model version string in this branch workflow. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
parent
f98c348e2b
commit
e4995bbb1c
95 changed files with 10162 additions and 315 deletions
237
server/src/services/environment-config.ts
Normal file
237
server/src/services/environment-config.ts
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type {
|
||||
Environment,
|
||||
EnvironmentDriver,
|
||||
LocalEnvironmentConfig,
|
||||
SshEnvironmentConfig,
|
||||
} from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { parseObject } from "../adapters/utils.js";
|
||||
import { secretService } from "./secrets.js";
|
||||
|
||||
const secretRefSchema = z.object({
|
||||
type: z.literal("secret_ref"),
|
||||
secretId: z.string().uuid(),
|
||||
version: z.union([z.literal("latest"), z.number().int().positive()]).optional().default("latest"),
|
||||
}).strict();
|
||||
|
||||
const sshEnvironmentConfigSchema = z.object({
|
||||
host: z.string({ required_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({ required_error: "SSH environments require a username." }).trim().min(1, "SSH environments require a username."),
|
||||
remoteWorkspacePath: z
|
||||
.string({ required_error: "SSH environments require a remote workspace path." })
|
||||
.trim()
|
||||
.min(1, "SSH environments require a remote workspace path.")
|
||||
.refine((value) => value.startsWith("/"), "SSH remote workspace path must be absolute."),
|
||||
privateKey: z.null().optional().default(null),
|
||||
privateKeySecretRef: secretRefSchema.optional().nullable().default(null),
|
||||
knownHosts: z
|
||||
.string()
|
||||
.trim()
|
||||
.optional()
|
||||
.nullable()
|
||||
.transform((value) => (value && value.length > 0 ? value : null)),
|
||||
strictHostKeyChecking: z.boolean().optional().default(true),
|
||||
}).strict();
|
||||
|
||||
const sshEnvironmentConfigProbeSchema = sshEnvironmentConfigSchema.extend({
|
||||
privateKey: z
|
||||
.string()
|
||||
.trim()
|
||||
.optional()
|
||||
.nullable()
|
||||
.transform((value) => (value && value.length > 0 ? value : null)),
|
||||
}).strict();
|
||||
|
||||
const sshEnvironmentConfigPersistenceSchema = sshEnvironmentConfigProbeSchema;
|
||||
|
||||
export type ParsedEnvironmentConfig =
|
||||
| { driver: "local"; config: LocalEnvironmentConfig }
|
||||
| { driver: "ssh"; config: SshEnvironmentConfig };
|
||||
|
||||
function toErrorMessage(error: z.ZodError) {
|
||||
const first = error.issues[0];
|
||||
if (!first) return "Invalid environment config.";
|
||||
return first.message;
|
||||
}
|
||||
|
||||
function secretName(input: {
|
||||
environmentName: string;
|
||||
driver: EnvironmentDriver;
|
||||
field: string;
|
||||
}) {
|
||||
const slug = input.environmentName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 48) || "environment";
|
||||
return `environment-${input.driver}-${slug}-${input.field}-${randomUUID().slice(0, 8)}`;
|
||||
}
|
||||
|
||||
async function createEnvironmentSecret(input: {
|
||||
db: Db;
|
||||
companyId: string;
|
||||
environmentName: string;
|
||||
driver: EnvironmentDriver;
|
||||
field: string;
|
||||
value: string;
|
||||
actor?: { userId?: string | null; agentId?: string | null };
|
||||
}) {
|
||||
const created = await secretService(input.db).create(
|
||||
input.companyId,
|
||||
{
|
||||
name: secretName(input),
|
||||
provider: "local_encrypted",
|
||||
value: input.value,
|
||||
description: `Secret for ${input.environmentName} ${input.field}.`,
|
||||
},
|
||||
input.actor,
|
||||
);
|
||||
return {
|
||||
type: "secret_ref" as const,
|
||||
secretId: created.id,
|
||||
version: "latest" as const,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeEnvironmentConfig(input: {
|
||||
driver: EnvironmentDriver;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
}): Record<string, unknown> {
|
||||
if (input.driver === "local") {
|
||||
return { ...parseObject(input.config) };
|
||||
}
|
||||
|
||||
if (input.driver === "ssh") {
|
||||
const parsed = sshEnvironmentConfigSchema.safeParse(parseObject(input.config));
|
||||
if (!parsed.success) {
|
||||
throw unprocessable(toErrorMessage(parsed.error), {
|
||||
issues: parsed.error.issues,
|
||||
});
|
||||
}
|
||||
return parsed.data satisfies SshEnvironmentConfig;
|
||||
}
|
||||
|
||||
throw unprocessable(`Unsupported environment driver "${input.driver}".`);
|
||||
}
|
||||
|
||||
export function normalizeEnvironmentConfigForProbe(input: {
|
||||
driver: EnvironmentDriver;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
}): Record<string, unknown> {
|
||||
if (input.driver === "ssh") {
|
||||
const parsed = sshEnvironmentConfigProbeSchema.safeParse(parseObject(input.config));
|
||||
if (!parsed.success) {
|
||||
throw unprocessable(toErrorMessage(parsed.error), {
|
||||
issues: parsed.error.issues,
|
||||
});
|
||||
}
|
||||
return parsed.data satisfies SshEnvironmentConfig;
|
||||
}
|
||||
|
||||
return normalizeEnvironmentConfig(input);
|
||||
}
|
||||
|
||||
export async function normalizeEnvironmentConfigForPersistence(input: {
|
||||
db: Db;
|
||||
companyId: string;
|
||||
environmentName: string;
|
||||
driver: EnvironmentDriver;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
actor?: { userId?: string | null; agentId?: string | null };
|
||||
}): Promise<Record<string, unknown>> {
|
||||
if (input.driver === "ssh") {
|
||||
const parsed = sshEnvironmentConfigPersistenceSchema.safeParse(parseObject(input.config));
|
||||
if (!parsed.success) {
|
||||
throw unprocessable(toErrorMessage(parsed.error), {
|
||||
issues: parsed.error.issues,
|
||||
});
|
||||
}
|
||||
const secrets = secretService(input.db);
|
||||
const { privateKey, ...stored } = parsed.data;
|
||||
let nextPrivateKeySecretRef = stored.privateKeySecretRef;
|
||||
if (privateKey) {
|
||||
nextPrivateKeySecretRef = await createEnvironmentSecret({
|
||||
db: input.db,
|
||||
companyId: input.companyId,
|
||||
environmentName: input.environmentName,
|
||||
driver: input.driver,
|
||||
field: "private-key",
|
||||
value: privateKey,
|
||||
actor: input.actor,
|
||||
});
|
||||
if (
|
||||
stored.privateKeySecretRef &&
|
||||
stored.privateKeySecretRef.secretId !== nextPrivateKeySecretRef.secretId
|
||||
) {
|
||||
await secrets.remove(stored.privateKeySecretRef.secretId);
|
||||
}
|
||||
}
|
||||
return {
|
||||
...stored,
|
||||
privateKey: null,
|
||||
privateKeySecretRef: nextPrivateKeySecretRef,
|
||||
} satisfies SshEnvironmentConfig;
|
||||
}
|
||||
|
||||
return normalizeEnvironmentConfig({
|
||||
driver: input.driver,
|
||||
config: input.config,
|
||||
});
|
||||
}
|
||||
|
||||
export async function resolveEnvironmentDriverConfigForRuntime(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
environment: Pick<Environment, "driver" | "config">,
|
||||
): Promise<ParsedEnvironmentConfig> {
|
||||
const parsed = parseEnvironmentDriverConfig(environment);
|
||||
if (parsed.driver === "ssh" && parsed.config.privateKeySecretRef) {
|
||||
return {
|
||||
driver: "ssh",
|
||||
config: {
|
||||
...parsed.config,
|
||||
privateKey: await secretService(db).resolveSecretValue(
|
||||
companyId,
|
||||
parsed.config.privateKeySecretRef.secretId,
|
||||
parsed.config.privateKeySecretRef.version ?? "latest",
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function readSshEnvironmentPrivateKeySecretId(
|
||||
environment: Pick<Environment, "driver" | "config">,
|
||||
): string | null {
|
||||
if (environment.driver !== "ssh") return null;
|
||||
const parsed = sshEnvironmentConfigSchema.safeParse(parseObject(environment.config));
|
||||
if (!parsed.success) return null;
|
||||
return parsed.data.privateKeySecretRef?.secretId ?? null;
|
||||
}
|
||||
|
||||
export function parseEnvironmentDriverConfig(
|
||||
environment: Pick<Environment, "driver" | "config">,
|
||||
): ParsedEnvironmentConfig {
|
||||
if (environment.driver === "local") {
|
||||
return {
|
||||
driver: "local",
|
||||
config: { ...parseObject(environment.config) },
|
||||
};
|
||||
}
|
||||
|
||||
if (environment.driver === "ssh") {
|
||||
const parsed = sshEnvironmentConfigSchema.parse(parseObject(environment.config));
|
||||
return {
|
||||
driver: "ssh",
|
||||
config: parsed,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported environment driver "${environment.driver}".`);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue