diff --git a/src/main/environment-providers/environment-provider-driver-contract.test-support.ts b/src/main/environment-providers/environment-provider-driver-contract.test-support.ts new file mode 100644 index 00000000000..0ca2c695584 --- /dev/null +++ b/src/main/environment-providers/environment-provider-driver-contract.test-support.ts @@ -0,0 +1,105 @@ +// Shared lifecycle contract every EnvironmentProviderDriver must pass; drivers call it from their test. +import { describe, expect, it } from 'vitest' +import { + getEphemeralVmRecipeResultConnection, + getEphemeralVmRecipeResultProjectRoot, + isAbsoluteRuntimePath +} from '../../shared/ephemeral-vm-recipes' +import { + ENVIRONMENT_PROVIDER_ERROR_CODES, + isEnvironmentProviderError, + type EnvironmentCreateSpec, + type EnvironmentProviderDriver, + type EnvironmentReady +} from './environment-provider-driver' + +export type EnvironmentProviderDriverContractHarness = { + driver: EnvironmentProviderDriver + /** Ids the backing provider still holds; destroy must leave none behind. */ + liveEnvironmentIds: () => Promise + /** A fresh driver over the same backing provider, as after an Orca restart. */ + reopenDriver: () => EnvironmentProviderDriver +} + +// Handles are persisted with the runtime record, so later calls only ever see the JSON form. +function reload(handle: T): T { + return JSON.parse(JSON.stringify(handle)) +} + +export function runEnvironmentProviderDriverContract( + name: string, + makeHarness: () => Promise, + spec: (workspaceId: string) => EnvironmentCreateSpec = (workspaceId) => ({ workspaceId }) +): void { + describe(`${name} satisfies the environment provider driver contract`, () => { + function expectReady(driver: EnvironmentProviderDriver, ready: EnvironmentReady): void { + expect(ready.handle.driverId).toBe(driver.id) + expect(ready.handle.environmentId).not.toBe('') + expect(['orca-server', 'ssh']).toContain( + getEphemeralVmRecipeResultConnection(ready.result).type + ) + expect(isAbsoluteRuntimePath(getEphemeralVmRecipeResultProjectRoot(ready.result))).toBe(true) + if (driver.capabilities.maxSessionMs !== null) { + expect(ready.session.deadlineAt).not.toBeNull() + expect(ready.session.deadlineAt! - ready.session.startedAt).toBeLessThanOrEqual( + driver.capabilities.maxSessionMs + ) + } + } + + it('creates, suspends, resumes and destroys one environment without leaking it', async () => { + const { driver, liveEnvironmentIds, reopenDriver } = await makeHarness() + const phases: string[] = [] + const created = await driver.create(spec('ws-contract-1'), { + onProgress: ({ phase }) => phases.push(phase) + }) + expectReady(driver, created) + expect(phases.length).toBeGreaterThan(0) + expect(await liveEnvironmentIds()).toContain(created.handle.environmentId) + expect((await driver.status(created.handle)).status).toBe('running') + + const suspended = await driver.suspend(created.handle) + expect(suspended.status).toBe('suspended') + expect((await driver.status(created.handle)).status).toBe('suspended') + + const resumed = await driver.resume(created.handle) + expectReady(driver, resumed) + expect(resumed.handle.environmentId).toBe(created.handle.environmentId) + expect((await driver.status(created.handle)).status).toBe('running') + + await driver.destroy(created.handle) + expect(await liveEnvironmentIds()).not.toContain(created.handle.environmentId) + // Idempotent: cleanup retries after a lost response or a restart must not fail. + await reopenDriver().destroy(reload(created.handle)) + }) + + it('refuses to bring back a destroyed environment, even after a restart', async () => { + const { driver, liveEnvironmentIds, reopenDriver } = await makeHarness() + const created = await driver.create(spec('ws-contract-2')) + await driver.destroy(created.handle) + const error = await reopenDriver() + .resume(reload(created.handle)) + .then( + () => null, + (caught: unknown) => caught + ) + expect(isEnvironmentProviderError(error)).toBe(true) + expect(await liveEnvironmentIds()).not.toContain(created.handle.environmentId) + }) + + it('rejects a cancelled create with a catalogued error and leaks nothing', async () => { + const { driver, liveEnvironmentIds } = await makeHarness() + const controller = new AbortController() + controller.abort() + const error = await driver.create(spec('ws-contract-3'), { signal: controller.signal }).then( + () => null, + (caught: unknown) => caught + ) + expect(isEnvironmentProviderError(error)).toBe(true) + expect(ENVIRONMENT_PROVIDER_ERROR_CODES).toContain( + isEnvironmentProviderError(error) ? error.code : null + ) + expect(await liveEnvironmentIds()).toEqual([]) + }) + }) +} diff --git a/src/main/environment-providers/environment-provider-driver.ts b/src/main/environment-providers/environment-provider-driver.ts new file mode 100644 index 00000000000..7edfb2d1310 --- /dev/null +++ b/src/main/environment-providers/environment-provider-driver.ts @@ -0,0 +1,125 @@ +// One lifecycle seam for VM-backed workspaces: every environment provider answers the same calls, +// and capability flags (not provider ids) decide what the UI offers. +import type { EphemeralVmRecipeResult, JsonValue } from '../../shared/ephemeral-vm-recipes' + +export type EnvironmentProviderCapabilities = Readonly<{ + /** Suspend keeps memory and processes; false means suspend/resume is a reboot from disk. */ + memoryPause: boolean + /** Hard per-session cap enforced by the provider; null when sessions are unbounded. */ + maxSessionMs: number | null + /** The filesystem (worktree, auth homes, orcad identity) survives suspend. */ + fsPersistOnStop: boolean + /** Orca-owned idle stop; null when the provider has none. */ + idleStopMs: number | null +}> + +export type EnvironmentProviderPhase = + | 'provisioning' + | 'booting' + | 'connecting' + | 'suspending' + | 'resuming' + | 'destroying' + +export type EnvironmentProviderCallContext = { + signal?: AbortSignal + onProgress?: (progress: { phase: EnvironmentProviderPhase; message?: string }) => void +} + +export type EnvironmentCreateSpec = { + /** Orca's workspace id; one environment per workspace. */ + workspaceId: string + workspaceName?: string + projectId?: string + machineSize?: string + region?: string + repo?: { url: string; ref?: string } +} + +/** Persisted with the runtime record; `driverState` is opaque to everything but the driver. */ +export type EnvironmentHandle = { + driverId: string + environmentId: string + driverState: Record +} + +export type EnvironmentSessionInfo = { + startedAt: number + /** When the provider will end this session regardless of activity. */ + deadlineAt: number | null +} + +export type EnvironmentStatus = + | 'provisioning' + | 'running' + | 'suspending' + | 'suspended' + | 'resuming' + | 'destroying' + | 'destroyed' + | 'failed' + +export type EnvironmentStatusSnapshot = { + status: EnvironmentStatus + session: EnvironmentSessionInfo | null +} + +export type EnvironmentReady = { + handle: EnvironmentHandle + /** Same document a shell recipe prints, so runtime records, pairing and resume keep one path. */ + result: EphemeralVmRecipeResult + session: EnvironmentSessionInfo +} + +export type EnvironmentProviderDriver = { + readonly id: string + readonly capabilities: EnvironmentProviderCapabilities + create( + spec: EnvironmentCreateSpec, + ctx?: EnvironmentProviderCallContext + ): Promise + resume(handle: EnvironmentHandle, ctx?: EnvironmentProviderCallContext): Promise + suspend( + handle: EnvironmentHandle, + ctx?: EnvironmentProviderCallContext + ): Promise + /** Idempotent: an environment that is already gone resolves. */ + destroy(handle: EnvironmentHandle, ctx?: EnvironmentProviderCallContext): Promise + status( + handle: EnvironmentHandle, + ctx?: EnvironmentProviderCallContext + ): Promise +} + +export const ENVIRONMENT_PROVIDER_ERROR_CODES = [ + 'unauthorized', + 'not_found', + 'conflict', + 'invalid_request', + 'unavailable', + 'timeout', + 'aborted', + 'invalid_response' +] as const + +export type EnvironmentProviderErrorCode = (typeof ENVIRONMENT_PROVIDER_ERROR_CODES)[number] + +export class EnvironmentProviderError extends Error { + readonly code: EnvironmentProviderErrorCode + /** Machine-readable provider detail, e.g. the Orca failure-copy code behind the message. */ + readonly reason: string | null + + constructor(code: EnvironmentProviderErrorCode, message: string, reason: string | null = null) { + super(message) + this.name = 'EnvironmentProviderError' + this.code = code + this.reason = reason + } +} + +export function isEnvironmentProviderError( + error: unknown, + code?: EnvironmentProviderErrorCode +): error is EnvironmentProviderError { + return error instanceof EnvironmentProviderError && (code === undefined || error.code === code) +} diff --git a/src/main/environment-providers/shell-recipe-driver.test.ts b/src/main/environment-providers/shell-recipe-driver.test.ts new file mode 100644 index 00000000000..d7cafb409b5 --- /dev/null +++ b/src/main/environment-providers/shell-recipe-driver.test.ts @@ -0,0 +1,68 @@ +import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach } from 'vitest' +import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import { runEnvironmentProviderDriverContract } from './environment-provider-driver-contract.test-support' +import { ShellRecipeDriver } from './shell-recipe-driver' + +const tmpRoots: string[] = [] + +afterEach(() => { + for (const root of tmpRoots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +// A recipe whose "VMs" are files in a state dir, so the contract can see what destroy left behind. +function makeFileBackedRecipe(): { repoPath: string; stateDir: string; recipe: OrcaVmRecipe } { + const repoPath = mkdtempSync(join(tmpdir(), 'orca-shell-recipe-driver-')) + tmpRoots.push(repoPath) + const stateDir = join(repoPath, 'vms') + mkdirSync(stateDir) + const pairingCode = encodePairingOffer({ + v: PAIRING_OFFER_VERSION, + endpoint: 'wss://vm.example.com', + deviceToken: 'token', + publicKeyB64: 'public-key' + }) + const vmFile = `require('node:path').join(${JSON.stringify(stateDir)}, process.env.ORCA_VM_INSTANCE_ID)` + const printResult = `console.log(JSON.stringify({ schemaVersion: 1, pairingCode: ${JSON.stringify(pairingCode)}, projectRoot: '/workspace/repo' }))` + const scripts = { + create: `require('node:fs').writeFileSync(${vmFile}, 'running'); ${printResult}`, + suspend: `require('node:fs').writeFileSync(${vmFile}, 'suspended')`, + // Like a real provider: a destroyed VM cannot be woken. + resume: `const fs = require('node:fs'); if (!fs.existsSync(${vmFile})) process.exit(1); fs.writeFileSync(${vmFile}, 'running'); ${printResult}`, + destroy: `require('node:fs').rmSync(${vmFile}, { force: true })` + } + const commands = Object.fromEntries( + Object.entries(scripts).map(([mode, source]) => { + const scriptPath = join(repoPath, `${mode}.js`) + writeFileSync(scriptPath, source) + return [mode, `"${process.execPath}" "${scriptPath}"`] + }) + ) + return { + repoPath, + stateDir, + recipe: { + id: 'file-backed', + name: 'File-backed VM', + create: commands.create, + suspend: commands.suspend, + resume: commands.resume, + destroy: commands.destroy + } + } +} + +runEnvironmentProviderDriverContract('ShellRecipeDriver', async () => { + const { repoPath, stateDir, recipe } = makeFileBackedRecipe() + return { + driver: new ShellRecipeDriver(recipe, repoPath), + liveEnvironmentIds: async () => readdirSync(stateDir), + reopenDriver: () => new ShellRecipeDriver(recipe, repoPath) + } +}) diff --git a/src/main/environment-providers/shell-recipe-driver.ts b/src/main/environment-providers/shell-recipe-driver.ts new file mode 100644 index 00000000000..4d962fbc744 --- /dev/null +++ b/src/main/environment-providers/shell-recipe-driver.ts @@ -0,0 +1,286 @@ +// orca.yaml environment recipes and plugin VM recipes as an environment provider: each lifecycle +// call runs the recipe's shell step, exactly as the runtime service did before the driver seam. +import { z } from 'zod' +import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import { + EphemeralVmRecipeResultSchema, + type EphemeralVmRecipeResult, + type JsonValue +} from '../../shared/ephemeral-vm-recipes' +import { + runEphemeralVmRecipeCleanup, + runEphemeralVmRecipeResume, + runEphemeralVmRecipeStart, + runEphemeralVmRecipeSuspend, + type EphemeralVmRecipeCleanupArgs, + type EphemeralVmRecipeContext, + type EphemeralVmRecipeLifecycleArgs, + type EphemeralVmRecipeStartArgs +} from '../../shared/ephemeral-vm-recipe-runner' +import { EPHEMERAL_VM_FAILURE_COPY } from '../../shared/ephemeral-vm-failure-copy' +import { getProvisionedRootResumeIntegrityError } from '../ephemeral-vm/resume-integrity' +import { + EnvironmentProviderError, + isEnvironmentProviderError, + type EnvironmentCreateSpec, + type EnvironmentHandle, + type EnvironmentProviderCallContext, + type EnvironmentProviderCapabilities, + type EnvironmentProviderDriver, + type EnvironmentReady, + type EnvironmentStatus, + type EnvironmentStatusSnapshot +} from './environment-provider-driver' + +export const SHELL_RECIPE_DRIVER_ID = 'shell-recipe' + +type RecipeStepArgs = Omit + +type RecipeStepFailure = { + error?: string + errorCode?: string + exitCode: number | null + aborted?: true + timedOut?: true +} + +const DriverStateSchema = z.object({ + recipeResult: EphemeralVmRecipeResultSchema, + projectId: z.string().optional(), + workspaceId: z.string().optional(), + workspaceName: z.string().optional() +}) + +export class ShellRecipeDriver implements EnvironmentProviderDriver { + readonly id = SHELL_RECIPE_DRIVER_ID + readonly capabilities: EnvironmentProviderCapabilities + // Recipes have no status step, so status only covers calls this instance ran; the runtime + // record stays the persisted source of truth. + private readonly statuses = new Map() + + constructor( + private readonly recipe: OrcaVmRecipe, + private readonly repoPath: string + ) { + this.capabilities = { + memoryPause: false, + maxSessionMs: null, + fsPersistOnStop: Boolean(recipe.suspend && recipe.resume), + idleStopMs: null + } + } + + // Recipe-shaped steps keep stdout/stderr and failure copy for runtime records and diagnostics. + runCreate(args: RecipeStepArgs) { + return runEphemeralVmRecipeStart({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + runSuspend(args: RecipeStepArgs) { + return runEphemeralVmRecipeSuspend({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + runResume(args: RecipeStepArgs) { + return runEphemeralVmRecipeResume({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + runDestroy(args: RecipeStepArgs) { + return runEphemeralVmRecipeCleanup({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + create(spec: EnvironmentCreateSpec, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.createOnce(spec, ctx)) + } + + suspend(handle: EnvironmentHandle, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.suspendOnce(handle, ctx)) + } + + resume(handle: EnvironmentHandle, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.resumeOnce(handle, ctx)) + } + + destroy(handle: EnvironmentHandle, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.destroyOnce(handle, ctx)) + } + + private async createOnce( + spec: EnvironmentCreateSpec, + ctx: EnvironmentProviderCallContext + ): Promise { + ctx.onProgress?.({ phase: 'provisioning' }) + const start = await this.runCreate({ + context: { + projectId: spec.projectId, + workspaceId: spec.workspaceId, + workspaceName: spec.workspaceName, + repoUrl: spec.repo?.url, + ref: spec.repo?.ref + }, + signal: ctx.signal + }) + if (!start.ok) { + const error = toProviderError(start) + if (start.recipeResult) { + // The VM exists even though Orca rejected its result; release it rather than leak it. + const cleanup = await this.runDestroy({ + context: start.context, + recipeResult: start.recipeResult + }) + if (!cleanup.ok || cleanup.skipped) { + const detail = cleanup.error ?? EPHEMERAL_VM_FAILURE_COPY.destroyDisabled + throw new EnvironmentProviderError(error.code, `${error.message} ${detail}`, error.reason) + } + } + throw error + } + const handle = toHandle(start.context, start.result) + this.statuses.set(handle.environmentId, 'running') + return toReady(handle, start.result) + } + + private async suspendOnce( + handle: EnvironmentHandle, + ctx: EnvironmentProviderCallContext + ): Promise { + const { context, recipeResult } = this.readHandle(handle) + ctx.onProgress?.({ phase: 'suspending' }) + const suspend = await this.runSuspend({ context, recipeResult, signal: ctx.signal }) + if (!suspend.ok) { + throw toProviderError(suspend) + } + // No suspend step: the VM keeps running. + const status = suspend.skipped ? 'running' : 'suspended' + this.statuses.set(handle.environmentId, status) + return { status, session: null } + } + + private async resumeOnce( + handle: EnvironmentHandle, + ctx: EnvironmentProviderCallContext + ): Promise { + const { context, recipeResult } = this.readHandle(handle) + ctx.onProgress?.({ phase: 'resuming' }) + const resume = await this.runResume({ context, recipeResult, signal: ctx.signal }) + if (!resume.ok) { + throw toProviderError(resume) + } + const result = resume.skipped ? recipeResult : resume.result + const integrityError = getProvisionedRootResumeIntegrityError(recipeResult, result) + if (integrityError) { + throw new EnvironmentProviderError('conflict', integrityError) + } + this.statuses.set(handle.environmentId, 'running') + return toReady(toHandle(context, result), result) + } + + private async destroyOnce( + handle: EnvironmentHandle, + ctx: EnvironmentProviderCallContext + ): Promise { + if (this.statuses.get(handle.environmentId) === 'destroyed') { + return + } + const { context, recipeResult } = this.readHandle(handle) + ctx.onProgress?.({ phase: 'destroying' }) + const cleanup = await this.runDestroy({ context, recipeResult, signal: ctx.signal }) + if (!cleanup.ok) { + throw toProviderError(cleanup) + } + if (cleanup.skipped) { + throw new EnvironmentProviderError( + 'invalid_request', + EPHEMERAL_VM_FAILURE_COPY.destroyDisabled, + 'destroyDisabled' + ) + } + this.statuses.set(handle.environmentId, 'destroyed') + } + + async status(handle: EnvironmentHandle): Promise { + const status = this.statuses.get(handle.environmentId) + if (!status) { + throw new EnvironmentProviderError('not_found', 'This driver has not run that environment.') + } + return { status, session: null } + } + + private readHandle(handle: EnvironmentHandle): { + context: EphemeralVmRecipeContext + recipeResult: EphemeralVmRecipeResult + } { + if (handle.driverId !== this.id) { + throw new EnvironmentProviderError('invalid_request', 'Handle belongs to another driver.') + } + if (this.statuses.get(handle.environmentId) === 'destroyed') { + throw new EnvironmentProviderError('not_found', 'Environment was destroyed.') + } + const state = DriverStateSchema.safeParse(handle.driverState) + if (!state.success) { + throw new EnvironmentProviderError('invalid_request', 'Handle has no recipe result.') + } + const { recipeResult, ...fields } = state.data + return { + context: { + ...fields, + instanceId: handle.environmentId, + recipeId: this.recipe.id, + repoPath: this.repoPath + }, + recipeResult + } + } +} + +function toHandle( + context: EphemeralVmRecipeContext, + recipeResult: EphemeralVmRecipeResult +): EnvironmentHandle { + const { instanceId, projectId, workspaceId, workspaceName } = context + if (!instanceId) { + throw new EnvironmentProviderError('invalid_response', 'Recipe run has no instance id.') + } + // Round-trip through JSON so the persisted state is plain data (drops undefined fields). + const driverState: Record = JSON.parse( + JSON.stringify({ recipeResult, projectId, workspaceId, workspaceName }) + ) + return { + driverId: SHELL_RECIPE_DRIVER_ID, + environmentId: instanceId, + driverState + } +} + +function toReady(handle: EnvironmentHandle, result: EphemeralVmRecipeResult): EnvironmentReady { + return { handle, result, session: { startedAt: Date.now(), deadlineAt: null } } +} + +// Spawn errors and a missing repo dir surface as plain errors; the contract promises catalogued ones. +async function catalogued(run: () => Promise): Promise { + try { + return await run() + } catch (error) { + if (isEnvironmentProviderError(error)) { + throw error + } + throw new EnvironmentProviderError( + 'unavailable', + error instanceof Error ? error.message : String(error) + ) + } +} + +function toProviderError(failure: RecipeStepFailure): EnvironmentProviderError { + const code = failure.aborted + ? 'aborted' + : failure.timedOut + ? 'timeout' + : // The step exited cleanly but Orca rejected what it printed. + failure.exitCode === 0 + ? 'invalid_response' + : 'unavailable' + return new EnvironmentProviderError( + code, + failure.error ?? 'Recipe step failed.', + failure.errorCode ?? null + ) +}