An open-source, faster Devin alternative
TypeScript
wip
Brian Reardonce4c8e34d161
diff --git a/.gitignore b/.gitignoreindex 8ffca6f1..fbb509bf 100644--- a/.gitignore+++ b/.gitignore@@ -81,3 +81,9 @@ deploy/azure/.dev-vector-token-*/server/seed-dev-secrets/backfill++# Claude Code agent memory (session-local, not source)+/memory/++# Per-env wrangler config generated for CI deploys (not source)+cloudflare-workers/api-edge/wrangler.ci.tomldiff --git a/cloudflare-workers/vm-do-poc/bench-from-guest.mjs b/cloudflare-workers/vm-do-poc/bench-from-guest.mjsnew file mode 100644index 00000000..a87ec6bd--- /dev/null+++ b/cloudflare-workers/vm-do-poc/bench-from-guest.mjs@@ -0,0 +1,53 @@+#!/usr/bin/env node+// Run the TTI benchmark from INSIDE a dev sandbox (client in westus2, same+// region as the POC fleet + wnam DOs) — reproduces the colleague's aligned+// client→ingress→DO→VM geometry instead of a laptop across the triangle.+import { readFile } from "node:fs/promises";+import { Sandbox } from "@opencomputer/sdk";++const apiKey = process.env.OPENCOMPUTER_API_KEY;+const apiUrl = process.env.OPENCOMPUTER_API_URL ?? "https://app2.opensandbox.ai";+const pocUrl = process.env.OC_DO_HTTP_URL;+const benchToken = process.env.OC_POC_BENCH_TOKEN;+const iters = process.env.BENCH_ITERS ?? "29";+const conc = process.env.BENCH_CONC ?? "29";+const mode = process.env.BENCH_MODE ?? ""; // empty = all modes+if (!apiKey || !pocUrl || !benchToken) {+ console.error("OPENCOMPUTER_API_KEY, OC_DO_HTTP_URL, OC_POC_BENCH_TOKEN required");+ process.exit(2);+}++const benchSource = await readFile(new URL("../../benchmarks/tti/bench.mjs", import.meta.url), "utf8");++// 2/8192 tier so the 29-wide client fan-out isn't throttled by a 1-vCPU guest.+const sandbox = await Sandbox.create({ apiUrl, apiKey, template: "base", timeout: 3600, cpuCount: 2, memoryMB: 8192 });+console.error(`client sandbox: ${sandbox.sandboxId}`);+try {+ const dir = "/home/sandbox/ttibench";+ // mkdir + npm via exec BEFORE files.write — the files API and exec sessions+ // run as different users; an API-created dir breaks npm (same pattern as+ // provision-vm.mjs).+ const install = await sandbox.exec.run(+ `mkdir -p ${dir} && cd ${dir} && npm init -y && npm install --no-audit --no-fund @computesdk/opencomputer computesdk`,+ { timeout: 240 },+ );+ await sandbox.files.write(`${dir}/bench.mjs`, benchSource);+ console.error(`npm: exit=${install.exitCode} out=${install.stdout.slice(-200).trim()} err=${install.stderr.slice(-400).trim()}`);+ if (install.exitCode !== 0) throw new Error(`npm install failed (${install.exitCode})`);++ const where = await sandbox.exec.run(+ "curl -sS -m 10 https://www.cloudflare.com/cdn-cgi/trace | grep -E 'colo|ip' | head -2",+ { timeout: 30 },+ );+ console.error(`guest CF ingress: ${where.stdout.trim().replaceAll("\n", " ")}`);++ const modeArg = mode ? `--mode ${mode}` : "";+ const run = await sandbox.exec.run(+ `cd ${dir} && OPENCOMPUTER_API_URL=${pocUrl} OPENCOMPUTER_API_KEY=${benchToken} node bench.mjs ${modeArg} --iterations ${iters} --concurrency ${conc} 2>&1 | tail -14`,+ { timeout: 900, timeoutMs: 900_000 },+ );+ console.log(run.stdout);+ if (run.exitCode !== 0) console.error(`bench exit=${run.exitCode} stderr: ${run.stderr.slice(0, 500)}`);+} finally {+ await sandbox.kill().catch(() => {});+}diff --git a/cloudflare-workers/vm-do-poc/src/index.ts b/cloudflare-workers/vm-do-poc/src/index.tsindex 96e7b20c..be2b8f54 100644--- a/cloudflare-workers/vm-do-poc/src/index.ts+++ b/cloudflare-workers/vm-do-poc/src/index.ts@@ -105,7 +105,14 @@ export class VmSession extends DurableObject<WorkerEnv> {}private async run(command: string, cwd: string, env: Record<string, string>, timeoutMs: number): Promise<ExecResult> {- const socket = this.connectedSocket();+ // Reconnect grace: a dropped socket takes the agent one backoff cycle to+ // redial (250ms-10s). Waiting briefly here turns that window from a hard+ // 500 into a slightly slower exec.+ let socket = this.connectedSocket();+ for (let waited = 0; !socket && waited < 3_000; waited += 100) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ socket = this.connectedSocket();+ }if (!socket) throw new Error("warm VM is not connected");const requestId = this.nextRequestId++ >>> 0 || 1;const result = new Promise<ExecResult>((resolve, reject) => {@@ -151,7 +158,12 @@ export class VmSession extends DurableObject<WorkerEnv> {}function stubFor(env: WorkerEnv, sandboxId: string): DurableObjectStub {- return env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(sandboxId), { locationHint: "enam" });+ // Placement hint is config, not code: the DO must sit in the same region as+ // the VM it fronts (the persistent WS is the long-lived hop; the Worker→DO+ // leg rides Cloudflare's backbone from any ingress colo). enam matches the+ // original IAD/eastus2 proof; our dev VMs are westus2 → wnam.+ const hint = (env.DO_LOCATION_HINT || "enam") as DurableObjectLocationHint;+ return env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(sandboxId), { locationHint: hint });}async function requireApiAuth(request: Request, env: WorkerEnv): Promise<Response | null> {@@ -160,6 +172,78 @@ async function requireApiAuth(request: Request, env: WorkerEnv): Promise<Respons: json({ error: "unauthorized" }, { status: 401 });}+// VmRoster is the minimal real allocator the single-VM floor test deferred:+// one DO instance holding the fleet of provisioned VM ids with leased/free+// state. create leases (one DO hop — the allocation cost the floor numbers+// omit), DELETE releases. Leases self-expire so a crashed benchmark run can't+// wedge the roster.+const LEASE_TTL_MS = 120_000;++export class VmRoster extends DurableObject<WorkerEnv> {+ private ids: string[] = [];+ private leases = new Map<string, number>(); // id -> leasedAt ms++ constructor(ctx: DurableObjectState, env: WorkerEnv) {+ super(ctx, env);+ this.ctx.blockConcurrencyWhile(async () => {+ this.ids = (await this.ctx.storage.get<string[]>("ids")) ?? [];+ this.leases = new Map(Object.entries((await this.ctx.storage.get<Record<string, number>>("leases")) ?? {}));+ });+ }++ private persist(): void {+ void this.ctx.storage.put("ids", this.ids);+ void this.ctx.storage.put("leases", Object.fromEntries(this.leases));+ }++ async fetch(request: Request): Promise<Response> {+ const url = new URL(request.url);+ const now = Date.now();+ for (const [id, at] of this.leases) if (now - at > LEASE_TTL_MS) this.leases.delete(id);++ if (url.pathname === "/seed" && request.method === "POST") {+ const body = (await request.json()) as { ids?: string[] };+ this.ids = [...new Set(body.ids ?? [])];+ this.leases.clear();+ this.persist();+ return json({ total: this.ids.length });+ }+ if (url.pathname === "/lease" && request.method === "POST") {+ const free = this.ids.find((id) => !this.leases.has(id));+ if (!free) return json({ error: "roster exhausted" }, { status: 409 });+ this.leases.set(free, now);+ this.persist();+ return json({ id: free });+ }+ if (url.pathname === "/release" && request.method === "POST") {+ const body = (await request.json()) as { id?: string };+ if (body.id) {+ this.leases.delete(body.id);+ this.persist();+ }+ return json({ ok: true });+ }+ if (url.pathname === "/known" && request.method === "POST") {+ const body = (await request.json()) as { id?: string };+ return json({ known: !!body.id && this.ids.includes(body.id) });+ }+ if (url.pathname === "/status") {+ return json({ total: this.ids.length, leased: this.leases.size });+ }+ return new Response("not found", { status: 404 });+ }+}++function rosterStub(env: WorkerEnv): DurableObjectStub {+ const hint = (env.DO_LOCATION_HINT || "enam") as DurableObjectLocationHint;+ return env.VM_ROSTER.get(env.VM_ROSTER.idFromName("roster"), { locationHint: hint });+}++// No per-id addressability gate: the bench token is the auth, and the roster's+// job is ALLOCATION (create leases, DELETE releases), not access control. An+// exec against an id with no connected agent fails in the DO ("warm VM is not+// connected") — no roster hop on the hot path.+export default {async fetch(request: Request, env: WorkerEnv): Promise<Response> {const url = new URL(request.url);@@ -167,7 +251,10 @@ export default {const connectMatch = url.pathname.match(/^\/internal\/vms\/([^/]+)\/connect$/);if (connectMatch && request.headers.get("upgrade")?.toLowerCase() === "websocket") {- if (connectMatch[1] !== env.POC_VM_ID || !(await tokenMatches(socketSecret(request), env.VM_CONNECT_SECRET))) {+ // Secret-only auth: agents connect before the roster is seeded (the+ // roster gates the API surface, not the VM-side dial). An id that never+ // joins the roster is simply unreachable.+ if (!(await tokenMatches(socketSecret(request), env.VM_CONNECT_SECRET))) {return new Response("unauthorized", { status: 401 });}return stubFor(env, connectMatch[1]).fetch(new Request("https://do/connect", request));@@ -177,7 +264,8 @@ export default {if (bootstrapMatch && request.method === "POST") {const denied = await requireApiAuth(request, env);if (denied) return denied;- if (bootstrapMatch[1] !== env.POC_VM_ID) return json({ error: "not found" }, { status: 404 });+ // No roster gate: bootstrap is the provisioning probe and runs BEFORE+ // the id joins the roster (bench-token auth is sufficient).const startedAt = performance.now();const response = await stubFor(env, bootstrapMatch[1]).fetch("https://do/lease");const lease = (await response.json()) as { connected: boolean };@@ -193,33 +281,59 @@ export default {if (locationMatch && request.method === "GET") {const denied = await requireApiAuth(request, env);if (denied) return denied;- if (locationMatch[1] !== env.POC_VM_ID) return json({ error: "not found" }, { status: 404 });+ // No roster gate — same reasoning as bootstrap.return stubFor(env, locationMatch[1]).fetch("https://do/location");}const denied = await requireApiAuth(request, env);if (denied) return denied;+ if (url.pathname === "/internal/roster/seed" && request.method === "POST") {+ return rosterStub(env).fetch("https://do/seed", { method: "POST", headers: { "content-type": "application/json" }, body: request.body });+ }+ if (url.pathname === "/internal/roster/status") {+ return rosterStub(env).fetch("https://do/status");+ }+if (url.pathname === "/api/sandboxes" && request.method === "POST") {+ // Real allocation: lease a VM from the roster (one DO round trip — the+ // cost the single-VM floor test omitted). Falls back to the static+ // single-VM flow when no roster is seeded.const startedAt = performance.now();+ let vmId = env.POC_VM_ID;+ const lease = await rosterStub(env).fetch("https://do/lease", { method: "POST" });+ if (lease.ok) {+ vmId = ((await lease.json()) as { id: string }).id;+ } else if (lease.status === 409) {+ const status = await (await rosterStub(env).fetch("https://do/status")).json<{ total: number }>();+ if (status.total > 0) return json({ error: "no VMs available" }, { status: 503 });+ // total 0 → roster never seeded → static single-VM fallback+ }return json({- sandboxID: env.POC_VM_ID,+ sandboxID: vmId,status: "running",templateID: "base",- connectURL: `${url.origin}/api/sandboxes/${env.POC_VM_ID}`,+ connectURL: `${url.origin}/api/sandboxes/${vmId}`,token: env.BENCH_API_TOKEN,pocTiming: { createEdgeMs: performance.now() - startedAt },});}const sandboxMatch = url.pathname.match(/^\/api\/sandboxes\/([^/]+)$/);- if (sandboxMatch && sandboxMatch[1] === env.POC_VM_ID) {- if (request.method === "GET") return json({ sandboxID: env.POC_VM_ID, status: "running" });- if (request.method === "DELETE") return new Response(null, { status: 204 });+ if (sandboxMatch) {+ if (request.method === "GET") return json({ sandboxID: sandboxMatch[1], status: "running" });+ if (request.method === "DELETE") {+ await rosterStub(env).fetch("https://do/release", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ id: sandboxMatch[1] }),+ });+ return new Response(null, { status: 204 });+ }}const execMatch = url.pathname.match(/^\/api\/sandboxes\/([^/]+)\/exec\/run-async$/);- if (execMatch && execMatch[1] === env.POC_VM_ID && request.method === "POST") {+ if (execMatch && request.method === "POST") {const response = await stubFor(env, execMatch[1]).fetch("https://do/exec", {method: "POST",headers: { "content-type": "application/json" },diff --git a/cloudflare-workers/vm-do-poc/vm-agent.mjs b/cloudflare-workers/vm-do-poc/vm-agent.mjsindex 3d38ad4e..653a334f 100644--- a/cloudflare-workers/vm-do-poc/vm-agent.mjs+++ b/cloudflare-workers/vm-do-poc/vm-agent.mjs@@ -172,6 +172,37 @@ function connect() {retryMs = 250;console.log(`connected to ${new URL(url).host}`);if (probeOnly) socket.close(1000, "probe complete");+ // Keepalive: idle WebSockets get dropped by intermediaries (observed+ // ~90-120s on CF), and every silent drop is a hard-fail window until the+ // reconnect lands. Protocol-level pings are answered by the Cloudflare+ // runtime without waking the (hibernated) Durable Object. Only the `ws`+ // package exposes ping(); the global WebSocket (Node >=22) has no+ // client-initiated ping, so there we fall back to nothing rather than+ // corrupt the protobuf stream with app-level frames.+ if (typeof socket.ping === "function") {+ // Ping alone is not liveness: on a half-open TCP (DO evicted, FIN lost)+ // pings vanish silently and the socket looks OPEN forever — the agent+ // wedges "connected" while the DO reports no socket. Track pongs and+ // terminate() after ~2.5 missed intervals so the close event fires and+ // the reconnect loop takes over.+ let lastPong = Date.now();+ if (typeof socket.on === "function") socket.on("pong", () => (lastPong = Date.now()));+ const keepalive = setInterval(() => {+ if (Date.now() - lastPong > 75_000) {+ console.error("pong timeout — terminating wedged socket");+ clearInterval(keepalive);+ if (typeof socket.terminate === "function") socket.terminate();+ else socket.close(4000, "pong timeout");+ return;+ }+ try {+ socket.ping();+ } catch {+ clearInterval(keepalive);+ }+ }, 30_000);+ socket.addEventListener("close", () => clearInterval(keepalive));+ }});socket.addEventListener("message", async (event) => {let request;diff --git a/cloudflare-workers/vm-do-poc/worker-configuration.d.ts b/cloudflare-workers/vm-do-poc/worker-configuration.d.tsindex 343f4607..66e53a6c 100644--- a/cloudflare-workers/vm-do-poc/worker-configuration.d.ts+++ b/cloudflare-workers/vm-do-poc/worker-configuration.d.ts@@ -2,8 +2,10 @@// Generated by Wrangler by running `wrangler types` (hash: 25b8bef949716b18f45a0af63abcbfea)// Runtime types generated with [email protected] 2026-08-02 nodejs_compatinterface __BaseEnv_Env {- POC_VM_ID: "vm-1";+ POC_VM_ID: string;+ DO_LOCATION_HINT?: string;VM_SESSIONS: DurableObjectNamespace<import("./src/index").VmSession>;+ VM_ROSTER: DurableObjectNamespace<import("./src/index").VmRoster>;}declare namespace Cloudflare {interface GlobalProps {diff --git a/cloudflare-workers/vm-do-poc/wrangler.dev.jsonc b/cloudflare-workers/vm-do-poc/wrangler.dev.jsoncnew file mode 100644index 00000000..11747feb--- /dev/null+++ b/cloudflare-workers/vm-do-poc/wrangler.dev.jsonc@@ -0,0 +1,42 @@+{+ "$schema": "node_modules/wrangler/config-schema.json",+ // OpenSandbox dev-account deployment of the VM↔DO POC (iteration copy of the+ // personal-account config in wrangler.jsonc). workers.dev URL — no DNS/cert.+ // POC_VM_ID is stamped per provisioned sandbox before deploy.+ "name": "opensandbox-vm-do-poc-dev",+ "main": "src/index.ts",+ "compatibility_date": "2026-08-02",+ "compatibility_flags": ["nodejs_compat"],+ "account_id": "1241f114453e32d292197e3fb36210b2",+ "workers_dev": true,+ "durable_objects": {+ "bindings": [+ {+ "name": "VM_SESSIONS",+ "class_name": "VmSession"+ },+ {+ "name": "VM_ROSTER",+ "class_name": "VmRoster"+ }+ ]+ },+ "migrations": [+ {+ "tag": "v1",+ "new_sqlite_classes": ["VmSession"]+ },+ {+ "tag": "v2",+ "new_sqlite_classes": ["VmRoster"]+ }+ ],+ "vars": {+ "POC_VM_ID": "sb-ac0af601-w2",+ "DO_LOCATION_HINT": "wnam"+ },+ "observability": {+ "enabled": true,+ "head_sampling_rate": 1+ }+}