mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 03:36:57 +01:00
Add experimental durable exe.dev agent environments
Keep one VM per environment with independent lease cgroups, persistent workspaces, immutable runner images, and an explicit experimental gate. Add live compatibility, recovery, browser-preview, and stress campaigns. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
e26d787928
commit
056703424a
56 files changed
+1782
-2062
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { createDb, environments } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { bindEnvironmentResource, readEnvironmentResourceBinding } from "../services/environment-resource-binding.js";
|
||||
import { assertExeEnvironmentEnabled } from "../services/exe-environment-gate.js";
|
||||
import { environmentService } from "../services/environments.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("durable exe.dev environment resource", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let stop: () => Promise<void>;
|
||||
beforeAll(async () => {
|
||||
const started = await startEmbeddedPostgresTestDatabase("exe-resource");
|
||||
db = createDb(started.connectionString); stop = started.stop;
|
||||
});
|
||||
afterAll(async () => { await stop?.(); });
|
||||
async function fixture() {
|
||||
const id = randomUUID(); const companyId = randomUUID();
|
||||
await db.insert(environments).values({ id, name: id, driver: "sandbox", config: { provider: "exe-dev" } });
|
||||
const binding = { provider: "exe-dev", companyId, resourceId: "test-vm", identity: randomUUID() };
|
||||
return { id, companyId, binding };
|
||||
}
|
||||
it("defaults off, gates API/runtime admission, and allows explicit opt-in", async () => {
|
||||
const environment = { driver: "sandbox", config: { provider: "exe-dev" } };
|
||||
await expect(assertExeEnvironmentEnabled(db, environment)).rejects.toThrow("Enable experimental");
|
||||
await expect(assertExeEnvironmentEnabled(db, { driver: "sandbox", config: { provider: "daytona" } })).resolves.toBeUndefined();
|
||||
await instanceSettingsService(db).updateExperimental({ enableExeEnvironments: true });
|
||||
await expect(assertExeEnvironmentEnabled(db, environment)).resolves.toBeUndefined();
|
||||
await instanceSettingsService(db).updateExperimental({ enableExeEnvironments: false });
|
||||
});
|
||||
it("atomically converges concurrent acquisitions on the same durable identity", async () => {
|
||||
const { id, companyId, binding } = await fixture();
|
||||
await Promise.all(Array.from({ length: 8 }, () => bindEnvironmentResource(db, id, companyId, binding)));
|
||||
expect(await readEnvironmentResourceBinding(db, id, companyId)).toEqual(binding);
|
||||
});
|
||||
it("allows only one identity when competing first acquisitions disagree", async () => {
|
||||
const { id, companyId, binding } = await fixture();
|
||||
const results = await Promise.allSettled([
|
||||
bindEnvironmentResource(db, id, companyId, binding),
|
||||
bindEnvironmentResource(db, id, companyId, { ...binding, identity: randomUUID() }),
|
||||
]);
|
||||
expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1);
|
||||
expect(results.filter((result) => result.status === "rejected")).toHaveLength(1);
|
||||
});
|
||||
it("survives metadata replacement and has no dependence on run lease rows", async () => {
|
||||
const { id, companyId, binding } = await fixture();
|
||||
await bindEnvironmentResource(db, id, companyId, binding);
|
||||
await environmentService(db).update(id, { metadata: { note: "operator edit" } });
|
||||
expect(await readEnvironmentResourceBinding(db, id, companyId)).toEqual(binding);
|
||||
await environmentService(db).update(id, { metadata: null });
|
||||
expect(await readEnvironmentResourceBinding(db, id, companyId)).toEqual(binding);
|
||||
});
|
||||
it("denies a different company and a replacement VM", async () => {
|
||||
const { id, companyId, binding } = await fixture();
|
||||
await bindEnvironmentResource(db, id, companyId, binding);
|
||||
await expect(readEnvironmentResourceBinding(db, id, randomUUID())).rejects.toThrow("another company");
|
||||
await expect(bindEnvironmentResource(db, id, companyId, { ...binding, identity: randomUUID() })).rejects.toThrow("identity changed");
|
||||
expect(await readEnvironmentResourceBinding(db, id, companyId)).toEqual(binding);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
PRP_V1_EVENT_TYPES,
|
||||
PRP_V2_EVENT_TYPES,
|
||||
REDACTED_EVENT_VALUE,
|
||||
redactAgentAdapterConfig,
|
||||
redactEventPayload,
|
||||
@@ -10,6 +11,16 @@ import {
|
||||
} from "../redaction.js";
|
||||
|
||||
describe("redaction", () => {
|
||||
it("preserves only the closed v2 event catalog in matching v2 envelopes", () => {
|
||||
const schema = JSON.parse(readFileSync(new URL("../../../packages/paperclip-runner/protocol/schemas/event-v2.schema.json", import.meta.url), "utf8"));
|
||||
expect([...PRP_V2_EVENT_TYPES].sort()).toEqual([...schema.properties.eventType.enum].sort());
|
||||
for (const eventType of PRP_V2_EVENT_TYPES) {
|
||||
const clean = redactEventPayload({ schema: "paperclip.prp.event.v2", schemaVersion: 2, eventType, apiKey: "sensitive" });
|
||||
expect(clean).toMatchObject({ schema: "paperclip.prp.event.v2", schemaVersion: 2, eventType, apiKey: REDACTED_EVENT_VALUE });
|
||||
}
|
||||
expect(redactEventPayload({ schema: "paperclip.prp.event.v2", schemaVersion: 2, eventType: "unknown.provider.credential" })?.eventType).toBe(REDACTED_EVENT_VALUE);
|
||||
expect(redactEventPayload({ schema: "paperclip.prp.event.v1", schemaVersion: 1, eventType: "session.goal.updated" })?.eventType).toBe(REDACTED_EVENT_VALUE);
|
||||
});
|
||||
it("keeps the discriminator allowlist in exact PRP v1 schema parity", () => {
|
||||
const schema = JSON.parse(
|
||||
readFileSync(
|
||||
|
||||
@@ -110,6 +110,7 @@ export const PAPERCLIP_PUBLIC_SCHEMA_IDS = new Set([
|
||||
"paperclip.prp.command.v1",
|
||||
"paperclip.prp.contract_manifest.v1",
|
||||
"paperclip.prp.event.v1",
|
||||
"paperclip.prp.event.v2",
|
||||
"paperclip.prp.fixture.v1",
|
||||
"paperclip.prp.identity.v1",
|
||||
"paperclip.prp.semantic_tool.v1",
|
||||
@@ -303,6 +304,10 @@ export const PRP_V1_EVENT_TYPES = new Set([
|
||||
"issue.status.decision.superseded",
|
||||
"run.terminal",
|
||||
]);
|
||||
export const PRP_V2_EVENT_TYPES = new Set([
|
||||
...[...PRP_V1_EVENT_TYPES].filter((type) => type !== "runner.backpressure" && type !== "semantic_tool.reconciled"),
|
||||
"session.capabilities.updated", "session.goal.snapshot", "session.goal.updated", "session.goal.cleared",
|
||||
]);
|
||||
const NATIVE_RUN_SPAN_SCHEMA = "paperclip.run-performance-span.v1";
|
||||
const NATIVE_RUN_SPAN_FIELDS = ["span", "parentSpan"] as const;
|
||||
const NATIVE_RUN_SPAN_NAMES = new Set([
|
||||
@@ -843,10 +848,9 @@ function isKnownPrpEventDiscriminator(
|
||||
): value is string {
|
||||
return (
|
||||
key === "eventType" &&
|
||||
container.schema === "paperclip.prp.event.v1" &&
|
||||
container.schemaVersion === 1 &&
|
||||
typeof value === "string" &&
|
||||
PRP_V1_EVENT_TYPES.has(value)
|
||||
((container.schema === "paperclip.prp.event.v1" && container.schemaVersion === 1 && PRP_V1_EVENT_TYPES.has(value)) ||
|
||||
(container.schema === "paperclip.prp.event.v2" && container.schemaVersion === 2 && PRP_V2_EVENT_TYPES.has(value)))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { assertExeEnvironmentEnabled } from "../services/exe-environment-gate.js";
|
||||
import { Router, type Request } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -311,6 +312,9 @@ async function assertPlatformProvisionedEnvironmentWritable(
|
||||
* Clearing (null/false) is allowed so stale markers can be removed.
|
||||
*/
|
||||
function assertNoClientPlatformProvisionedMarkers(metadata: unknown): void {
|
||||
if (isPlainRecord(metadata) && "environmentResourceBinding" in metadata) {
|
||||
throw unprocessable("metadata.environmentResourceBinding is managed by Paperclip");
|
||||
}
|
||||
if (!isCloudManagedInstance() || !isPlainRecord(metadata)) return;
|
||||
for (const key of PLATFORM_PROVISIONED_MARKER_KEYS) {
|
||||
if (metadata[key] !== undefined && metadata[key] !== null && metadata[key] !== false) {
|
||||
@@ -723,11 +727,12 @@ export function environmentRoutes(
|
||||
|
||||
router.get("/companies/:companyId/environments/capabilities", async (req, res) => {
|
||||
assertCanReadInstanceEnvironments(req);
|
||||
const pluginDrivers = await listReadyPluginEnvironmentDrivers({
|
||||
const exeEnabled = (await instanceSettings.getExperimental()).enableExeEnvironments;
|
||||
const pluginDrivers = (await listReadyPluginEnvironmentDrivers({
|
||||
db,
|
||||
workerManager: options.pluginWorkerManager,
|
||||
recoverMissingWorker: options.recoverMissingPluginWorker,
|
||||
});
|
||||
})).filter((driver) => driver.driverKey !== "exe-dev" || exeEnabled);
|
||||
res.json(getEnvironmentCapabilities(
|
||||
AGENT_ADAPTER_TYPES,
|
||||
{
|
||||
@@ -1015,6 +1020,7 @@ export function environmentRoutes(
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCanAccessInstanceEnvironments(req);
|
||||
assertNoClientPlatformProvisionedMarkers(req.body.metadata);
|
||||
await assertExeEnvironmentEnabled(db, req.body);
|
||||
if (req.body.driver === "local") {
|
||||
const existingLocal = await svc.list({ driver: "local" });
|
||||
if (existingLocal.length > 0) {
|
||||
@@ -1129,6 +1135,7 @@ export function environmentRoutes(
|
||||
res.status(404).json({ error: "Environment not found" });
|
||||
return;
|
||||
}
|
||||
await assertExeEnvironmentEnabled(db, { driver: req.body.driver ?? existing.driver, config: req.body.config ?? existing.config });
|
||||
await assertPlatformProvisionedEnvironmentWritable(existing, {
|
||||
patchBody: req.body,
|
||||
isForcedKubernetesExecution: async () =>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { assertExeEnvironmentEnabled } from "./exe-environment-gate.js";
|
||||
import type { Environment, EnvironmentProbeResult } from "@paperclipai/shared";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { ensureSshWorkspaceReady } from "@paperclipai/adapter-utils/ssh";
|
||||
@@ -23,6 +24,7 @@ export async function probeEnvironment(
|
||||
acquireSandboxRuntimeLease?: boolean;
|
||||
} = {},
|
||||
): Promise<EnvironmentProbeResult> {
|
||||
await assertExeEnvironmentEnabled(db, environment);
|
||||
const resolvedCompanyId = options.companyId ?? null;
|
||||
const parsed = options.resolvedConfig ?? (
|
||||
options.acquireSandboxRuntimeLease === true
|
||||
@@ -47,7 +49,7 @@ export async function probeEnvironment(
|
||||
}
|
||||
|
||||
if (parsed.driver === "sandbox") {
|
||||
if (options.acquireSandboxRuntimeLease) {
|
||||
if (options.acquireSandboxRuntimeLease && parsed.config.provider !== "exe-dev") {
|
||||
if (!resolvedCompanyId) {
|
||||
return {
|
||||
ok: false,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { environments, type Db } from "@paperclipai/db";
|
||||
import type { PluginEnvironmentResourceBinding } from "@paperclipai/plugin-sdk";
|
||||
import { conflict } from "../errors.js";
|
||||
|
||||
export function parseResourceBinding(value: unknown): PluginEnvironmentResourceBinding | undefined {
|
||||
if (value == null) return undefined;
|
||||
const binding = value as PluginEnvironmentResourceBinding;
|
||||
if (binding.provider !== "exe-dev" || typeof binding.companyId !== "string" || !binding.companyId || typeof binding.resourceId !== "string" || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(binding.resourceId) || typeof binding.identity !== "string" || !/^[a-f0-9-]{36}$/.test(binding.identity)) {
|
||||
throw conflict("Invalid durable environment resource binding");
|
||||
}
|
||||
return { provider: binding.provider, companyId: binding.companyId, resourceId: binding.resourceId, identity: binding.identity };
|
||||
}
|
||||
|
||||
export async function readEnvironmentResourceBinding(db: Db, environmentId: string, companyId: string) {
|
||||
// Environments are instance-scoped; the durable binding carries ownership.
|
||||
// Lease insertion separately rechecks the existing company binding contract.
|
||||
const [row] = await db.select({ metadata: environments.metadata }).from(environments).where(eq(environments.id, environmentId));
|
||||
const binding = parseResourceBinding(row?.metadata?.environmentResourceBinding);
|
||||
if (binding && binding.companyId !== companyId) throw conflict("Durable VM belongs to another company");
|
||||
return binding;
|
||||
}
|
||||
|
||||
/** Atomic compare-and-set: concurrent first acquisitions must agree on identity. */
|
||||
export async function bindEnvironmentResource(db: Db, environmentId: string, companyId: string, value: unknown) {
|
||||
const binding = parseResourceBinding(value);
|
||||
if (!binding || binding.companyId !== companyId) throw conflict("Provider did not attest a company-scoped durable VM binding");
|
||||
const encoded = JSON.stringify(binding);
|
||||
const rows = await db.update(environments).set({
|
||||
metadata: sql`coalesce(${environments.metadata}, '{}'::jsonb) || jsonb_build_object('environmentResourceBinding', ${encoded}::jsonb)`,
|
||||
updatedAt: new Date(),
|
||||
}).where(and(eq(environments.id, environmentId), sql`(${environments.metadata}->'environmentResourceBinding' IS NULL OR ${environments.metadata}->'environmentResourceBinding' = ${encoded}::jsonb)`)).returning({ id: environments.id });
|
||||
if (rows.length !== 1) throw conflict("Durable VM identity changed; explicit recovery to a new environment is required");
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readEnvironmentResourceBinding, bindEnvironmentResource } from "./environment-resource-binding.js";
|
||||
import { assertExeEnvironmentEnabled } from "./exe-environment-gate.js";
|
||||
import { remoteTerminationReceipt } from "./remote-execution-termination.js";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
@@ -1100,6 +1102,7 @@ function createLocalEnvironmentDriver(db: Db): EnvironmentRuntimeDriver {
|
||||
driver: "local",
|
||||
|
||||
async acquireRunLease(input) {
|
||||
await assertExeEnvironmentEnabled(db, input.environment);
|
||||
return await environmentsSvc.acquireLease({
|
||||
companyId: input.companyId,
|
||||
environmentId: input.environment.id,
|
||||
@@ -1154,6 +1157,7 @@ function createSshEnvironmentDriver(db: Db): EnvironmentRuntimeDriver {
|
||||
driver: "ssh",
|
||||
|
||||
async acquireRunLease(input) {
|
||||
await assertExeEnvironmentEnabled(db, input.environment);
|
||||
const parsed = await resolveEnvironmentDriverConfigForRuntime(db, input.companyId, input.environment, {
|
||||
issueId: input.issueId,
|
||||
heartbeatRunId: input.heartbeatRunId,
|
||||
@@ -1752,6 +1756,7 @@ function createSandboxEnvironmentDriver(
|
||||
driver: "sandbox",
|
||||
|
||||
async acquireRunLease(input) {
|
||||
await assertExeEnvironmentEnabled(db, input.environment);
|
||||
const storedParsed = parseEnvironmentDriverConfig(input.environment);
|
||||
const parsed = await resolveEnvironmentDriverConfigForRuntime(db, input.companyId, input.environment, {
|
||||
issueId: input.issueId,
|
||||
@@ -1996,6 +2001,9 @@ function createSandboxEnvironmentDriver(
|
||||
});
|
||||
}
|
||||
}
|
||||
const resourceBinding = parsed.config.provider === "exe-dev"
|
||||
? await readEnvironmentResourceBinding(db, input.environment.id, input.companyId)
|
||||
: undefined;
|
||||
const acquiredLease = providerLease ?? await pluginWorkerManager.call(
|
||||
pluginProvider.resolved.plugin.id,
|
||||
"environmentAcquireLease",
|
||||
@@ -2005,6 +2013,7 @@ function createSandboxEnvironmentDriver(
|
||||
environmentId: input.environment.id,
|
||||
issueId: input.issueId,
|
||||
config: workerConfig,
|
||||
...(resourceBinding ? { resourceBinding } : {}),
|
||||
// Plugin SDK requires a string; ad-hoc test leases use a fresh
|
||||
// UUID so providers that validate or persist the runId still see
|
||||
// a well-formed identifier.
|
||||
@@ -2085,6 +2094,9 @@ function createSandboxEnvironmentDriver(
|
||||
...(reusableScope ? { reusableSandboxLease: reusableScope } : {}),
|
||||
};
|
||||
try {
|
||||
if (parsed.config.provider === "exe-dev") {
|
||||
await bindEnvironmentResource(db, input.environment.id, input.companyId, acquiredLease.metadata?.environmentResourceBinding);
|
||||
}
|
||||
return await environmentsSvc.acquireLease({
|
||||
companyId: input.companyId,
|
||||
environmentId: input.environment.id,
|
||||
@@ -3333,6 +3345,7 @@ function createPluginEnvironmentDriver(
|
||||
driver: "plugin",
|
||||
|
||||
async acquireRunLease(input) {
|
||||
await assertExeEnvironmentEnabled(db, input.environment);
|
||||
const parsed = parseEnvironmentDriverConfig(input.environment);
|
||||
if (parsed.driver !== "plugin") {
|
||||
throw new Error(`Expected plugin environment config for driver "${input.environment.driver}".`);
|
||||
|
||||
@@ -1129,9 +1129,14 @@ export function environmentService(db: Db) {
|
||||
values.metadata = withoutManagedEnvironmentArchiveToken(existingMetadata);
|
||||
}
|
||||
|
||||
// Client metadata edits cannot remove or overwrite the host's durable VM
|
||||
// identity. Merge from the current row in SQL to avoid a first-acquire race.
|
||||
const metadataUpdate = values.metadata !== undefined
|
||||
? sql`CASE WHEN ${environments.metadata}->'environmentResourceBinding' IS NOT NULL THEN coalesce(${values.metadata === null ? null : JSON.stringify(values.metadata)}::jsonb, '{}'::jsonb) || jsonb_build_object('environmentResourceBinding', ${environments.metadata}->'environmentResourceBinding') ELSE ${values.metadata === null ? null : JSON.stringify(values.metadata)}::jsonb END`
|
||||
: undefined;
|
||||
const row = await writeDb
|
||||
.update(environments)
|
||||
.set(values)
|
||||
.set({ ...values, ...(metadataUpdate ? { metadata: metadataUpdate } : {}) })
|
||||
.where(eq(environments.id, id))
|
||||
.returning()
|
||||
.then((rows) => rows[0] ?? null)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { forbidden } from "../errors.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
|
||||
export function isExeEnvironment(environment: { driver: string; config?: unknown }): boolean {
|
||||
const config = environment.config as Record<string, unknown> | null;
|
||||
return (environment.driver === "sandbox" && config?.provider === "exe-dev") ||
|
||||
(environment.driver === "plugin" && config?.driverKey === "exe-dev");
|
||||
}
|
||||
|
||||
/** Gate new work, never the teardown of an already acquired lease. */
|
||||
export async function assertExeEnvironmentEnabled(db: Db, environment: { driver: string; config?: unknown }) {
|
||||
if (environment.driver === "plugin" && isExeEnvironment(environment)) {
|
||||
throw forbidden("Configure exe.dev using the sandbox environment driver.");
|
||||
}
|
||||
if (isExeEnvironment(environment) && !(await instanceSettingsService(db).getExperimental()).enableExeEnvironments) {
|
||||
throw forbidden("Enable experimental exe.dev environments in instance settings before using this environment.");
|
||||
}
|
||||
}
|
||||
@@ -224,6 +224,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
if (parsed.success) {
|
||||
return {
|
||||
enableEnvironments: parsed.data.enableEnvironments ?? false,
|
||||
enableExeEnvironments: parsed.data.enableExeEnvironments ?? false,
|
||||
enableNativeRunner: parsed.data.enableNativeRunner ?? true,
|
||||
enableManagedSandboxOnly: parsed.data.enableManagedSandboxOnly ?? false,
|
||||
enableIsolatedWorkspaces: parsed.data.enableIsolatedWorkspaces ?? false,
|
||||
@@ -267,6 +268,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
}
|
||||
return {
|
||||
enableEnvironments: false,
|
||||
enableExeEnvironments: false,
|
||||
enableNativeRunner: true,
|
||||
enableManagedSandboxOnly: false,
|
||||
enableIsolatedWorkspaces: false,
|
||||
|
||||
Reference in new issue
Block a user