Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions packages/api/src/agent-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { TraceSources } from "./trace-source";
import { JOB_RESULT_PATH } from "./job-result";
export type AgentKind = "codex" | "claude" | "pi";

export interface AgentConfiguration { model?: string; effort?: string; }
export interface AgentConfiguration { model?: string; effort?: string; codexModel?: { baseUrl: string; providerName?: string }; }
export interface ArtifactLocator {
/** Paths are interpreted inside the guest; the compute backend only transports files. */
roots: string[];
Expand All @@ -29,7 +29,11 @@ export interface AgentDriver {
class CodexDriver implements AgentDriver {
readonly kind = "codex" as const;
launch(runId: string, config: AgentConfiguration): AgentLaunchSpec {
const args = ["exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--color", "never", "-c", "model_provider=exe-llm", "-c", 'model_providers.exe-llm.name="exe-llm"', "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"'];
const args = ["exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--color", "never"];
if (config.codexModel?.baseUrl) {
const provider = "factorize";
args.push("-c", `model_provider=${provider}`, "-c", `model_providers.${provider}.name=${JSON.stringify(config.codexModel.providerName ?? "Factorize")}`, "-c", `model_providers.${provider}.base_url=${JSON.stringify(config.codexModel.baseUrl)}`, "-c", `model_providers.${provider}.requires_openai_auth=false`);
}
if (config.model?.trim()) args.push("--model", config.model.trim());
if (config.effort?.trim()) args.push("-c", `model_reasoning_effort=${config.effort.trim()}`);
return {
Expand Down
7 changes: 5 additions & 2 deletions packages/api/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe";

import { HARNESS_LOG_LIMIT, safeDiagnosticText } from "./harness-diagnostics";
import { ExeRunProxy } from "./exe-run-proxy";
import { runProxyName } from "./run-credentials";

const API = "https://exe.dev/exec";
const capabilities = ["output", "recovery", "stop"] as const;
Expand Down Expand Up @@ -61,6 +62,8 @@ export class ExeVmBackend implements ExecutionBackend {

constructor(private readonly connection: Pick<ExeConnection, "apiToken" | "tags"> & { image?: string } | ExeRunConnection) {}

reserve(runId: string): RunHandle { return { backendKind: this.kind, id: vmNameFor(runId), runProxyName: runProxyName(runId) }; }

private async api(command: string): Promise<BackendCommandResult> {
const response = await fetch(API, { method: "POST", headers: { Authorization: `Bearer ${this.connection.apiToken}`, "Content-Type": "text/plain" }, body: command });
const body = await response.text(), exit = response.headers.get("X-Exe-Exit");
Expand Down Expand Up @@ -153,8 +156,8 @@ export class ExeVmBackend implements ExecutionBackend {
const connection = this.connection as ExeRunConnection;
if (!request.code && (!connection.agentKind || !request.harness)) throw new Error("The job is missing its agent harness launch plan");
if (request.traceSources) validateTraceSources(request.traceSources);
const vm = vmNameFor(request.runId);
const handle: RunHandle = { backendKind: this.kind, id: vm };
const handle: RunHandle = request.reservation ?? { backendKind: this.kind, id: vmNameFor(request.runId) };
const vm = this.vm(handle);
let proxy: ExeRunProxy | undefined, plan: Awaited<ReturnType<ExeRunProxy["prepare"]>> | undefined;
if (request.runProxy) {
try {
Expand Down
4 changes: 4 additions & 0 deletions packages/api/src/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export interface BackendCommandResult {

export interface LaunchRequest {
runId: string;
/** Backend-owned provisional handle, persisted before provisioning when supported. */
reservation?: RunHandle;
prompt: string;
/** Control-plane only: provisioned into an exe.dev proxy, never the guest. */
runProxy?: { targetOrigin: string; credential: string };
Expand Down Expand Up @@ -54,6 +56,8 @@ export interface ArtifactCollectionReceipt { ok: boolean; detail?: string; comma
export interface ExecutionBackend {
readonly kind: string;
readonly capabilities: readonly ExecutionCapability[];
/** Reserve a cleanup handle before provisioning, or return null when the provider allocates one during launch. */
reserve?(runId: string): RunHandle | null;
launch(request: LaunchRequest): Promise<LaunchReceipt>;
inspect(handle: RunHandle): Promise<ExecutionObservation>;
stop(handle: RunHandle): Promise<ExecutionObservation>;
Expand Down
23 changes: 14 additions & 9 deletions packages/api/src/postgres/run-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { artifactKey } from "../artifacts";
import { ArtifactRepository } from "./artifact-repository";
import { safeDiagnosticText } from "../harness-diagnostics";
import { decrypt } from "../crypto";
import { ExeVmBackend, vmNameFor } from "../exe-vm-backend";
import { ExeVmBackend } from "../exe-vm-backend";
import type { ExecutionBackend } from "../execution";
import type { ExeRunConnection } from "../exe";
import type { Env } from "../types";
import { ConnectionRepository } from "./connection-repository";
Expand All @@ -18,7 +19,7 @@ import { rolloutTraceSources } from "../trace-source";
import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./trace-projection-repository";
import { LiveTraceRepository } from "./live-trace-repository";
import { JOB_RESULT_INSTRUCTIONS, parseJobResult } from "../job-result";
import { issueRunCredential, runProxyInstructions, runProxyName } from "../run-credentials";
import { issueRunCredential, runProxyInstructions } from "../run-credentials";

export class RunScheduler {
private runs: RunRepository;
Expand All @@ -32,9 +33,11 @@ export class RunScheduler {
}

private connections(run: PersistedRun) { return new ConnectionRepository(this.database, run.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); }
private async backend(run: PersistedRun) {
private async backend(run: PersistedRun): Promise<ExecutionBackend> {
const id = String(run.executionConfig.connectionId ?? "");
if (run.executionConfig.agentKind === "Amp") { const connection = await this.connections(run).get<AmpConnection>(`amp:${id}`); if (!connection) throw new Error("Amp connection is unavailable"); return new AmpBackend(connection); }
const kind = run.executionConfig.backendKind ?? (run.executionConfig.agentKind === "Amp" ? "amp" : "exe-vm");
if (kind === "amp") { const connection = await this.connections(run).get<AmpConnection>(`amp:${id}`); if (!connection) throw new Error("Amp connection is unavailable"); return new AmpBackend(connection); }
if (kind !== "exe-vm") throw new Error(`Unsupported execution backend: ${String(kind)}`);
const connection = await this.connections(run).get<ExeRunConnection>(`exe:${id}`); if (!connection) throw new Error("exe.dev connection is unavailable");
return new ExeVmBackend({ ...connection, tags: Array.isArray(run.executionConfig.tags) ? run.executionConfig.tags : [], image: typeof run.executionConfig.image === "string" ? run.executionConfig.image : undefined, model: String(run.executionConfig.model ?? ""), effort: String(run.executionConfig.effort ?? "") });
}
Expand All @@ -45,20 +48,22 @@ export class RunScheduler {
const backend = await this.backend(run), context = run.executionConfig.inputContext;
if (!context || typeof context !== "object" || Array.isArray(context)) throw new Error("The code job input context snapshot is missing");
const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes);
await this.runs.recordLaunchHandle(run, { backendKind: backend.kind, id: vmNameFor(run.id), runProxyName: runProxyName(run.id) });
const launched = await backend.launch({ runId: run.id, prompt: "", runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, code: { script: run.executionConfig.script, context } });
const reservation = backend.reserve?.(run.id) ?? null;
if (reservation) await this.runs.recordLaunchHandle(run, reservation);
const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: "", runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, code: { script: run.executionConfig.script, context } });
await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities);
if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation);
return;
}
if (run.executionConfig.agentKind === "Amp") throw new Error("Amp execution is unavailable for new runs because it cannot deliver the required structured result file. Choose an exe.dev agent integration.");
const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionConfig.model, effort: run.executionConfig.effort });
const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionConfig.model, effort: run.executionConfig.effort, ...(driver.kind === "codex" ? { codexModel: { baseUrl: this.env.CODEX_MODEL_BASE_URL ?? "https://llm.int.exe.xyz/v1" } } : {}) });
const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env);
validateTraceSources(sources);
const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes);
const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY);
await this.runs.recordLaunchHandle(run, { backendKind: backend.kind, id: vmNameFor(run.id), runProxyName: runProxyName(run.id) });
const launched = await backend.launch({ runId: run.id, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runProxyInstructions(run.id)}`, runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env } });
const reservation = backend.reserve?.(run.id) ?? null;
if (reservation) await this.runs.recordLaunchHandle(run, reservation);
const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runProxyInstructions(run.id)}`, runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env } });
await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources);
if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation);
}
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export interface Env {
RUN_ARTIFACTS?: R2Bucket;
TRACE_PRIMARY_MODE?: "execution_stream" | "native_session";
TRACE_STREAM_TENANTS?: string;
/** OpenAI-compatible Codex endpoint configured for the execution environment. */
CODEX_MODEL_BASE_URL?: string;
HYPERDRIVE?: Hyperdrive;
/** Test-only injection point; production uses HYPERDRIVE. */
DATABASE?: import("./postgres/database").Database;
Expand Down
18 changes: 13 additions & 5 deletions packages/api/test/execution-backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ import { ExeImageVerificationError, ExeVmBackend, isOwnedVmName, tagsFromInvento
import type { ExecutionBackend, ExecutionObservation, LaunchRequest, RunHandle } from "../src/execution";
import { effortOptions, selectableExeTags, type ExeRunConnection } from "../src/exe";
import { agentDriver } from "../src/agent-driver";
import { runProxyName } from "../src/run-credentials";

afterEach(() => vi.unstubAllGlobals());

const connection = { apiToken: "secret", agentKind: "codex", tags: ["github", "llm"], model: "gpt-5.5", effort: "high" } satisfies ExeRunConnection;

describe("ExeVmBackend", () => {
it("reserves its legacy VM and proxy handle for scheduler recovery", () => {
const runId = "00000000-0000-4000-8000-000000000001";
expect(new ExeVmBackend(connection).reserve(runId)).toEqual({ backendKind: "exe-vm", id: vmNameFor(runId), runProxyName: runProxyName(runId) });
});
it("defines the supported effort choices by agent", () => {
expect(effortOptions.codex).toEqual(["minimal", "low", "medium", "high", "xhigh"]);
expect(effortOptions.claude).toEqual(["low", "medium", "high"]);
Expand Down Expand Up @@ -67,7 +72,7 @@ describe("ExeVmBackend", () => {
requests.push(String(init.body));
return new Response(requests.length === 1 ? '{"name":"factorize-run-1"}' : "started", { headers: { "X-Exe-Exit": "0" } });
}));
const harness = agentDriver("codex").launch("run-1", {});
const harness = agentDriver("codex").launch("run-1", { codexModel: { baseUrl: "https://models.example/v1" } });
harness.env = { FACTORIZE_RESULT_PATH: "/home/exedev/.factorize-job/results.json" };
const launched = await new ExeVmBackend(connection).launch({ runId: "run-1", prompt: "do the work", harness, traceSources: { primary: { kind: "execution_stream", path: "/tmp/trace/events.jsonl", mediaType: "application/x-ndjson", provider: "codex" } } });
expect(launched.handle).toEqual({ backendKind: "exe-vm", id: "factorize-run-1" });
Expand All @@ -79,8 +84,9 @@ describe("ExeVmBackend", () => {
expect(requests[1]).toContain("codex");
expect(requests[1]).toContain("--color");
expect(requests[1]).toContain("never");
expect(requests[1]).toContain("model_provider=exe-llm");
expect(requests[1]).toContain("model_providers.exe-llm.base_url=\"https://llm.int.exe.xyz/v1\"");
expect(requests[1]).toContain("model_provider=factorize");
expect(requests[1]).toContain("model_providers.factorize.base_url=\"https://models.example/v1\"");
expect(requests[1]).toContain("model_providers.factorize.requires_openai_auth=false");
expect(requests[1]).toContain("sudo systemd-run");
expect(requests[1]).toContain("'--setenv=FACTORIZE_RESULT_PATH=/home/exedev/.factorize-job/results.json'");
expect(requests[1]).toContain("--uid=exedev --gid=exedev");
Expand Down Expand Up @@ -330,11 +336,13 @@ describe("ExecutionBackend contract", () => {
it("launches, observes, and stops a provider-neutral backend", async () => {
class FakeBackend implements ExecutionBackend {
readonly kind = "fake"; readonly capabilities = [] as const; state: ExecutionObservation["state"] = "queued";
async launch(request: LaunchRequest) { this.state = "running"; return { handle: { backendKind: this.kind, id: request.runId }, destinationUrl: `https://runs.example/${request.runId}`, capabilities: this.capabilities, observation: { state: this.state } }; }
reserve(runId: string) { return { backendKind: this.kind, id: `remote-${runId}` }; }
async launch(request: LaunchRequest) { this.state = "running"; return { handle: request.reservation!, destinationUrl: `https://runs.example/${request.runId}`, capabilities: this.capabilities, observation: { state: this.state } }; }
async inspect(_handle: RunHandle) { return { state: this.state }; }
async stop(_handle: RunHandle) { this.state = "stopped"; return { state: this.state }; }
}
const backend = new FakeBackend(), launched = await backend.launch({ runId: "1", prompt: "work" });
const backend = new FakeBackend(), reservation = backend.reserve("1"), launched = await backend.launch({ runId: "1", reservation, prompt: "work" });
expect(reservation).toEqual({ backendKind: "fake", id: "remote-1" });
expect(await backend.inspect(launched.handle)).toEqual({ state: "running" });
expect(await backend.stop(launched.handle)).toEqual({ state: "stopped" });
});
Expand Down
Loading