diff --git a/README.md b/README.md index 53524e7a..cfde2b0d 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,10 @@ curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ Job CRUD is available at `/jobs` and `/jobs/:id`; job metadata includes `currentRuns` and `maxConcurrency`. Run collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the rendered `prompt`, complete structured trigger `context`, and invocation metadata, including the firing `trigger_id`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. +Production diagnostics are authenticated and tenant-scoped. `GET /api/v1/runs/:runId/diagnostics` reports generic run lifecycle checks without returning credentials or internal command payloads. `POST /api/v1/integrations/exe/:connectionId/diagnostics` checks saved exe.dev permissions and creates then deletes a disposable tagged VM to verify the configured agent and managed model integration. + +The Wrangler-backed E2E suite loads the complete Worker and Durable Objects from `wrangler.jsonc`. Its exe.dev lifecycle tests disable external networking and use a stateful command-API stub to cover successful completion, masked shell-launch failures, run diagnostics, integration diagnostics, output capture, and VM cleanup without creating a real VM or calling an LLM. + ## MCP clients Configure a compatible remote MCP client with this single URL: diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index bfd4bb83..47c6cd4e 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -22,6 +22,11 @@ function shellWords(value: string): string[] { function agentCommand(connection: ExeRunConnection): string { const args = shellWords(connection.agentCommand?.trim() || defaultAgentCommand(connection.agentKind)); + if (connection.agentKind === "codex") args.push( + "-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"', + ); if (connection.model?.trim()) args.push("--model", connection.model.trim()); if (connection.effort?.trim() && connection.agentKind === "codex") args.push("-c", `model_reasoning_effort=${connection.effort.trim()}`); return args.map(shellAtom).join(" "); @@ -105,15 +110,15 @@ export class ExeVmBackend implements ExecutionBackend { const prompt = base64(request.prompt), output = "/tmp/factorize.log", status = "/tmp/factorize.status"; const work = [ "set -eu", - "mkdir -p /workspace", - "cd /workspace", + "mkdir -p /home/exedev/workspace", + "cd /home/exedev/workspace", `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, - `setsid nohup sh -c ${shellAtom(`set +e; ${agentCommand(connection)} < /tmp/factorize-prompt.md > ${output} 2>&1; code=$?; printf '%s' "$code" > ${status}`)} >/dev/null 2>&1 &`, - "echo started", - ].join(" && "); + `setsid nohup sh -c ${shellAtom(`set +e; ${agentCommand(connection)} < /tmp/factorize-prompt.md > ${output} 2>&1; code=$?; printf '%s' "$code" > ${status}`)} >/dev/null 2>&1 & echo started`, + ].join("; "); let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); - for (let attempt = 1; !started.ok && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); - if (!started.ok) { + const accepted = (result: BackendCommandResult) => result.ok && result.body.trim() === "started"; + for (let attempt = 1; !accepted(started) && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); + if (!accepted(started)) { const cleanup = await this.deleteVm(vm); const detail = `VM provisioning failed (${started.status}): ${started.body.slice(0, 500)}${cleanup.ok ? "" : `; cleanup also failed: ${cleanup.body.slice(0, 200)}`}`; return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail, command: started }, command: started }; diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 53192d26..9eee78a5 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -50,6 +50,7 @@ export class ApiService { listRuns(query: URLSearchParams) { return this.call("runs:read", `/v1/runs?${query}`); } search(query: string) { return this.call("runs:read", `/v1/search?q=${encodeURIComponent(query)}`); } getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); } + getRunDiagnostics(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}/diagnostics`); } stopRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: "POST" }); } async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); } async getJob(jobId: string) { return this.publicJob(await this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`)); } @@ -63,6 +64,7 @@ export class ApiService { setJobEnabled(jobId: string, enabled: boolean) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}/${enabled ? "enable" : "disable"}`, { method: "POST" }); } invokeJob(jobId: string, input: ManualInvocationInput) { return this.call("runs:write", `/v1/jobs/${encodeURIComponent(jobId)}/invocations`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); } listExecutionTargets() { return this.call("flows:read", "/v1/execution-targets"); } + diagnoseExeIntegration(connectionId: string) { return this.call("flows:write", `/v1/integrations/exe/${encodeURIComponent(connectionId)}/diagnostics`, { method: "POST" }); } listJobTriggerAvailability() { return this.call("flows:read", "/v1/job-trigger-availability"); } async previewSchedule(input: unknown) { await this.authorize("flows:read"); diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index f2bc4281..9a7973de 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -44,6 +44,8 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (request.method === "GET" && path === "/api/v1/job-trigger-availability") return Response.json(await service.listJobTriggerAvailability()); if (request.method === "POST" && path === "/api/v1/schedules/preview") return Response.json(await service.previewSchedule(await request.json())); if (request.method === "GET" && path === "/api/v1/integrations/cloudflare-tail") return Response.json(await service.listTailIntegrations()); + const exeDiagnosticMatch = path.match(/^\/api\/v1\/integrations\/exe\/([^/]+)\/diagnostics$/); + if (exeDiagnosticMatch && request.method === "POST") return Response.json(await service.diagnoseExeIntegration(decodeURIComponent(exeDiagnosticMatch[1]))); if (request.method === "GET" && path === "/api/v1/jobs") return Response.json(await service.listJobs()); if (request.method === "POST" && path === "/api/v1/jobs") return Response.json(await service.createJob(jobInputSchema.parse(await request.json())), { status: 201 }); if (request.method === "POST" && path === "/api/v1/job-handlers/test") return Response.json(await service.testJobHandler(jobHandlerTestSchema.parse(await request.json()))); @@ -64,6 +66,8 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (webhookDeliveryMatch && request.method === "GET") return Response.json(await service.getWebhookDelivery(decodeURIComponent(webhookDeliveryMatch[1]))); const runMatch = path.match(/^\/api\/v1\/runs\/([^/]+)$/); if (runMatch && request.method === "GET") return Response.json(await service.getRun(decodeURIComponent(runMatch[1]))); + const runDiagnosticMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/diagnostics$/); + if (runDiagnosticMatch && request.method === "GET") return Response.json(await service.getRunDiagnostics(decodeURIComponent(runDiagnosticMatch[1]))); const stopMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/stop$/); if (stopMatch && request.method === "POST") return Response.json(await service.stopRun(decodeURIComponent(stopMatch[1]))); return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); @@ -82,6 +86,7 @@ function createMcpServer(service: ApiService): McpServer { tool("list_github_installations", "List connected GitHub App installations, including the installation IDs needed by GitHub Job triggers. Credentials are never returned.", z.object({}), () => service.listGitHubInstallations()); tool("list_runs", "List authoritative job runs by job ID, state, and an optional case-insensitive literal substring of triggered context. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); tool("get_run", "Get a run with its rendered prompt, full triggered context, invocation metadata, execution metadata, output, and activity. For manual invocations, invocation.idempotency_key is the client-reusable value; invocation.claim_key is internal.", runIdSchema, ({ runId }: any) => service.getRun(runId)); + tool("get_run_diagnostics", "Get credential-safe launch, prompt delivery, output capture, claim release, cleanup, and activity diagnostics for a run.", runIdSchema, ({ runId }: any) => service.getRunDiagnostics(runId)); tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); tool("list_jobs", "List jobs with their current run count and maximum concurrency", z.object({}), () => service.listJobs()); tool("get_job", "Get a job with its current run count and maximum concurrency", jobIdSchema, ({ jobId }: any) => service.getJob(jobId)); @@ -96,6 +101,7 @@ function createMcpServer(service: ApiService): McpServer { tool("get_webhook_delivery", "Get a webhook delivery and its safe processing timeline. Secrets and payloads are never returned.", z.object({ deliveryId: z.string().min(1) }), ({ deliveryId }: any) => service.getWebhookDelivery(deliveryId)); tool("test_job_webhook_handler", "Test an isolated synchronous Job webhook handler without creating a run. Returns the decision and never accepts credentials.", jobHandlerTestSchema, (input: any) => service.testJobHandler(input)); tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets()); + tool("diagnose_exe_integration", "Probe a saved exe.dev connection's permissions and a disposable tagged VM's agent/model integration. The disposable VM is deleted before the tool returns.", z.object({ connectionId: z.string().min(1) }), ({ connectionId }: any) => service.diagnoseExeIntegration(connectionId)); tool("list_cloudflare_tail_integrations", "List installed Cloudflare Tail integrations and reference counts. Signing secrets are never returned.", z.object({}), () => service.listTailIntegrations()); return server; } diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 8b50d581..46414009 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -210,8 +210,11 @@ export class TenantV2 extends DurableObject { const webhookDeliveryMatch = url.pathname.match(/^\/v1\/webhooks\/deliveries\/([^/]+)$/); if (request.method === "GET" && webhookDeliveryMatch) return this.getWebhookDelivery(decodeURIComponent(webhookDeliveryMatch[1])); if (request.method === "GET" && /^\/v1\/runs\/[^/]+$/.test(url.pathname)) return await this.getRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); + if (request.method === "GET" && /^\/v1\/runs\/[^/]+\/diagnostics$/.test(url.pathname)) return this.getRunDiagnostics(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "POST" && /^\/v1\/runs\/[^/]+\/stop$/.test(url.pathname)) return await this.stopRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "GET" && url.pathname === "/v1/execution-targets") return await this.executionTargets(); + const exeDiagnosticMatch = url.pathname.match(/^\/v1\/integrations\/exe\/([^/]+)\/diagnostics$/); + if (request.method === "POST" && exeDiagnosticMatch) return await this.exeIntegrationDiagnostics(decodeURIComponent(exeDiagnosticMatch[1])); if (request.method === "GET" && url.pathname === "/v1/job-trigger-availability") return await this.triggerAvailability(); if (request.method === "GET" && url.pathname === "/v1/jobs") return json(await this.publicJobs(this.rows("SELECT * FROM jobs ORDER BY created_at DESC"))); if (request.method === "POST" && url.pathname === "/v1/jobs") return await this.createJob(await request.json()); @@ -356,6 +359,20 @@ export class TenantV2 extends DurableObject { return json({ ok: result.ok, missingPermissions: result.missingPermissions, tags: result.tags, checks: result.checks.map(check => ({ command: check.requestBody, ok: check.ok, httpStatus: check.status, exitCode: check.exitCode, output: check.body })) }); } + private async exeIntegrationDiagnostics(connectionId: string): Promise { + const connection = await this.exeConnection(connectionId); + if (!connection) return new Response("Not found", { status: 404 }); + const backend = new ExeVmBackend(connection), permissions = await backend.testPermissions(); + const permissionSummary = { ok: permissions.ok, missing: permissions.missingPermissions, tags: permissions.tags, checks: permissions.checks.map(check => ({ command: check.requestBody, ok: check.ok, httpStatus: check.status, exitCode: check.exitCode })) }; + if (!permissions.ok) return json({ ok: false, connectionId, agentKind: connection.agentKind, permissions: permissionSummary, agent: null }); + try { + const validation = await backend.validateAgentAndModels(connection.agentKind); + return json({ ok: true, connectionId, agentKind: connection.agentKind, permissions: permissionSummary, agent: { ok: true, models: validation.models, httpStatus: validation.command.status, exitCode: validation.command.exitCode } }); + } catch (error) { + return json({ ok: false, connectionId, agentKind: connection.agentKind, permissions: permissionSummary, agent: { ok: false, error: error instanceof Error ? error.message.slice(0, 500) : "Agent validation failed" } }); + } + } + private async removeExecutionConnection(kind: "exe" | "amp", connectionId: string): Promise { const referenced = this.rows("SELECT id,execution_target FROM jobs").some(row => { try { const target = JSON.parse(String(row.execution_target)); return target.backendKind === (kind === "exe" ? "exe-vm" : "amp") && String(target.connectionId) === connectionId; } catch { return false; } @@ -494,7 +511,7 @@ export class TenantV2 extends DurableObject { kind: "exe-vm", name: "Ephemeral exe.dev VMs", workspace: "ephemeral", - cwd: "/workspace", + cwd: "/home/exedev/workspace", agentKind: connection.agentKind, models: connection.models ?? [], modelsRefreshedAt: connection.modelsRefreshedAt ?? null, @@ -597,7 +614,7 @@ export class TenantV2 extends DurableObject { } const target = (await this.exeConnections()).find(item => item.connectionId === targetId); if (!target) throw new Error("Execution target not found"); - return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: "ephemeral", cwd: "/workspace", agentKind: target.agentKind }; + return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: target.agentKind }; } private validateJobInput(input: any): void { @@ -1075,6 +1092,23 @@ export class TenantV2 extends DurableObject { return json(run); } + private getRunDiagnostics(runId: string): Response { + const run = this.one(`SELECT id,pipe_id AS job_id,state,provider,execution_backend_kind AS backend_kind,prompt_delivery_state,prompt_accepted,output_captured,claim_released,exec_status,exec_exit_code,vm_cleanup_complete,vm_cleanup_attempt,vm_cleanup_next_at,created_at,updated_at FROM runs WHERE id=?`, runId) as Row | undefined; + if (!run) return new Response("Not found", { status: 404 }); + const activity = this.rows("SELECT action,detail,created_at FROM run_activity WHERE run_id=? ORDER BY created_at,id", runId); + const checks = { + launchAcknowledged: Boolean(run.prompt_accepted), + promptAccepted: Boolean(run.prompt_accepted), outputCaptured: Boolean(run.output_captured), claimReleased: Boolean(run.claim_released), cleanupComplete: Boolean(run.vm_cleanup_complete), + }; + return json({ + runId: run.id, jobId: run.job_id, state: normalizeExecutionState(run.state), provider: run.provider, backendKind: run.backend_kind, checks, + launch: { httpStatus: run.exec_status == null ? null : Number(run.exec_status), exitCode: run.exec_exit_code == null ? null : Number(run.exec_exit_code) }, + promptDelivery: { state: run.prompt_delivery_state ?? null }, + cleanup: { complete: checks.cleanupComplete, attempts: Number(run.vm_cleanup_attempt || 0), nextAttemptAt: run.vm_cleanup_next_at == null ? null : new Date(Number(run.vm_cleanup_next_at)).toISOString() }, + activity, createdAt: run.created_at, updatedAt: run.updated_at, + }); + } + private listEvents(url: URL): Response { const limit = this.pageSize(url), cursor = this.cursor(url), flowId = url.searchParams.get("flowId"); const clauses: string[] = [], args: unknown[] = []; @@ -1450,6 +1484,7 @@ export class TenantV2 extends DurableObject { const execResponse = await encrypt(safeSession(result.body) ?? "Agent command response unavailable.", this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET exec_request = ?, exec_response = ?, exec_status = ?, exec_exit_code = ?, updated_at = ? WHERE id = ?", execRequest, execResponse, result.status, result.exitCode, now(), run.id); this.commandActivity(run.id, "initial agent start", result); + if (launched.observation.state === "failed") return this.finishRun(run, "failed", launched.observation.detail ?? `Unable to start the ephemeral VM agent (exe.dev HTTP ${result.status}).`); if (!result.ok || (result.exitCode !== null && result.exitCode !== 0)) return this.finishRun(run, "failed", `Unable to start the ephemeral VM agent (exe.dev HTTP ${result.status}, VM exit ${result.exitCode ?? "not reported"}): ${result.body.slice(0, 800)}`); this.ctx.storage.sql.exec("UPDATE runs SET prompt_delivery_state='accepted',prompt_delivery_request=?,prompt_delivery_response=?,prompt_delivery_status=?,prompt_delivery_exit_code=?,prompt_accepted=1,updated_at=? WHERE id=?", execRequest, execResponse, result.status, result.exitCode, now(), run.id); this.activity(run.id, "prompt_delivered_at_launch", "The initial prompt was written to the run-owned VM and the agent was detached."); diff --git a/packages/app/test/exe-run-lifecycle.e2e.test.ts b/packages/app/test/exe-run-lifecycle.e2e.test.ts new file mode 100644 index 00000000..772fa4df --- /dev/null +++ b/packages/app/test/exe-run-lifecycle.e2e.test.ts @@ -0,0 +1,91 @@ +import { env, fetchMock, runDurableObjectAlarm, SELF } from "cloudflare:test"; +import { beforeAll, describe, expect, it } from "vitest"; +import { signSession } from "../src/index"; +import type { Env as FactorizeEnv } from "../src/types"; + +declare module "cloudflare:test" { interface ProvidedEnv extends FactorizeEnv {} } + +const origin = "https://app.factorize.sh"; + +describe("exe.dev run lifecycle", () => { + const vms = new Map(); + let scenario: "success" | "launch-failure" = "success"; + + beforeAll(() => { + fetchMock.activate(); + fetchMock.disableNetConnect(); + fetchMock.get("https://exe.dev").intercept({ path: "/exec", method: "POST" }).reply(options => { + const command = String(options.body ?? ""), headers = { "X-Exe-Exit": "0", "Content-Type": "text/plain" }; + if (command === "ls --json") return { statusCode: 200, data: JSON.stringify({ vms: [...vms].map(([name, vm]) => ({ name, comment: vm.comment, tags: ["factorize"] })) }), responseOptions: { headers } }; + if (command === "integrations list --json") return { statusCode: 200, data: JSON.stringify({ integrations: [{ tags: ["factorize"] }] }), responseOptions: { headers } }; + if (command.endsWith("--help")) return { statusCode: 200, data: "help", responseOptions: { headers } }; + if (command.startsWith("new ")) { + const name = command.match(/--name='([^']+)'/)?.[1] ?? ""; + vms.set(name, { comment: `Factorize VM ${name}` }); + return { statusCode: 200, data: JSON.stringify({ name }), responseOptions: { headers } }; + } + if (command.startsWith("rm ")) { vms.delete(command.match(/^rm '([^']+)'/)?.[1] ?? ""); return { statusCode: 200, data: "removed", responseOptions: { headers } }; } + if (command.startsWith("ssh ") && command.includes("command -v codex")) return { statusCode: 200, data: '["gpt-test"]', responseOptions: { headers } }; + if (command.startsWith("ssh ") && command.includes("factorize-prompt.md")) { + if (scenario === "launch-failure") return { statusCode: 200, data: "bash: syntax error", responseOptions: { headers: { "Content-Type": "text/plain" } } }; + const name = command.match(/^ssh '([^']+)'/)?.[1] ?? ""; const vm = vms.get(name); if (vm) vm.state = "succeeded"; + return { statusCode: 200, data: "started", responseOptions: { headers } }; + } + if (command.startsWith("ssh ") && command.includes("factorize.status")) return { statusCode: 200, data: "succeeded", responseOptions: { headers } }; + if (command.startsWith("ssh ") && command.includes("cat /tmp/factorize.log")) return { statusCode: 200, data: "Hello from the stubbed agent!", responseOptions: { headers } }; + return { statusCode: 422, data: `unexpected command: ${command}` }; + }).persist(); + }); + + it("runs through the Worker, Durable Object, stubbed exe backend, diagnostics, and cleanup", async () => { + scenario = "success"; + const tenantId = `exe-e2e-${crypto.randomUUID()}`, userId = "owner"; + const tenant = env.TENANTS.get(env.TENANTS.idFromName(`tenant:${tenantId}`)); + await tenant.fetch("https://tenant/members", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ userId, email: "owner@example.com" }) }); + const session = await signSession({ tenantId, userId, email: "owner@example.com", exp: Math.floor(Date.now() / 1000) + 60, sessionVersion: 1 }, "e2e-session-secret"); + const headers = { cookie: `factorize_session=${session}`, "content-type": "application/json" }; + + const connected = await SELF.fetch(`${origin}/api/connections/exe`, { method: "PUT", headers, body: JSON.stringify({ connectionId: "exe-test", apiToken: "exe1-test", agentKind: "codex", tags: ["factorize"] }) }); + expect(connected.status, await connected.clone().text()).toBe(200); + + const integrationDiagnostic = await SELF.fetch(`${origin}/api/v1/integrations/exe/exe-test/diagnostics`, { method: "POST", headers }); + expect(integrationDiagnostic.status, await integrationDiagnostic.clone().text()).toBe(200); + await expect(integrationDiagnostic.json()).resolves.toMatchObject({ ok: true, connectionId: "exe-test", permissions: { ok: true }, agent: { ok: true, models: ["gpt-test"] } }); + + const created = await SELF.fetch(`${origin}/api/v1/jobs`, { method: "POST", headers, body: JSON.stringify({ name: "Stubbed run", slug: "stubbed-run", promptTemplate: "{{trigger-1.prompt}}", concurrencyLimit: 1, executionTargetId: "exe-test", model: "gpt-test", effort: "low", triggers: [{ kind: "manual", slug: "trigger-1", config: {} }] }) }); + expect(created.status, await created.clone().text()).toBe(201); + const job = await created.json<{ id: string }>(); + const invoked = await SELF.fetch(`${origin}/api/v1/jobs/${job.id}/invocations`, { method: "POST", headers, body: JSON.stringify({ prompt: "say hello" }) }); + expect(invoked.status, await invoked.clone().text()).toBe(202); + const run = await invoked.json<{ runId: string }>(); + + for (let attempt = 0; attempt < 4; attempt++) await runDurableObjectAlarm(tenant); + + const inspected = await SELF.fetch(`${origin}/api/v1/runs/${run.runId}`, { headers }); + expect(inspected.status, await inspected.clone().text()).toBe(200); + await expect(inspected.json()).resolves.toMatchObject({ id: run.runId, state: "succeeded", result: expect.stringContaining("Hello from the stubbed agent!") }); + const diagnostics = await SELF.fetch(`${origin}/api/v1/runs/${run.runId}/diagnostics`, { headers }); + expect(diagnostics.status, await diagnostics.clone().text()).toBe(200); + await expect(diagnostics.json()).resolves.toMatchObject({ runId: run.runId, state: "succeeded", checks: { launchAcknowledged: true, promptAccepted: true, outputCaptured: true, claimReleased: true, cleanupComplete: true } }); + expect(vms.size).toBe(0); + }); + + it("reports an HTTP-200 shell launch failure without calling an LLM", async () => { + scenario = "launch-failure"; + const tenantId = `exe-failure-${crypto.randomUUID()}`, userId = "owner"; + const tenant = env.TENANTS.get(env.TENANTS.idFromName(`tenant:${tenantId}`)); + await tenant.fetch("https://tenant/members", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ userId, email: "owner@example.com" }) }); + const session = await signSession({ tenantId, userId, email: "owner@example.com", exp: Math.floor(Date.now() / 1000) + 60, sessionVersion: 1 }, "e2e-session-secret"); + const headers = { cookie: `factorize_session=${session}`, "content-type": "application/json" }; + const connected = await SELF.fetch(`${origin}/api/connections/exe`, { method: "PUT", headers, body: JSON.stringify({ connectionId: "exe-test", apiToken: "exe1-test", agentKind: "codex", tags: ["factorize"] }) }); + expect(connected.status, await connected.clone().text()).toBe(200); + const created = await SELF.fetch(`${origin}/api/v1/jobs`, { method: "POST", headers, body: JSON.stringify({ name: "Failed stub", slug: "failed-stub", promptTemplate: "{{trigger-1.prompt}}", concurrencyLimit: 1, executionTargetId: "exe-test", model: "gpt-test", effort: "low", triggers: [{ kind: "manual", slug: "trigger-1", config: {} }] }) }); + const job = await created.json<{ id: string }>(); + const invoked = await SELF.fetch(`${origin}/api/v1/jobs/${job.id}/invocations`, { method: "POST", headers, body: JSON.stringify({ prompt: "say hello" }) }); + const run = await invoked.json<{ runId: string }>(); + for (let attempt = 0; attempt < 3; attempt++) await runDurableObjectAlarm(tenant); + const diagnostics = await SELF.fetch(`${origin}/api/v1/runs/${run.runId}/diagnostics`, { headers }); + await expect(diagnostics.json()).resolves.toMatchObject({ state: "failed", checks: { launchAcknowledged: false, promptAccepted: false, claimReleased: true, cleanupComplete: true }, activity: expect.arrayContaining([expect.objectContaining({ detail: expect.stringContaining("bash: syntax error") })]) }); + expect(vms.size).toBe(0); + }); +}); diff --git a/packages/app/test/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index ced34b46..17fb3151 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -47,9 +47,27 @@ describe("ExeVmBackend", () => { expect(requests[0]).toContain("new --name='factorize-run-1'"); expect(requests[0]).toContain("--tag='github'"); expect(requests[0]).toContain("--tag='llm'"); - expect(requests[1]).toContain("cd /workspace"); + expect(requests[1]).toContain("cd /home/exedev/workspace"); expect(requests[1]).not.toContain("git clone"); expect(requests[1]).toContain("codex"); + 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]).not.toContain("& &&"); + expect(requests[1]).toContain("& echo started"); + }); + + it("rejects an HTTP-successful launch whose shell did not acknowledge startup", async () => { + const requests: string[] = []; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { + requests.push(String(init.body)); + if (requests.length === 1) return new Response("created", { headers: { "X-Exe-Exit": "0" } }); + if (requests.length <= 6) return new Response("bash: syntax error"); + if (String(init.body) === "ls --json") return new Response(JSON.stringify({ vms: [{ name: "factorize-run-1", comment: "Factorize VM factorize-run-1" }] }), { headers: { "X-Exe-Exit": "0" } }); + return new Response("removed", { headers: { "X-Exe-Exit": "0" } }); + })); + const launched = await new ExeVmBackend(connection).launch({ runId: "run-1", prompt: "do the work" }); + expect(launched.observation.state).toBe("failed"); + expect(launched.observation.detail).toContain("bash: syntax error"); }); it("validates Codex and loads models in a temporary tagged VM that is deleted", async () => { diff --git a/packages/app/vitest.e2e.config.ts b/packages/app/vitest.e2e.config.ts index d321a04e..b8f80334 100644 --- a/packages/app/vitest.e2e.config.ts +++ b/packages/app/vitest.e2e.config.ts @@ -2,7 +2,7 @@ import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; export default defineWorkersConfig({ test: { - include: ["test/device-oauth.e2e.test.ts", "test/fresh-namespace.e2e.test.ts"], + include: ["test/device-oauth.e2e.test.ts", "test/fresh-namespace.e2e.test.ts", "test/exe-run-lifecycle.e2e.test.ts"], poolOptions: { workers: { isolatedStorage: false, diff --git a/packages/docs/api/reference.mdx b/packages/docs/api/reference.mdx index b535e847..32930db9 100644 --- a/packages/docs/api/reference.mdx +++ b/packages/docs/api/reference.mdx @@ -20,6 +20,7 @@ All paths are relative to `APP_ORIGIN` and require a bearer token or browser own | GET | `/api/v1/jobs/{jobId}` | flows:read | One job | | GET | `/api/v1/jobs/{jobId}/events?limit=50` | runs:read | Webhook activity; limit 1–100 | | GET | `/api/v1/runs/{runId}` | runs:read | Full prompt, context, invocation, execution, output, activity | +| GET | `/api/v1/runs/{runId}/diagnostics` | runs:read | Credential-safe lifecycle checks and activity | ## Writes and runs @@ -31,6 +32,7 @@ All paths are relative to `APP_ORIGIN` and require a bearer token or browser own | POST | `/api/v1/jobs/{jobId}/enable` | flows:write | Enable | | POST | `/api/v1/jobs/{jobId}/disable` | flows:write | Disable | | POST | `/api/v1/job-handlers/test` | flows:write | Isolated synchronous test; no run | +| POST | `/api/v1/integrations/exe/{connectionId}/diagnostics` | flows:write | Probe permissions and a disposable VM's agent/model integration | | POST | `/api/v1/jobs/{jobId}/invocations` | runs:write | Manual invocation; returns `202` | | GET | `/api/v1/runs?jobId=&state=&contextQuery=&limit=&cursor=` | runs:read | `{items,nextCursor}`; limit 1–100 | | POST | `/api/v1/runs/{runId}/stop` | runs:write | Stop an active run | diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 2886f9dd..19dc9424 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -40,6 +40,9 @@ paths: /api/v1/execution-targets: { get: { summary: List execution targets, responses: { '200': { description: Targets } } } } /api/v1/job-trigger-availability: { get: { summary: List available trigger kinds, responses: { '200': { description: Availability } } } } /api/v1/integrations/cloudflare-tail: { get: { summary: List Tail integrations, responses: { '200': { description: Integrations } } } } + /api/v1/integrations/exe/{connectionId}/diagnostics: + parameters: [{ name: connectionId, in: path, required: true, schema: { type: string } }] + post: { summary: Probe exe.dev permissions and a disposable VM's agent/model integration, responses: { '200': { description: Credential-safe diagnostic result } } } /api/v1/jobs: get: { summary: List jobs, responses: { '200': { description: Jobs } } } post: { summary: Create job, requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/JobInput' } } } }, responses: { '201': { description: Created } } } @@ -58,5 +61,6 @@ paths: /api/v1/runs: get: { summary: List runs, parameters: [{ name: jobId, in: query, schema: { type: string } }, { name: state, in: query, schema: { type: string } }, { name: contextQuery, in: query, schema: { type: string } }, { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }, { name: cursor, in: query, schema: { type: string } }], responses: { '200': { description: Paginated runs, content: { application/json: { schema: { $ref: '#/components/schemas/RunPage' } } } } } } /api/v1/runs/{runId}: { get: { summary: Get run, responses: { '200': { description: Run } } } } + /api/v1/runs/{runId}/diagnostics: { get: { summary: Get credential-safe run lifecycle diagnostics, responses: { '200': { description: Launch, prompt, output, claim, cleanup, and activity diagnostics } } } } /api/v1/runs/{runId}/stop: { post: { summary: Stop run, responses: { '200': { description: Stopped } } } } /api/v1/schedules/preview: { post: { summary: Preview schedule, responses: { '200': { description: Next occurrence } } } }