An open-source, faster Devin alternative
TypeScript
api-edge: computer routes as one route family; agent-route 404 copy (work 081)
Igor Zalutski via Computera934a108fc8d
diff --git a/cloudflare-workers/api-edge/src/computer.ts b/cloudflare-workers/api-edge/src/computer.tsindex f324b919..94eb7f47 100644--- a/cloudflare-workers/api-edge/src/computer.ts+++ b/cloudflare-workers/api-edge/src/computer.ts@@ -7,31 +7,10 @@// contract body passes through unchanged while anything the backend adds// beside it (where the machine runs, what size it is) never reaches a browser.-const COMPUTER_ROUTE = /^\/computer(?:\/|$)/;--export function isComputerRouteSuffix(suffix: string): boolean {- return COMPUTER_ROUTE.test(suffix);-}+import type { RouteFamily } from "./route_family";-export function isComputerRoute(method: string, suffix: string): boolean {- if ((method === "GET" || method === "POST") && suffix === "/computer") {- return true;- }- if (method === "GET" && suffix === "/computer/sessions") return true;- if (method === "POST" && suffix === "/computer/slack/install") return true;- if (method === "DELETE" && suffix === "/computer/slack") return true;- // Choose your agent (work 081).- if (- (method === "PUT" || method === "DELETE") &&- suffix === "/computer/agent/claude"- ) {- return true;- }- if (method === "POST" && suffix === "/computer/agent/claude/resume") {- return true;- }- return method === "PUT" && suffix === "/computer/agent/choice";-}+const COMPUTER_ROUTE = /^\/computer(?:\/|$)/;+const COMPUTER_AGENT_ROUTE = /^\/computer\/agent(?:\/|$)/;// The backend's codes are stable; the messages are written here so no// infrastructure detail (cloud, capacity pools, hosts) reaches the dashboard.@@ -62,14 +41,23 @@ export const COMPUTER_ERROR_MESSAGES: Record<string, string> = {computer_agent_disabled: "Your workspace admin turned this off.",computer_agent_not_member:"You're not a member of this organization's Slack workspace.",+ invalid_request: "That choice isn't valid.",};-/** Fallback copy for a computer route when the backend's code is unknown. */-export function computerFallbackMessage(status: number): string {+/**+ * Fallback copy for a computer route when the backend's code is unknown. A+ * 404 on an agent route is an older backend without work 081, not a missing+ * computer, so it reads as the feature being on its way.+ */+function computerFallbackMessage(status: number, suffix: string): string {if (status === 401 || status === 403) {return "You do not have access to this organization's computer.";}- if (status === 404) return "This organization does not have a computer yet.";+ if (status === 404) {+ return COMPUTER_AGENT_ROUTE.test(suffix)+ ? "Connecting a subscription isn't available yet. Try again shortly."+ : "This organization does not have a computer yet.";+ }if (status === 409) {return "Your computer is changing state. Try again in a moment.";}@@ -252,49 +240,103 @@ function publicComputerSession(value: unknown): Record<string, unknown> {};}+function publicComputerSessions(body: Record<string, unknown>) {+ return {+ sessions: Array.isArray(body.sessions)+ ? body.sessions.map(publicComputerSession)+ : [],+ };+}++function publicSlackInstall(body: Record<string, unknown>) {+ const url = httpsURL(body.url);+ if (!url) throw new Error("Invalid Slack install URL");+ return { url };+}++function publicAgentConnect(body: Record<string, unknown>) {+ const via = body.via;+ if (via !== "own" && via !== "pool" && via !== "none") {+ throw new Error("Invalid computer agent connect response");+ }+ return {+ agent: requiredAgent(body.agent),+ verified: body.verified === true,+ via,+ };+}++function publicAgentOnly(body: Record<string, unknown>) {+ return { agent: requiredAgent(body.agent) };+}+/**- * The public body for a successful computer route. Throws on a body that- * cannot honour the contract (the proxy turns that into its generic 502).+ * The contract's routes. `shape` rebuilds the success body from the+ * backend's; `null` means the route answers with no content (unlinking+ * Slack, disconnecting the agent), whatever the backend sent beside 204.*/-export function publicComputerBody(- method: string,- suffix: string,- value: unknown,-): unknown {- const body = record(value) ?? {};- if (suffix === "/computer") return publicComputerStatus(body);- if (method === "GET" && suffix === "/computer/sessions") {- return {- sessions: Array.isArray(body.sessions)- ? body.sessions.map(publicComputerSession)- : [],- };- }- if (method === "POST" && suffix === "/computer/slack/install") {- const url = httpsURL(body.url);- if (!url) throw new Error("Invalid Slack install URL");- return { url };- }- if (method === "PUT" && suffix === "/computer/agent/claude") {- const via = body.via;- if (via !== "own" && via !== "pool" && via !== "none") {- throw new Error("Invalid computer agent connect response");- }- return {- agent: requiredAgent(body.agent),- verified: body.verified === true,- via,- };- }- if (- (method === "POST" && suffix === "/computer/agent/claude/resume") ||- (method === "PUT" && suffix === "/computer/agent/choice")- ) {- return { agent: requiredAgent(body.agent) };- }- throw new Error("Unsupported computer response");+const COMPUTER_ROUTES: ReadonlyArray<{+ method: string;+ suffix: string;+ shape: ((body: Record<string, unknown>) => unknown) | null;+}> = [+ { method: "GET", suffix: "/computer", shape: publicComputerStatus },+ { method: "POST", suffix: "/computer", shape: publicComputerStatus },+ {+ method: "GET",+ suffix: "/computer/sessions",+ shape: publicComputerSessions,+ },+ {+ method: "POST",+ suffix: "/computer/slack/install",+ shape: publicSlackInstall,+ },+ { method: "DELETE", suffix: "/computer/slack", shape: null },+ // Choose your agent (work 081).+ {+ method: "PUT",+ suffix: "/computer/agent/claude",+ shape: publicAgentConnect,+ },+ { method: "DELETE", suffix: "/computer/agent/claude", shape: null },+ {+ method: "POST",+ suffix: "/computer/agent/claude/resume",+ shape: publicAgentOnly,+ },+ { method: "PUT", suffix: "/computer/agent/choice", shape: publicAgentOnly },+];++function computerRoute(method: string, suffix: string) {+ return COMPUTER_ROUTES.find(+ (route) => route.method === method && route.suffix === suffix,+ );}+export const computerFamily: RouteFamily = {+ owns: (suffix) => COMPUTER_ROUTE.test(suffix),+ allows: (method, suffix) => computerRoute(method, suffix) !== undefined,+ // A dashboard surface in v1: API keys do not reach it.+ dashboardOnly: true,+ enabledFor: computerEnabledFor,+ async shapeSuccess(method, suffix, upstream) {+ const route = computerRoute(method, suffix);+ if (!route) throw new Error("Unsupported computer response");+ const headers = { "cache-control": "no-store" };+ if (!route.shape) return new Response(null, { status: 204, headers });+ const body = record(await upstream.json()) ?? {};+ return Response.json(route.shape(body), {+ status: upstream.status,+ headers,+ });+ },+ errorMessage: (code, status, suffix) =>+ Object.hasOwn(COMPUTER_ERROR_MESSAGES, code)+ ? COMPUTER_ERROR_MESSAGES[code]+ : computerFallbackMessage(status, suffix),+};+/*** Whether an organization has its computer (work 052 rollout). Until* COMPUTER_ENABLED_FOR_ALL is "true", only organizations listed indiff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 88529d3b..fa636baf 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -6876,6 +6876,51 @@ describe("organization computer (work 052)", () => {await expect(response.json()).resolves.toEqual({ error: { code, message } });});+ it("tells a bad choice apart from a missing computer", async () => {+ const { response } = await call(+ "PUT",+ "/computer/agent/choice",+ Response.json(+ { error: { code: "invalid_request", message: "choice must be one of claude|codex|credits (got gemini)" } },+ { status: 400 },+ ),+ );+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toEqual({+ error: { code: "invalid_request", message: "That choice isn't valid." },+ });+ });++ it.each([+ ["PUT", "/computer/agent/claude"],+ ["POST", "/computer/agent/claude/resume"],+ ["PUT", "/computer/agent/choice"],+ ])("reads a 404 on %s %s as the feature not being there yet", async (method, path) => {+ const { response } = await call(+ method,+ path,+ Response.json({ error: "route not found" }, { status: 404 }),+ );+ expect(response.status).toBe(404);+ const body = (await response.json()) as { error: { message: string } };+ expect(body.error.message).toBe(+ "Connecting a subscription isn't available yet. Try again shortly.",+ );+ });++ it("keeps the missing-computer copy for a 404 off the agent routes", async () => {+ const { response } = await call(+ "GET",+ "/computer/sessions",+ Response.json({ error: "route not found" }, { status: 404 }),+ );+ expect(response.status).toBe(404);+ const body = (await response.json()) as { error: { message: string } };+ expect(body.error.message).toBe(+ "This organization does not have a computer yet.",+ );+ });+it("keeps the computer off the API-key mount", async () => {const { response, fetchMock } = await call("GET",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 4f6a897c..f638f9e5 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -1,13 +1,7 @@import { getAutumnCustomer } from "./autumn_webhook";import { FREE_CREDITS_PAYWALL } from "./billing_onramp";-import {- COMPUTER_ERROR_MESSAGES,- computerFallbackMessage,- computerEnabledFor,- isComputerRoute,- isComputerRouteSuffix,- publicComputerBody,-} from "./computer";+import { computerFamily } from "./computer";+import type { RouteFamily } from "./route_family";export interface ManagedAgentsEnv {/** Computer rollout (work 052): see computerEnabledFor. */@@ -296,14 +290,16 @@ async function publicErrorResponse(Object.hasOwn(LINEAR_ROUTE_ERROR_MESSAGES, backendCode)? LINEAR_ROUTE_ERROR_MESSAGES[backendCode]: undefined;- const computerMessage =- suffix !== undefined && isComputerRouteSuffix(suffix)- ? Object.hasOwn(COMPUTER_ERROR_MESSAGES, backendCode)- ? COMPUTER_ERROR_MESSAGES[backendCode]- : computerFallbackMessage(upstream.status)+ const familyMessage =+ suffix !== undefined+ ? routeFamilyFor(suffix)?.errorMessage(+ backendCode,+ upstream.status,+ suffix,+ ): undefined;- if (computerMessage) {- message = computerMessage;+ if (familyMessage) {+ message = familyMessage;} else if (slackSetupMessage) {message = slackSetupMessage;} else if (deploymentSourceMessage) {@@ -2719,9 +2715,18 @@ export function isGrantRoute(method: string, suffix: string): boolean {);}+// The route families the proxy dispatches to as a unit (see route_family.ts).+// Only the organization's computer so far (work 052); the other surfaces keep+// their branches below until each is ported.+const ROUTE_FAMILIES: ReadonlyArray<RouteFamily> = [computerFamily];++function routeFamilyFor(suffix: string): RouteFamily | undefined {+ return ROUTE_FAMILIES.find((family) => family.owns(suffix));+}+function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {- // The organization's computer: only the contract's routes (work 052).- if (isComputerRouteSuffix(suffix)) return isComputerRoute(method, suffix);+ const family = routeFamilyFor(suffix);+ if (family) return family.allows(method, suffix);if (method === "GET" && suffix === "/account/runtime-profile") return true;if (method === "POST" && suffix === "/template-inspections") return true;if (method === "POST" && suffix === "/template-installations") return true;@@ -3589,11 +3594,12 @@ export async function proxyManagedAgents({ status: 403 },);}- // The computer is a dashboard surface in v1; API keys do not reach it.+ const family = routeFamilyFor(suffix);if (- isComputerRouteSuffix(suffix) &&- (publicPrefix !== DASHBOARD_MANAGED_AGENTS_PREFIX ||- !computerEnabledFor(env, caller.orgID))+ family &&+ ((family.dashboardOnly &&+ publicPrefix !== DASHBOARD_MANAGED_AGENTS_PREFIX) ||+ family.enabledFor?.(env, caller.orgID) === false)) {return Response.json({ error: "route not found" }, { status: 404 });}@@ -3790,19 +3796,7 @@ export async function proxyManagedAgents(}if (!upstream.ok) return publicErrorResponse(upstream, suffix);if (upstream.status === 204) return new Response(null, { status: 204 });- if (isComputerRouteSuffix(suffix)) {- // Unlinking Slack and disconnecting the agent have no response body.- if (method === "DELETE") {- return new Response(null, {- status: 204,- headers: { "cache-control": "no-store" },- });- }- return Response.json(- publicComputerBody(method, suffix, await upstream.json()),- { status: upstream.status, headers: { "cache-control": "no-store" } },- );- }+ if (family) return await family.shapeSuccess(method, suffix, upstream);if (/^\/projects\/[^/]+\/source-archive$/.test(suffix) ||WORKSPACE_ARTIFACT_CONTENT_ROUTE.test(suffix)diff --git a/cloudflare-workers/api-edge/src/route_family.ts b/cloudflare-workers/api-edge/src/route_family.tsnew file mode 100644index 00000000..593b31ad--- /dev/null+++ b/cloudflare-workers/api-edge/src/route_family.ts@@ -0,0 +1,33 @@+// A route family is one backend surface the edge proxies as a unit: which+// routes it allows, who may reach them and how their replies are shaped.+// `proxyManagedAgents` looks a request's family up once and dispatches to it,+// instead of branching per route at each of those four points.+//+// Only the organization's computer (./computer.ts) is a family so far. The+// Slack-setup, deployment-source, Linear and workspace-export routes still+// take the hand-written branches in managed_agents.ts; each can be ported to+// this interface on its own, without changing the others' behaviour.++import type { ManagedAgentsEnv } from "./managed_agents";++export interface RouteFamily {+ /** Whether the suffix is this family's, whatever the method. */+ owns(suffix: string): boolean;+ /** Whether the method and suffix are a route in the family's contract. */+ allows(method: string, suffix: string): boolean;+ /** Only the dashboard mount reaches the family; API keys get a 404. */+ dashboardOnly: boolean;+ /** Whether the organization has the family (rollouts); true when absent. */+ enabledFor?(env: ManagedAgentsEnv, orgID: string | null | undefined): boolean;+ /**+ * The public response for a successful upstream reply. Throws on a body+ * that cannot honour the contract; the proxy turns that into its 502.+ */+ shapeSuccess(+ method: string,+ suffix: string,+ upstream: Response,+ ): Promise<Response>;+ /** Fixed copy for an upstream refusal; no backend detail passes through. */+ errorMessage(code: string, status: number, suffix: string): string;+}