From 10299e4bb4727863da0cfc7ad4b0bf7f84fab27e Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 17:28:41 +0000 Subject: [PATCH] Replace Herdr runs with ephemeral exe.dev VMs --- README.md | 4 +- docs/execution-boundaries.md | 8 +-- packages/app/src/exe-vm-backend.ts | 73 +++++++++++++++++++++ packages/app/src/tenant.ts | 102 +++++++++++------------------ packages/app/src/types.ts | 10 ++- packages/app/src/ui.ts | 8 +-- packages/docs/quickstart.mdx | 2 +- 7 files changed, 129 insertions(+), 78 deletions(-) create mode 100644 packages/app/src/exe-vm-backend.ts diff --git a/README.md b/README.md index ceaf2998..7dbd9916 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@ [![CI](https://github.com/GenerationSoftware/factorize/actions/workflows/ci.yml/badge.svg)](https://github.com/GenerationSoftware/factorize/actions/workflows/ci.yml) [![Deploy to Cloudflare](https://img.shields.io/badge/Deploy_to-Cloudflare-F38020?style=flat&logo=cloudflare&logoColor=white)](https://deploy.workers.cloudflare.com/?url=https://github.com/GenerationSoftware/factorize&path=packages/app) -**A no-code software factory for Linear teams.** Factorize turns selected Linear issue changes into coding-agent jobs on your own exe.dev VM, using Herdr to run the agent you choose. +**A no-code software factory for Linear teams.** Factorize turns selected Linear issue changes into coding-agent jobs on isolated, ephemeral exe.dev VMs. ```text -Linear webhook → Cloudflare Worker → Durable Object → exe.dev /exec → Herdr +Linear webhook → Cloudflare Worker → Durable Object → exe.dev /exec → isolated agent VM ↑ polls status ↓ concurrency control Linear comments ``` diff --git a/docs/execution-boundaries.md b/docs/execution-boundaries.md index 9382d6c9..51c3173a 100644 --- a/docs/execution-boundaries.md +++ b/docs/execution-boundaries.md @@ -20,10 +20,10 @@ Backends map their native lifecycle into `queued`, `starting`, `running`, `recovering`, and `cancelled` rows are presented as `succeeded`, `starting`, and `stopped` respectively, avoiding a risky rewrite of durable history. -`ExeHerdrBackend` and `AmpBackend` implement this boundary. exe.dev supplies command -transport and VM wake-up, Herdr supplies workspace and agent supervision, and -the configured harness supplies Codex, Claude, Pi, or another Herdr-supported -agent. Amp cloud runs persist an opaque thread handle and expose the canonical +`ExeVmBackend` and `AmpBackend` implement this boundary. exe.dev supplies account-level +VM creation, command transport, and deletion. The configured Codex, Claude, or Pi +harness runs directly in its isolated VM; output and exit status are durable files. +Amp cloud runs persist an opaque thread handle and expose the canonical Amp thread URL. Amp does not declare output retrieval, so Factorize does not ingest thread contents. Amp credentials are dashboard-only; REST and MCP expose only non-secret target metadata and capabilities. diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts new file mode 100644 index 00000000..7d6e3095 --- /dev/null +++ b/packages/app/src/exe-vm-backend.ts @@ -0,0 +1,73 @@ +import type { ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, PromptDeliveryReceipt, RunHandle } from "./execution"; +import { base64 } from "./crypto"; +import { shellAtom, type ExeConnection } from "./exe"; + +/** Account credentials used to create and destroy run-owned VMs. */ +export interface ExeVmConnection extends ExeConnection { + /** Account-level exe.dev token; it must be allowed to run new, ssh and rm. */ + accountToken?: string; + tags?: string[]; + repositoryUrl?: string; + checkoutRef?: string; +} + +const API = "https://exe.dev/exec"; +const capabilities = ["output", "recovery", "stop"] as const; + +function vmNameFor(runId: string): string { + const suffix = runId.replace(/[^a-zA-Z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(-38) || "run"; + return `factorize-${suffix}`.slice(0, 63); +} + +function commandResult(ok: boolean, status: number, body: string, requestBody: string, exitCode: number | null = null) { + return { ok, status, body, requestBody, exitCode }; +} + +/** Adapter for the documented exe.dev HTTPS command API. Every run owns one VM. */ +export class ExeVmBackend implements ExecutionBackend { + readonly kind = "exe-vm"; + readonly capabilities = capabilities; + constructor(private readonly connection: ExeVmConnection, private readonly launchContext?: { repositoryUrl?: string; checkoutRef?: string; cwd?: string; tags?: string[] }) {} + + private token(): string { return this.connection.accountToken || this.connection.apiToken; } + private async api(command: string) { + const response = await fetch(API, { method: "POST", headers: { Authorization: `Bearer ${this.token()}`, "Content-Type": "text/plain" }, body: command }); + const body = await response.text(); + const exit = response.headers.get("X-Exe-Exit"); + return { body, status: response.status, exitCode: exit && /^\d+$/.test(exit) ? Number(exit) : null, ok: response.ok && (!exit || exit === "0"), requestBody: command }; + } + + async launch(request: LaunchRequest): Promise { + const vm = vmNameFor(request.runId), tags = [...new Set(this.launchContext?.tags || this.connection.tags || [])]; + const tagArgs = tags.map(tag => `--tag=${shellAtom(tag)}`).join(" "); + const created = await this.api(`new --json --name=${shellAtom(vm)} --no-email ${tagArgs}`.trim()); + if (!created.ok) throw new Error(`exe.dev VM creation failed (${created.status}): ${created.body.slice(0, 500)}`); + const cwd = this.launchContext?.cwd || this.connection.cwd || "/workspace"; + const repo = this.launchContext?.repositoryUrl || this.connection.repositoryUrl; + const ref = this.launchContext?.checkoutRef || this.connection.checkoutRef; + const clone = repo ? `git clone ${shellAtom(repo)} repo && cd repo${ref ? ` && git checkout ${shellAtom(ref)}` : ""} && ` : ""; + const prompt = base64(request.prompt); + const agent = this.connection.agentKind === "claude" ? "claude --dangerously-skip-permissions" : "codex --dangerously-bypass-approvals-and-sandbox"; + const runKey = vm.slice(9), output = `/tmp/factorize-${runKey}.log`, status = `/tmp/factorize-${runKey}.status`; + const work = `mkdir -p ${shellAtom(cwd)} && cd ${shellAtom(cwd)} && ${clone}printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md && setsid nohup sh -c ${shellAtom(`${agent} < /tmp/factorize-prompt.md > ${output} 2>&1; printf '%s' "$?" > ${status}`)} >/dev/null 2>&1 & echo started`; + const started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); + const command = commandResult(started.ok, started.status, started.body, started.requestBody, started.exitCode); + if (!started.ok) { await this.deleteVm(vm); return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities: this.capabilities, observation: { state: "failed", command }, command }; } + return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities: this.capabilities, observation: { state: "running", command }, command }; + } + + async inspect(handle: RunHandle): Promise { + const vm = this.vm(handle), result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(`if [ -f /tmp/factorize-${vm.slice(9)}.status ]; then code=$(cat /tmp/factorize-${vm.slice(9)}.status); [ "$code" = 0 ] && printf succeeded || printf failed; else printf running; fi`)}`); + if (!result.ok && result.status >= 500) return { state: "running", command: commandResult(false, result.status, result.body, result.requestBody, result.exitCode) }; + const state = result.body.trim() === "succeeded" ? "succeeded" : result.body.trim() === "failed" ? "failed" : "running"; + return { state, command: commandResult(result.ok, result.status, result.body, result.requestBody, result.exitCode) }; + } + + async readOutput(handle: RunHandle): Promise { const vm = this.vm(handle), result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(`cat /tmp/factorize-${vm.slice(9)}.log`)}`); return result.ok ? result.body : null; } + async stop(handle: RunHandle): Promise { const vm = this.vm(handle), result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom("pkill -TERM -f factorize-prompt || true")}`); await this.deleteVm(vm); return { state: "stopped", command: commandResult(result.ok, result.status, result.body, result.requestBody, result.exitCode) }; } + async deliverPrompt(_handle: RunHandle, _prompt: string): Promise { return { state: "failed" }; } + private async deleteVm(vm: string) { for (let attempt = 0; attempt < 3; attempt++) { const result = await this.api(`rm ${shellAtom(vm)}`); if (result.ok || result.status === 404) return; } } + private vm(handle: RunHandle) { if (handle.backendKind !== this.kind || !handle.id) throw new Error("Invalid exe-vm execution handle"); return handle.id; } +} + +export { vmNameFor }; diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index f08fb765..d2c265b0 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -11,6 +11,7 @@ import { githubClaimKey, githubCollection, githubHeaders, installationToken, nor import type { WorkItem } from "./types"; import { invokeCustomHandler } from "./custom-handler"; import { generateTailSecret, sanitizeTailEvent, signTailDelivery, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "./cloudflare-tail"; +import { ExeVmBackend } from "./exe-vm-backend"; import { ExeHerdrBackend } from "./exe-herdr-backend"; import { AmpBackend, type AmpConnection } from "./amp-backend"; import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, renderContextTemplate } from "./linear-source"; @@ -326,20 +327,19 @@ export class TenantV2 extends DurableObject { private async saveExe(input: unknown): Promise { const value = input as ExeConnectionInput; - if (!value.vmName || !value.apiToken || !value.cwd || !value.agentKind) throw new Error("SSH destination, API token, agent, and working directory are required"); - const verification = await exec(value, herdrCheckCommand(value)); - if (verification.status === 403 && verification.body.includes("command not allowed by token permissions")) { - throw new Error(`This token cannot run ssh commands on ${value.vmName}. Create an exe.dev API token with --cmds="'ssh ${value.vmName}'" (not --vm), then paste the new exe1 token.`); - } - if (!verification.ok) throw new Error(`exe.dev/Herdr verification failed (${verification.status}): ${verification.body.slice(0, 300)}`); - const models = await this.discoverExeModels(value); + if (!value.apiToken || !value.agentKind) throw new Error("An account-level exe.dev token and agent are required"); + if (value.cwd && (!value.cwd.startsWith("/") || value.cwd.includes("\0"))) throw new Error("Working directory must be an absolute path"); + const tags = Array.isArray(value.tags) ? value.tags.map(tag => String(tag).trim()).filter(Boolean) : []; + if (tags.length > 20 || tags.some(tag => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(tag))) throw new Error("VM tags may contain only letters, numbers, dot, underscore, colon, and hyphen"); + if (value.repositoryUrl && (!/^https:\/\//i.test(value.repositoryUrl) || value.repositoryUrl.length > 2000)) throw new Error("Repository URL must be an HTTPS URL"); + if (value.checkoutRef && (value.checkoutRef.length > 255 || /[\0\r\n]/.test(value.checkoutRef))) throw new Error("Checkout ref is invalid"); + const saved = { ...value, cwd: value.cwd || "/workspace", tags, models: value.models ?? [], modelsRefreshedAt: now() }; const connectionId = value.connectionId || id(); - const saved = { ...value, models, modelsRefreshedAt: now() }; await this.putConnection(`exe:${connectionId}`, saved); // Preserve the most recently saved connection for existing flows created // before connections were selectable. await this.putConnection("exe", saved); - return json({ ok: true, connectionId, verification: verification.body, models }); + return json({ ok: true, connectionId, models: saved.models }); } private async discoverExeModels(connection: ExeConnection): Promise { @@ -439,7 +439,7 @@ export class TenantV2 extends DurableObject { const linear = await this.connection<{ accessToken: string }>("linear"); if (!linear) throw new Error("Connect Linear first"); const exe = await this.exeConnection(input.exeConnectionId); - if (!exe) throw new Error("Connect Herdr first"); + if (!exe) throw new Error("Connect an exe.dev account first"); const cwd = this.cwdTemplate(input.cwd ?? exe.cwd, flowId); const workspaceName = flowId; // These legacy fields are retained for compatibility with the v1 Durable Object schema. @@ -480,7 +480,7 @@ export class TenantV2 extends DurableObject { return json({ linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, clickup: clickup ? { teamName: clickup.teamName ?? null } : null, - exe: exe ? { vmName: exe.vmName, agentKind: exe.agentKind, cwd: exe.cwd, herdrCommand: exe.herdrCommand ?? "herdr", agentCommand: exe.agentCommand ?? defaultAgentCommand(exe.agentKind) } : null, + exe: exe ? { agentKind: exe.agentKind, cwd: exe.cwd, tags: exe.tags ?? [] } : null, exeConnections: connections.map(({ apiToken, ...connection }) => connection), ampConnections: ampConnections.map(({ accessToken, ...connection }) => connection), cloudflareTail: { count: tailInstallations.length, installations: await this.tailIntegrationStatus(tailInstallations) }, @@ -511,9 +511,9 @@ export class TenantV2 extends DurableObject { const ampConnections = await this.ampConnections(); return json([...populated.map(connection => ({ id: connection.connectionId, - kind: "exe-herdr", - name: connection.vmName, - workspace: connection.vmName, + kind: "exe-vm", + name: "Ephemeral exe.dev VMs", + workspace: "ephemeral", cwd: connection.cwd, agentKind: connection.agentKind, models: connection.models ?? [], @@ -530,7 +530,7 @@ export class TenantV2 extends DurableObject { if (!job) return undefined; let target: Record = {}; try { target = JSON.parse(String(job.execution_target)); } catch { return undefined; } - return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: job.slug, agent_kind: target.agentKind, model: target.model ?? "", effort: target.effort ?? "", cwd: target.cwd, execution_backend_kind: target.backendKind ?? "exe-herdr", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled }; + return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: job.slug, agent_kind: target.agentKind, model: target.model ?? "", effort: target.effort ?? "", cwd: target.cwd, execution_backend_kind: target.backendKind ?? "exe-vm", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled }; } private async publicJobs(rows: Row[]): Promise[]> { @@ -616,7 +616,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-herdr", workspace: target.vmName, cwd: target.cwd, agentKind: target.agentKind }; + return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: target.vmName ?? "ephemeral", cwd: target.cwd, agentKind: target.agentKind }; } private validateJobInput(input: any): void { @@ -816,7 +816,7 @@ export class TenantV2 extends DurableObject { let target: Record = {}; try { target = JSON.parse(String(row.execution_target)); } catch { /* validated when the job is saved */ } const provider = source === "webhook" ? String((occurrence as any)?.metadata?.provider ?? "webhook") : source; - const backendKind = String(target.backendKind ?? "exe-herdr"), capabilities = backendKind === "amp" ? ["stop"] : ["output", "prompt-delivery", "recovery", "stop"]; + const backendKind = String(target.backendKind ?? "exe-vm"), capabilities = backendKind === "amp" ? ["stop"] : ["output", "recovery", "stop"]; this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,run_name,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,prompt_delivery_state,provider,execution_backend_kind,execution_capabilities,destination_url,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, jobId, invocationId, String(row.name), runName, null, claimKey, `factorize-${runId}`, String(target.workspace ?? ""), String(target.agentKind ?? ""), "queued", encryptedPrompt, "pending", provider, backendKind, JSON.stringify(capabilities), backendKind === "amp" ? null : "https://exe.dev/", timestamp, timestamp); await this.ctx.storage.setAlarm(Date.now()); return { invocationId, runId, state: "queued", duplicate: false }; @@ -975,7 +975,7 @@ export class TenantV2 extends DurableObject { private presentExecution(run: Row): void { run.state = normalizeExecutionState(run.state); - run.backend_kind = String(run.backend_kind || "exe-herdr"); + run.backend_kind = String(run.backend_kind || "exe-vm"); try { run.capabilities = JSON.parse(String(run.capabilities || "[]")); } catch { run.capabilities = []; } if (!Array.isArray(run.capabilities) || run.capabilities.length === 0) run.capabilities = ["output", "prompt-delivery", "recovery"]; run.destination_url = String(run.destination_url || "https://exe.dev/"); @@ -1064,11 +1064,12 @@ export class TenantV2 extends DurableObject { run.name = String(run.run_name || run.issue_title || `Run ${String(run.id).slice(0, 8)}`); if (["starting", "running", "blocked", "stopping"].includes(String(run.state)) && (run.capabilities as unknown[]).includes("output")) { const pipe = this.executionConfig(run.job_id); - if (pipe && String(run.backend_kind) === "exe-herdr") { + if (pipe && ["exe-vm", "exe-herdr"].includes(String(run.backend_kind))) { const connection = await this.connectionForPipe(pipe); if (connection) { try { - const output = await new ExeHerdrBackend(connection).readOutput(this.executionHandle(run, "exe-herdr")); + const backend = String(run.backend_kind) === "exe-herdr" ? new ExeHerdrBackend(connection) : new ExeVmBackend(connection); + const output = await backend.readOutput(this.executionHandle(run, String(run.backend_kind))); if (output !== null) run.live_output = output; } catch { // Run inspection remains available when live output is temporarily unreachable. @@ -1107,7 +1108,7 @@ export class TenantV2 extends DurableObject { } else { const connection = await this.exeConnection(String(pipe.exe_connection_id || "default")); if (connection && run.agent_name) { - const backend = new ExeHerdrBackend(connection); + const backend = new ExeVmBackend(connection); this.ctx.storage.sql.exec("UPDATE runs SET state='stopping',updated_at=? WHERE id=?", now(), runId); const stopped = await backend.stop(this.executionHandle(run, backend.kind)); if (stopped.state !== "stopped") return Response.json({ error: "Could not stop the active agent" }, { status: 502 }); @@ -1336,7 +1337,7 @@ export class TenantV2 extends DurableObject { try { this.ctx.storage.sql.exec("INSERT INTO active_claims (pipe_id,issue_id,run_id) VALUES (?,?,?)", pipe.id, workItem.claimKey, runId); } catch { this.recordFlowEvent(pipe, deliveryId, workItem.identifier, workItem.url, workItem.event as any, "duplicate", "An active or queued run already owns this work item.", workItem.provider); return; } const prompt = await encrypt(plaintextPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); - this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,prompt_delivery_state,provider,execution_backend_kind,execution_capabilities,destination_url,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, pipe.id, workItem.identifier, workItem.title, workItem.url, workItem.claimKey, `factorize-${runId}`, String(pipe.workspace_name ?? ""), String(pipe.agent_kind ?? ""), "queued", prompt, "pending", workItem.provider, "exe-herdr", JSON.stringify(["output", "prompt-delivery", "recovery"]), "https://exe.dev/", now(), now()); + this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,prompt_delivery_state,provider,execution_backend_kind,execution_capabilities,destination_url,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, pipe.id, workItem.identifier, workItem.title, workItem.url, workItem.claimKey, `factorize-${runId}`, String(pipe.workspace_name ?? ""), String(pipe.agent_kind ?? ""), "queued", prompt, "pending", workItem.provider, "exe-vm", JSON.stringify(["output", "recovery", "stop"]), "https://exe.dev/", now(), now()); const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id=? AND state IN ('starting','running','blocked','recovering')", pipe.id) as Row; this.recordFlowEvent(pipe, deliveryId, workItem.identifier, workItem.url, workItem.event as any, Number(active.count) < Number(pipe.max_concurrency) ? "accepted" : "queued_capacity", Number(active.count) < Number(pipe.max_concurrency) ? "Handler accepted delivery; agent queued to start." : "Handler accepted delivery; queued for capacity.", workItem.provider); } @@ -1446,12 +1447,7 @@ export class TenantV2 extends DurableObject { } const connection = await this.connectionForPipe(pipe); if (!connection) return this.finishRun(run, "failed", "No exe.dev VM is connected."); - const workspaceName = String(run.workspace_name || pipe.workspace_name || workspaceNameFor(String(pipe.name))); - const lease = crypto.randomUUID(); - const worktreePath = `${connection.cwd.replace(/\/$/, "")}/.factorize-runs/${String(run.id)}`; - this.ctx.storage.sql.exec("UPDATE runs SET herdr_server_namespace='default',worktree_path=?,ownership_lease=?,ownership_generation=ownership_generation+1,agent_session_generation=1,updated_at=? WHERE id=?", worktreePath, lease, now(), run.id); - if (String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `Factorize started **${connection.agentKind}** on ${connection.vmName} in Herdr workspace \`${workspaceName}\` for this issue.`); - const backend = new ExeHerdrBackend(connection, { agentName: String(run.agent_name), workspaceName, runPath: worktreePath, lease }); + const backend = new ExeVmBackend(connection, { cwd: connection.cwd }); const prompt = await decrypt(String(run.prompt), this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET prompt_delivery_state='submitting',updated_at=? WHERE id=?", now(), run.id); const launched = await backend.launch({ runId: String(run.id), prompt }); @@ -1461,21 +1457,10 @@ export class TenantV2 extends DurableObject { const execResponse = await encrypt(result.body, 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 (!result.ok || (result.exitCode !== null && result.exitCode !== 0)) return this.finishRun(run, "failed", `Unable to start Herdr agent (exe.dev HTTP ${result.status}, VM exit ${result.exitCode ?? "not reported"}): ${result.body.slice(0, 800)}`); - const observed = await backend.inspect(launched.handle), verification = observed.command!; - this.commandActivity(run.id, "initial agent verification", verification); - if (!verification.ok || (verification.exitCode !== null && verification.exitCode !== 0) || !herdrAgentStatus(verification.body)) { - return this.beginRecovery(run, pipe, connection, `agent start succeeded but verification was ambiguous (exe.dev HTTP ${verification.status}, VM exit ${verification.exitCode ?? "not reported"})`); - } - const identity = parseAgent(verification.body); - if (!identity) return this.beginRecovery(run, pipe, connection, "agent start succeeded but its structured identity was inconsistent"); - const startupOutput = backend.readOutput ? await backend.readOutput(launched.handle) : null; - if (startupOutput && agentStartupBlocked(startupOutput)) { - return this.finishRun(run, "failed", "The agent process started but stopped at an interactive startup permission prompt."); - } + 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 passed as a positional harness argument in the successful Herdr launch command."); - this.persistIdentity(run.id, identity, "running"); + this.activity(run.id, "prompt_delivered_at_launch", "The initial prompt was written to the run-owned VM and the agent was detached."); + this.ctx.storage.sql.exec("UPDATE runs SET state='running',prompt_delivery_state='accepted',prompt_accepted=1,updated_at=? WHERE id=?", now(), run.id); } private async pollRun(run: Row): Promise { @@ -1499,26 +1484,10 @@ export class TenantV2 extends DurableObject { } const connection = await this.connectionForPipe(pipe); if (!connection) return this.finishRun(run, "failed", "exe.dev connection is unavailable."); - if (String(run.state) === "recovering") return this.recoverRun(run, pipe, connection); - const backend = new ExeHerdrBackend(connection), handle = this.executionHandle(run, backend.kind); - const observation = await backend.inspect(handle), status = observation.command!; - if (!status.ok && (status.exitCode === null || status.exitCode === 0)) return; // transient exe.dev/API failure - if (!status.ok || (status.exitCode !== null && status.exitCode !== 0)) return this.beginRecovery(run, pipe, connection, `expected Herdr agent is no longer resolvable (VM exit ${status.exitCode ?? "unknown"})`); - const live = parseAgent(status.body); - if (!live) return this.beginRecovery(run, pipe, connection, "Herdr returned an inconsistent agent identity"); - const terminalOwned = Boolean(run.herdr_terminal_id && ownsPane(this.savedIdentity(run), live, String(run.worktree_path || ""))); - if (terminalOwned) { - const rotated = String(run.agent_session_value || "") !== live.sessionValue; - this.persistIdentity(run.id, live, String(run.state), rotated); - this.ctx.storage.sql.exec("UPDATE runs SET recovery_attempt=0,recovery_started_at=NULL,recovery_next_at=NULL,recovery_reason=NULL WHERE id=?", run.id); - } - if (run.herdr_terminal_id && !terminalOwned) return this.beginRecovery(run, pipe, connection, "Herdr alias resolved to a different terminal owner"); - if (!terminalOwned) this.persistIdentity(run.id, live, String(run.state)); - if (observation.state === "blocked") { - this.ctx.storage.sql.exec("UPDATE runs SET state = 'blocked', updated_at = ? WHERE id = ?", now(), run.id); - return; - } - if (observation.state !== "succeeded") return; + const backend = new ExeVmBackend(connection), handle = this.executionHandle(run, backend.kind); + const observation = await backend.inspect(handle); + if (observation.state === "running") return; + if (observation.state === "failed") return this.finishRun(run, "failed", observation.detail ?? "The agent failed in its ephemeral VM."); const output = backend.readOutput ? await backend.readOutput(handle) : null; await this.finishRun(run, "done", output ?? "Agent completed; terminal output is not available from this backend.", output !== null); } @@ -1635,9 +1604,14 @@ export class TenantV2 extends DurableObject { this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id = ? AND issue_id = ?", run.pipe_id, run.claim_key || run.issue_id); this.ctx.storage.sql.exec("UPDATE runs SET claim_released=1 WHERE id=?", run.id); await this.afterJobTerminal(String(run.pipe_id), String(run.id), state === "done" ? "succeeded" : "failed", transitionedAt); - await this.collectRunPane({ ...run, state, output_captured: outputCaptured ? 1 : Number(run.output_captured || 0), claim_released: 1 }); + const pipe = this.executionConfig(run.pipe_id); + if (pipe && String(run.execution_backend_kind) === "exe-vm" && run.execution_handle) { + const connection = await this.connectionForPipe(pipe); + if (connection) await new ExeVmBackend(connection).stop(this.executionHandle(run, "exe-vm")).catch(error => this.activity(run.id, "vm_cleanup_retry", String(error).slice(0, 500))); + this.ctx.storage.sql.exec("UPDATE runs SET pane_collected=1,worktree_disposition='deleted',updated_at=? WHERE id=?", now(), run.id); + } else await this.collectRunPane({ ...run, state, output_captured: outputCaptured ? 1 : Number(run.output_captured || 0), claim_released: 1 }); const heading = state === "done" ? "Factorize completed the agent run." : "Factorize could not complete the agent run."; - if (String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `${heading}\n\nRun ID: \`${run.id}\`. Review the Herdr session on the configured VM for details.`); + if (String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `${heading}\n\nRun ID: \`${run.id}\`. The ephemeral exe.dev VM was deleted after the run.`); } private async collectRunPane(run: Row): Promise { diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index 03b3e3c0..2d192c61 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -51,12 +51,16 @@ export interface WorkItem { export interface ExeConnectionInput { connectionId?: string; - vmName: string; + /** Account-level token; no persistent VM is required. */ apiToken: string; agentKind: "claude" | "codex" | "pi" | string; - cwd: string; + cwd?: string; + tags?: string[]; + repositoryUrl?: string; + checkoutRef?: string; + /** Deprecated fields are accepted while old encrypted settings age out. */ + vmName?: string; herdrCommand?: string; - /** Arguments passed to Herdr's canonical executable for the selected kind. */ agentCommand?: string; models?: string[]; modelsRefreshedAt?: string; diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index c1ca4914..4bcd0ab0 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -50,9 +50,9 @@ const shell = (title: string, viewer: Viewer, body: string, script = "") => ` shell("Factorize: Software Factories for Everybody", viewer, `
-

Linear → Exe.dev → Herdr

+

Linear → Exe.dev → ephemeral agent VMs

No-code Software Factories

-

Create a multiplayer software factory with Linear, Exe.dev and Herdr

+

Create a multiplayer software factory with Linear and Exe.dev.

Create Job Read the docs @@ -63,7 +63,7 @@ export const landingPage = (viewer: Viewer) => shell("Factorize: Software Factor
  1. 1

    Plan work in Linear

    Define bugs, features, and product work as Linear issues—your source of truth for what should be built.

  2. 2

    Issues are routed to agents

    Factorize listens to Linear and sends issues to agents on your VM. Use criteria to filter the issues by matching status, assignee, label, etc. -

  3. 3

    Watch, guide, or take over

    Wait for the work to complete, or connect to the VM and start Herdr to watch or steer the agents. Do it with a colleague! It's multiplayer out-of-the-box.

  4. +
  5. 3

    Review captured output

    Every run gets its own VM. Factorize captures its output and deletes the VM when the run ends.

`); @@ -226,7 +226,7 @@ async function tailAction(id,method){await request('/api/connections/cloudflare- function bindActions(){bindTests();document.querySelectorAll('[data-refresh-models]').forEach(button=>button.onclick=async()=>{button.disabled=true;button.textContent='Refreshing…';try{const result=await request('/api/connections/exe/'+encodeURIComponent(button.dataset.refreshModels)+'/models',{method:'POST'});button.textContent=result.models.length+' models'}catch(e){button.textContent='Refresh failed';showError(e)}finally{setTimeout(()=>{button.disabled=false;button.textContent='Refresh models'},1500)}});document.querySelectorAll('[data-open-setup]').forEach(button=>button.onclick=()=>{if(button.dataset.openSetup==='tail'){delete $('#tail-connection').dataset.id;$('#tail-connection').reset()}openSetup(button.dataset.openSetup)});document.querySelectorAll('[data-close-setup]').forEach(button=>button.onclick=()=>closeSetup(button.dataset.closeSetup));document.querySelectorAll('dialog').forEach(dialog=>dialog.onclick=e=>{if(e.target===dialog)dialog.close()});document.querySelectorAll('[data-disconnect-github]').forEach(button=>button.onclick=()=>disconnectGitHub(button.dataset.disconnectGithub).catch(showError));document.querySelectorAll('[data-disconnect-tail]').forEach(button=>button.onclick=()=>{if(confirm('Disconnect this Tail installation? Jobs using it will need another installation.'))tailAction(button.dataset.disconnectTail,'DELETE').catch(showError)});document.querySelectorAll('[data-test-tail]').forEach(button=>button.onclick=async()=>{button.disabled=true;try{await request('/api/connections/cloudflare-tail/'+encodeURIComponent(button.dataset.testTail)+'/test',{method:'POST'});button.textContent='Connected'}catch(e){button.textContent='Action required'}finally{button.disabled=false}});document.querySelectorAll('[data-configure-tail]').forEach(button=>button.onclick=()=>{const form=$('#tail-connection');form.dataset.id=button.dataset.configureTail;form.elements.name.value=button.dataset.name;openSetup('tail')})} function showError(e){const error=$('#integration-error');error.textContent=e.message||'The integration action failed.';error.classList.remove('hidden')} function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/connections/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})} -$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});form.reset();m.textContent='Connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; +$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),tags:String(d.get('tags')||'').split(',').map(x=>x.trim()).filter(Boolean)})});form.reset();m.textContent='Connection saved. Each run will receive an isolated VM.';await load()}catch(x){m.textContent=x.message}}; const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});form.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; $('#tail-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#tail-message'),id=form.dataset.id,url='/api/connections/cloudflare-tail'+(id?'/'+encodeURIComponent(id):'');try{const x=await request(url,{method:id?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}form.reset();delete form.dataset.id;m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`); diff --git a/packages/docs/quickstart.mdx b/packages/docs/quickstart.mdx index ad2ae976..569b4ce9 100644 --- a/packages/docs/quickstart.mdx +++ b/packages/docs/quickstart.mdx @@ -5,7 +5,7 @@ description: Configure authentication and create a job end to end. ## Prerequisites -You need a Cloudflare Worker deployment, a Linear OAuth application, an exe.dev VM with Herdr and an agent, and an HTTPS API token restricted to the exact SSH destination used by the VM. Set `APP_ORIGIN`, OAuth credentials, `LINEAR_WEBHOOK_SIGNING_SECRET`, `CREDENTIAL_ENCRYPTION_KEY`, and `SESSION_SIGNING_SECRET`. +You need a Cloudflare Worker deployment, a Linear OAuth application, and an exe.dev account-level HTTPS API token allowed to run `new`, `ssh`, and `rm`. Agents are installed on each newly-created VM. Set `APP_ORIGIN`, OAuth credentials, `LINEAR_WEBHOOK_SIGNING_SECRET`, `CREDENTIAL_ENCRYPTION_KEY`, and `SESSION_SIGNING_SECRET`. Sign in to the dashboard, connect the VM, choose an execution target, and create a job. Use `list_execution_targets` or `GET /api/v1/execution-targets` before submitting `executionTargetId`.