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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
19 changes: 12 additions & 7 deletions packages/app/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(" ");
Expand Down Expand Up @@ -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 };
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)}`)); }
Expand All @@ -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");
Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())));
Expand All @@ -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 });
Expand All @@ -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));
Expand All @@ -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;
}
Expand Down
39 changes: 37 additions & 2 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,11 @@ export class TenantV2 extends DurableObject<Env> {
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());
Expand Down Expand Up @@ -356,6 +359,20 @@ export class TenantV2 extends DurableObject<Env> {
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<Response> {
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<Response> {
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; }
Expand Down Expand Up @@ -494,7 +511,7 @@ export class TenantV2 extends DurableObject<Env> {
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,
Expand Down Expand Up @@ -597,7 +614,7 @@ export class TenantV2 extends DurableObject<Env> {
}
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 {
Expand Down Expand Up @@ -1075,6 +1092,23 @@ export class TenantV2 extends DurableObject<Env> {
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[] = [];
Expand Down Expand Up @@ -1450,6 +1484,7 @@ export class TenantV2 extends DurableObject<Env> {
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.");
Expand Down
Loading
Loading