Skip to content

Commit 91c7194

Browse files
author
exe.dev user
committed
Refactor execution launch backend ownership
1 parent baf44d3 commit 91c7194

6 files changed

Lines changed: 44 additions & 18 deletions

File tree

‎packages/api/src/agent-driver.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type { TraceSources } from "./trace-source";
44
import { JOB_RESULT_PATH } from "./job-result";
55
export type AgentKind = "codex" | "claude" | "pi";
66

7-
export interface AgentConfiguration { model?: string; effort?: string; }
7+
export interface AgentConfiguration { model?: string; effort?: string; codexModel?: { baseUrl: string; providerName?: string }; }
88
export interface ArtifactLocator {
99
/** Paths are interpreted inside the guest; the compute backend only transports files. */
1010
roots: string[];
@@ -29,7 +29,11 @@ export interface AgentDriver {
2929
class CodexDriver implements AgentDriver {
3030
readonly kind = "codex" as const;
3131
launch(runId: string, config: AgentConfiguration): AgentLaunchSpec {
32-
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"'];
32+
const args = ["exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--color", "never"];
33+
if (config.codexModel?.baseUrl) {
34+
const provider = "factorize";
35+
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`);
36+
}
3337
if (config.model?.trim()) args.push("--model", config.model.trim());
3438
if (config.effort?.trim()) args.push("-c", `model_reasoning_effort=${config.effort.trim()}`);
3539
return {

‎packages/api/src/exe-vm-backend.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe";
66

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

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

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

65+
reserve(runId: string): RunHandle { return { backendKind: this.kind, id: vmNameFor(runId), runProxyName: runProxyName(runId) }; }
66+
6467
private async api(command: string): Promise<BackendCommandResult> {
6568
const response = await fetch(API, { method: "POST", headers: { Authorization: `Bearer ${this.connection.apiToken}`, "Content-Type": "text/plain" }, body: command });
6669
const body = await response.text(), exit = response.headers.get("X-Exe-Exit");
@@ -153,8 +156,8 @@ export class ExeVmBackend implements ExecutionBackend {
153156
const connection = this.connection as ExeRunConnection;
154157
if (!request.code && (!connection.agentKind || !request.harness)) throw new Error("The job is missing its agent harness launch plan");
155158
if (request.traceSources) validateTraceSources(request.traceSources);
156-
const vm = vmNameFor(request.runId);
157-
const handle: RunHandle = { backendKind: this.kind, id: vm };
159+
const handle: RunHandle = request.reservation ?? { backendKind: this.kind, id: vmNameFor(request.runId) };
160+
const vm = this.vm(handle);
158161
let proxy: ExeRunProxy | undefined, plan: Awaited<ReturnType<ExeRunProxy["prepare"]>> | undefined;
159162
if (request.runProxy) {
160163
try {

‎packages/api/src/execution.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ export interface BackendCommandResult {
1313

1414
export interface LaunchRequest {
1515
runId: string;
16+
/** Backend-owned provisional handle, persisted before provisioning when supported. */
17+
reservation?: RunHandle;
1618
prompt: string;
1719
/** Control-plane only: provisioned into an exe.dev proxy, never the guest. */
1820
runProxy?: { targetOrigin: string; credential: string };
@@ -54,6 +56,8 @@ export interface ArtifactCollectionReceipt { ok: boolean; detail?: string; comma
5456
export interface ExecutionBackend {
5557
readonly kind: string;
5658
readonly capabilities: readonly ExecutionCapability[];
59+
/** Reserve a cleanup handle before provisioning, or return null when the provider allocates one during launch. */
60+
reserve?(runId: string): RunHandle | null;
5761
launch(request: LaunchRequest): Promise<LaunchReceipt>;
5862
inspect(handle: RunHandle): Promise<ExecutionObservation>;
5963
stop(handle: RunHandle): Promise<ExecutionObservation>;

‎packages/api/src/postgres/run-scheduler.ts‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import { artifactKey } from "../artifacts";
55
import { ArtifactRepository } from "./artifact-repository";
66
import { safeDiagnosticText } from "../harness-diagnostics";
77
import { decrypt } from "../crypto";
8-
import { ExeVmBackend, vmNameFor } from "../exe-vm-backend";
8+
import { ExeVmBackend } from "../exe-vm-backend";
9+
import type { ExecutionBackend } from "../execution";
910
import type { ExeRunConnection } from "../exe";
1011
import type { Env } from "../types";
1112
import { ConnectionRepository } from "./connection-repository";
@@ -18,7 +19,7 @@ import { rolloutTraceSources } from "../trace-source";
1819
import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./trace-projection-repository";
1920
import { LiveTraceRepository } from "./live-trace-repository";
2021
import { JOB_RESULT_INSTRUCTIONS, parseJobResult } from "../job-result";
21-
import { issueRunCredential, runProxyInstructions, runProxyName } from "../run-credentials";
22+
import { issueRunCredential, runProxyInstructions } from "../run-credentials";
2223

2324
export class RunScheduler {
2425
private runs: RunRepository;
@@ -32,9 +33,11 @@ export class RunScheduler {
3233
}
3334

3435
private connections(run: PersistedRun) { return new ConnectionRepository(this.database, run.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); }
35-
private async backend(run: PersistedRun) {
36+
private async backend(run: PersistedRun): Promise<ExecutionBackend> {
3637
const id = String(run.executionConfig.connectionId ?? "");
37-
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); }
38+
const kind = run.executionConfig.backendKind ?? (run.executionConfig.agentKind === "Amp" ? "amp" : "exe-vm");
39+
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); }
40+
if (kind !== "exe-vm") throw new Error(`Unsupported execution backend: ${String(kind)}`);
3841
const connection = await this.connections(run).get<ExeRunConnection>(`exe:${id}`); if (!connection) throw new Error("exe.dev connection is unavailable");
3942
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 ?? "") });
4043
}
@@ -45,20 +48,22 @@ export class RunScheduler {
4548
const backend = await this.backend(run), context = run.executionConfig.inputContext;
4649
if (!context || typeof context !== "object" || Array.isArray(context)) throw new Error("The code job input context snapshot is missing");
4750
const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes);
48-
await this.runs.recordLaunchHandle(run, { backendKind: backend.kind, id: vmNameFor(run.id), runProxyName: runProxyName(run.id) });
49-
const launched = await backend.launch({ runId: run.id, prompt: "", runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, code: { script: run.executionConfig.script, context } });
51+
const reservation = backend.reserve?.(run.id) ?? null;
52+
if (reservation) await this.runs.recordLaunchHandle(run, reservation);
53+
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 } });
5054
await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities);
5155
if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation);
5256
return;
5357
}
5458
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.");
55-
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 });
59+
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" } } : {}) });
5660
const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env);
5761
validateTraceSources(sources);
5862
const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes);
5963
const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY);
60-
await this.runs.recordLaunchHandle(run, { backendKind: backend.kind, id: vmNameFor(run.id), runProxyName: runProxyName(run.id) });
61-
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 } });
64+
const reservation = backend.reserve?.(run.id) ?? null;
65+
if (reservation) await this.runs.recordLaunchHandle(run, reservation);
66+
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 } });
6267
await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources);
6368
if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation);
6469
}

‎packages/api/src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ export interface Env {
2929
RUN_ARTIFACTS?: R2Bucket;
3030
TRACE_PRIMARY_MODE?: "execution_stream" | "native_session";
3131
TRACE_STREAM_TENANTS?: string;
32+
/** OpenAI-compatible Codex endpoint configured for the execution environment. */
33+
CODEX_MODEL_BASE_URL?: string;
3234
HYPERDRIVE?: Hyperdrive;
3335
/** Test-only injection point; production uses HYPERDRIVE. */
3436
DATABASE?: import("./postgres/database").Database;

‎packages/api/test/execution-backend.test.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,17 @@ import { ExeImageVerificationError, ExeVmBackend, isOwnedVmName, tagsFromInvento
44
import type { ExecutionBackend, ExecutionObservation, LaunchRequest, RunHandle } from "../src/execution";
55
import { effortOptions, selectableExeTags, type ExeRunConnection } from "../src/exe";
66
import { agentDriver } from "../src/agent-driver";
7+
import { runProxyName } from "../src/run-credentials";
78

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

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

1213
describe("ExeVmBackend", () => {
14+
it("reserves its legacy VM and proxy handle for scheduler recovery", () => {
15+
const runId = "00000000-0000-4000-8000-000000000001";
16+
expect(new ExeVmBackend(connection).reserve(runId)).toEqual({ backendKind: "exe-vm", id: vmNameFor(runId), runProxyName: runProxyName(runId) });
17+
});
1318
it("defines the supported effort choices by agent", () => {
1419
expect(effortOptions.codex).toEqual(["minimal", "low", "medium", "high", "xhigh"]);
1520
expect(effortOptions.claude).toEqual(["low", "medium", "high"]);
@@ -67,7 +72,7 @@ describe("ExeVmBackend", () => {
6772
requests.push(String(init.body));
6873
return new Response(requests.length === 1 ? '{"name":"factorize-run-1"}' : "started", { headers: { "X-Exe-Exit": "0" } });
6974
}));
70-
const harness = agentDriver("codex").launch("run-1", {});
75+
const harness = agentDriver("codex").launch("run-1", { codexModel: { baseUrl: "https://models.example/v1" } });
7176
harness.env = { FACTORIZE_RESULT_PATH: "/home/exedev/.factorize-job/results.json" };
7277
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" } } });
7378
expect(launched.handle).toEqual({ backendKind: "exe-vm", id: "factorize-run-1" });
@@ -79,8 +84,9 @@ describe("ExeVmBackend", () => {
7984
expect(requests[1]).toContain("codex");
8085
expect(requests[1]).toContain("--color");
8186
expect(requests[1]).toContain("never");
82-
expect(requests[1]).toContain("model_provider=exe-llm");
83-
expect(requests[1]).toContain("model_providers.exe-llm.base_url=\"https://llm.int.exe.xyz/v1\"");
87+
expect(requests[1]).toContain("model_provider=factorize");
88+
expect(requests[1]).toContain("model_providers.factorize.base_url=\"https://models.example/v1\"");
89+
expect(requests[1]).toContain("model_providers.factorize.requires_openai_auth=false");
8490
expect(requests[1]).toContain("sudo systemd-run");
8591
expect(requests[1]).toContain("'--setenv=FACTORIZE_RESULT_PATH=/home/exedev/.factorize-job/results.json'");
8692
expect(requests[1]).toContain("--uid=exedev --gid=exedev");
@@ -330,11 +336,13 @@ describe("ExecutionBackend contract", () => {
330336
it("launches, observes, and stops a provider-neutral backend", async () => {
331337
class FakeBackend implements ExecutionBackend {
332338
readonly kind = "fake"; readonly capabilities = [] as const; state: ExecutionObservation["state"] = "queued";
333-
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 } }; }
339+
reserve(runId: string) { return { backendKind: this.kind, id: `remote-${runId}` }; }
340+
async launch(request: LaunchRequest) { this.state = "running"; return { handle: request.reservation!, destinationUrl: `https://runs.example/${request.runId}`, capabilities: this.capabilities, observation: { state: this.state } }; }
334341
async inspect(_handle: RunHandle) { return { state: this.state }; }
335342
async stop(_handle: RunHandle) { this.state = "stopped"; return { state: this.state }; }
336343
}
337-
const backend = new FakeBackend(), launched = await backend.launch({ runId: "1", prompt: "work" });
344+
const backend = new FakeBackend(), reservation = backend.reserve("1"), launched = await backend.launch({ runId: "1", reservation, prompt: "work" });
345+
expect(reservation).toEqual({ backendKind: "fake", id: "remote-1" });
338346
expect(await backend.inspect(launched.handle)).toEqual({ state: "running" });
339347
expect(await backend.stop(launched.handle)).toEqual({ state: "stopped" });
340348
});

0 commit comments

Comments
 (0)