An open-source, faster Devin alternative
TypeScript
api-edge: one edge.request per computer API request (work 084 instrumentation)
Igor Zalutski via Computer1142cdcbd61e
diff --git a/cloudflare-workers/api-edge/src/computer_api.test.ts b/cloudflare-workers/api-edge/src/computer_api.test.tsindex 2433325a..53c98165 100644--- a/cloudflare-workers/api-edge/src/computer_api.test.ts+++ b/cloudflare-workers/api-edge/src/computer_api.test.ts@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import worker, { type Env } from "./index";import { hashAPIKey } from "./api_keys";import { computerApiFamily, isComputerApiRoute } from "./computer_api";+import { computerApiRouteFamily } from "./computer_telemetry";const ORG = "22222222-2222-4222-8222-222222222222";const USER = "11111111-1111-4111-8111-111111111111";@@ -900,3 +901,189 @@ describe("key create and revoke tell blue", () => {expect(fetchMock).not.toHaveBeenCalled();});});++describe("computer API telemetry: one edge.request per call", () => {+ const TB = "https://tb.test";+ const SID = "cs_0123456789abcdef";+ const tbEnv = (db: FakeDB, extra: Partial<Record<string, unknown>> = {}) =>+ testEnv(db, {+ TINYBIRD_API_URL: TB,+ TINYBIRD_APPEND_TOKEN: "p.test-append",+ CF_VERSION_METADATA: { id: "v-123" },+ ...extra,+ });++ /** Blue answers with its Server-Timing; Tinybird's POSTs are collected. */+ function stubFetch(blue: () => Response = () =>+ Response.json({ ok: true }, { headers: { "server-timing": "blue;dur=12.6" } })) {+ const lines: Record<string, unknown>[] = [];+ const fetchMock = vi.fn(async (url: string | URL, init?: RequestInit) => {+ if (String(url).startsWith(TB)) {+ expect(String(url)).toBe(`${TB}/v0/events?name=calvin_events&wait=false`);+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer p.test-append");+ for (const l of String(init?.body).split("\n")) lines.push(JSON.parse(l));+ return new Response("{}", { status: 202 });+ }+ return blue();+ });+ vi.stubGlobal("fetch", fetchMock);+ return { fetchMock, lines };+ }++ const dataOf = (line: Record<string, unknown>) => JSON.parse(String(line.data)) as Record<string, unknown>;++ it("reports a proxied call: route family, status, upstream, blue_ms, ids only, via waitUntil", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const { lines } = stubFetch();+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(+ api(`/sessions/${SID}/events?after=ev_1&wait=30`, { headers: { "x-api-key": key, "user-agent": "opc/1.2.3" } }),+ tbEnv(db),+ ctx,+ );+ expect(res.status).toBe(200);+ expect(ctx.waitUntil).toHaveBeenCalled(); // off the response path+ await settle();+ expect(lines).toHaveLength(1);+ const [e] = lines;+ expect(e).toMatchObject({+ schema_version: 1,+ event_name: "edge.request",+ service_name: "edge",+ service_version: "v-123",+ surface: "cli",+ session_key: SID,+ org_id: ORG,+ outcome: "completed",+ synthetic: false,+ });+ expect(typeof e.duration_ms).toBe("number");+ expect(dataOf(e)).toEqual({+ route: "events",+ method: "GET",+ status: 200,+ upstream: "blue",+ auth: "ok",+ via: "key",+ rate_limited: false,+ blue_ms: 13,+ key_id: db.keys.get(await hashAPIKey(key))!.id,+ });+ // Data policy: no paths, query strings, key secrets, user agents or IPs.+ const text = JSON.stringify(e);+ expect(text).not.toContain(key);+ expect(text).not.toContain("/");+ expect(text).not.toContain("ev_1");+ expect(text).not.toContain("opc/1.2.3");+ });++ it.each([+ ["missing", {}, 401],+ ["invalid", { "x-api-key": "osb_nope" }, 401],+ ["conflicting", { "x-api-key": "osb_a", authorization: "Bearer osb_b" }, 401],+ ] as const)("classes a refused caller: %s", async (auth, headers, status) => {+ const { lines } = stubFetch();+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(api("/me", { headers }), tbEnv(new FakeDB()), ctx);+ expect(res.status).toBe(status);+ await settle();+ expect(lines).toHaveLength(1);+ expect(lines[0]).toMatchObject({ outcome: "failed", error_code: String(status) });+ expect(lines[0]).not.toHaveProperty("org_id");+ expect(dataOf(lines[0])).toMatchObject({ route: "me", status, upstream: "edge", auth, rate_limited: false });+ });++ it("marks a rate-limited key", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const { lines } = stubFetch();+ const { ctx, settle } = testCtx();+ const limit = vi.fn().mockResolvedValue({ success: false });+ const res = await worker.fetch(+ api("/sessions", { headers: { "x-api-key": key } }),+ tbEnv(db, { COMPUTER_API_RATE_LIMIT: { limit } }),+ ctx,+ );+ expect(res.status).toBe(429);+ await settle();+ expect(dataOf(lines[0])).toMatchObject({ route: "sessions", status: 429, upstream: "edge", auth: "ok", rate_limited: true });+ });++ it("names a dashboard call that needs a key, and the wire Worker as upstream", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const { lines } = stubFetch(() => new Response("x", { status: 200 }));+ const cookie = await sessionCookie();+ let t = testCtx();+ await worker.fetch(api(`/sessions/${SID}/workspace/file?path=a`, { headers: { cookie } }), tbEnv(db), t.ctx);+ await t.settle();+ t = testCtx();+ await worker.fetch(api(`/sessions/${SID}/workspace/file?path=a`, { headers: { "x-api-key": key } }), tbEnv(db), t.ctx);+ await t.settle();+ expect(lines.map(dataOf)).toEqual([+ expect.objectContaining({ route: "workspace", status: 403, auth: "key_required", via: "dashboard", upstream: "edge" }),+ expect.objectContaining({ route: "workspace", status: 200, auth: "ok", via: "key", upstream: "wire" }),+ ]);+ expect(dataOf(lines[1])).not.toHaveProperty("blue_ms");+ });++ it("sends nothing when Tinybird is not configured", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const { fetchMock, lines } = stubFetch();+ const { ctx, settle } = testCtx();+ await worker.fetch(api("/me", { headers: { "x-api-key": key } }), testEnv(db), ctx);+ await worker.fetch(api("/me", { headers: { "x-api-key": key } }), tbEnv(db, { TINYBIRD_APPEND_TOKEN: " " }), ctx);+ await settle();+ expect(lines).toHaveLength(0);+ expect(fetchMock).toHaveBeenCalledTimes(2); // blue only+ });++ it("never fails the call when Tinybird does", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ let tbCalls = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string | URL) => {+ if (String(url).startsWith(TB)) {+ tbCalls += 1;+ throw new Error("down");+ }+ return Response.json({ ok: true });+ }),+ );+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(api("/me", { headers: { "x-api-key": key } }), tbEnv(db), ctx);+ expect(res.status).toBe(200);+ await settle();+ expect(tbCalls).toBe(2); // one retry, then dropped+ });++ it("maps every documented route to a family", () => {+ expect(+ [+ "/computer/me",+ "/computer/tickets",+ "/computer/sessions",+ `/computer/sessions/${SID}`,+ `/computer/sessions/${SID}/capabilities`,+ `/computer/sessions/${SID}/interrupt`,+ `/computer/sessions/${SID}/turns/tn_1/cancel`,+ `/computer/sessions/${SID}/events`,+ `/computer/sessions/${SID}/asks/toolu_1/answer`,+ `/computer/sessions/${SID}/subagents`,+ "/computer/secrets",+ "/computer/me/secrets/X",+ "/computer/organization/secrets/X",+ `/computer/sessions/${SID}/secrets/X`,+ `/computer/sessions/${SID}/workspace/archive`,+ "/computer/nope",+ ].map(computerApiRouteFamily),+ ).toEqual([+ "me", "tickets", "sessions", "sessions", "sessions", "control", "turns", "events", "asks",+ "subagents", "secrets", "secrets", "secrets", "secrets", "workspace", "other",+ ]);+ });+});diff --git a/cloudflare-workers/api-edge/src/computer_telemetry.ts b/cloudflare-workers/api-edge/src/computer_telemetry.tsnew file mode 100644index 00000000..f19c9722--- /dev/null+++ b/cloudflare-workers/api-edge/src/computer_telemetry.ts@@ -0,0 +1,210 @@+// The computer API's edge telemetry (serverless-agents-ws work 084, instrumentation;+// the contract is the calvin catalog's "blue and edge" section). One `edge.request`+// per /api/managed-agents/computer/* request: route family, method, status,+// where it went (blue, the wire Worker, or answered here), blue's own time from+// its `Server-Timing: blue;dur=`, why the edge refused it, and whether the+// per-key rate limit did.+//+// Dumb dump: one event per request, no sums or windows here; Tinybird aggregates.+// The line goes to Tinybird's Events API (`calvin_events`, the envelope blue's+// gateway emitter writes) through `ctx.waitUntil`, never awaited on the request.+// Off (nothing built, nothing sent) unless TINYBIRD_API_URL and+// TINYBIRD_APPEND_TOKEN are both set.+//+// Data policy (work 054): ids only. No paths, bodies, key secrets or hashes,+// tickets, IPs or user agents; the route is a family name, never the URL.++export interface EdgeTelemetryEnv {+ TINYBIRD_API_URL?: string;+ TINYBIRD_APPEND_TOKEN?: string;+ CF_VERSION_METADATA?: { id?: string };+}++/** Why the edge refused the caller, or `ok`. */+export type EdgeAuth =+ | "ok"+ | "missing"+ | "invalid"+ | "conflicting"+ | "project_key"+ | "not_member"+ | "origin"+ | "key_required"+ | "disabled"+ | "none";++/** What the edge learns about one request while it handles it. */+export interface EdgeRequestFacts {+ started: number;+ auth: EdgeAuth;+ via: "key" | "dashboard" | "none";+ upstream: "blue" | "wire" | "edge";+ rateLimited: boolean;+ orgId?: string;+ keyId?: string;+}++export function newEdgeRequestFacts(now = Date.now()): EdgeRequestFacts {+ return { started: now, auth: "none", via: "none", upstream: "edge", rateLimited: false };+}++const POST_TIMEOUT_MS = 5_000;+const METHODS = new Set(["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"]);+const ID = /^[A-Za-z0-9_-]{1,64}$/;+const SESSION = /^\/computer\/sessions\/(cs_[0-9a-hjkmnp-tv-z]{16})(?:\/|$)/;++export function edgeTelemetryEnabled(env: EdgeTelemetryEnv): boolean {+ return Boolean(env.TINYBIRD_API_URL?.trim() && env.TINYBIRD_APPEND_TOKEN?.trim());+}++/** The route family of a computer API suffix (`/computer/...`), as blue's `httpapi.request` names them. */+export function computerApiRouteFamily(suffix: string): string {+ const parts = suffix.split("/").filter(Boolean); // ["computer", ...]+ const [, first, , third] = parts;+ if (first === "me") return parts.length === 2 ? "me" : "secrets";+ if (first === "tickets") return "tickets";+ if (first === "secrets" || first === "organization") return "secrets";+ if (first !== "sessions") return "other";+ if (parts.length <= 3) return "sessions";+ switch (third) {+ case "capabilities":+ return "sessions";+ case "interrupt":+ case "compact":+ case "suspend":+ case "resume":+ return "control";+ case "turns":+ return "turns";+ case "events":+ return "events";+ case "asks":+ return "asks";+ case "subagents":+ return "subagents";+ case "secrets":+ return "secrets";+ case "workspace":+ return "workspace";+ default:+ return "other";+ }+}++/** Blue's `Server-Timing: blue;dur=12.3`, in whole ms; undefined when absent. */+export function blueMs(response: Response): number | undefined {+ const header = response.headers.get("server-timing");+ const match = header ? /(?:^|,)\s*blue;dur=([0-9.]+)/.exec(header) : null;+ if (!match) return undefined;+ const ms = Math.round(Number(match[1]));+ return Number.isFinite(ms) && ms >= 0 ? ms : undefined;+}++/** A Tinybird `DateTime64` string. */+function tbTime(ms: number): string {+ return new Date(ms).toISOString().replace("T", " ").replace("Z", "");+}++/** UUIDv7: a 48-bit ms timestamp, then random bits. */+function uuidv7(now: number): string {+ const b = new Uint8Array(16);+ crypto.getRandomValues(b);+ let t = now;+ for (let i = 5; i >= 0; i--) {+ b[i] = t % 256;+ t = Math.floor(t / 256);+ }+ b[6] = (b[6] & 0x0f) | 0x70;+ b[8] = (b[8] & 0x3f) | 0x80;+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;+}++/** The `edge.request` line for `calvin_events` (`data` as a JSON string, as blue writes it). */+export function edgeRequestEvent(+ env: EdgeTelemetryEnv,+ req: Request,+ suffix: string,+ status: number,+ facts: EdgeRequestFacts,+ response: Response | null,+ now = Date.now(),+): Record<string, unknown> {+ const method = req.method.toUpperCase();+ const ua = req.headers.get("user-agent") ?? "";+ const session = SESSION.exec(suffix)?.[1];+ const colo = (req as { cf?: { colo?: unknown } }).cf?.colo;+ const blue = facts.upstream === "blue" && response ? blueMs(response) : undefined;+ const data: Record<string, unknown> = {+ route: computerApiRouteFamily(suffix),+ method: METHODS.has(method) ? method : "other",+ status,+ upstream: facts.upstream,+ auth: facts.auth,+ via: facts.via,+ rate_limited: facts.rateLimited,+ ...(blue !== undefined ? { blue_ms: blue } : {}),+ ...(facts.keyId && ID.test(facts.keyId) ? { key_id: facts.keyId } : {}),+ };+ return {+ schema_version: 1,+ event_id: uuidv7(now),+ event_name: "edge.request",+ occurred_at: tbTime(now),+ service_name: "edge",+ service_version: env.CF_VERSION_METADATA?.id || "dev",+ region: typeof colo === "string" && /^[A-Z]{3}$/.test(colo) ? colo : "unknown",+ synthetic: false,+ surface: ua.startsWith("opc/") ? "cli" : "api",+ ...(session ? { session_key: session } : {}),+ ...(facts.orgId && ID.test(facts.orgId) ? { org_id: facts.orgId } : {}),+ duration_ms: Math.max(0, Math.round(now - facts.started)),+ outcome: status < 400 ? "completed" : "failed",+ ...(status >= 400 ? { error_type: "unknown", error_code: String(status) } : {}),+ data: JSON.stringify(data),+ };+}++/**+ * Sends one request's `edge.request` off the response path. Never throws;+ * a failed POST is retried once on 5xx, 429 or a timeout, then dropped.+ */+export function reportEdgeRequest(+ env: EdgeTelemetryEnv,+ ctx: { waitUntil(p: Promise<unknown>): void } | undefined,+ req: Request,+ suffix: string,+ facts: EdgeRequestFacts,+ response: Response | null,+): void {+ try {+ if (!ctx || !edgeTelemetryEnabled(env)) return;+ const line = JSON.stringify(+ edgeRequestEvent(env, req, suffix, response?.status ?? 500, facts, response),+ );+ ctx.waitUntil(post(env, line).catch(() => {}));+ } catch {+ // Telemetry never fails the request.+ }+}++async function post(env: EdgeTelemetryEnv, line: string): Promise<void> {+ const url = `${env.TINYBIRD_API_URL!.trim().replace(/\/+$/, "")}/v0/events?name=calvin_events&wait=false`;+ for (let attempt = 1; attempt <= 2; attempt++) {+ try {+ const res = await fetch(url, {+ method: "POST",+ headers: {+ authorization: `Bearer ${env.TINYBIRD_APPEND_TOKEN!.trim()}`,+ "content-type": "application/x-ndjson",+ },+ body: line,+ signal: AbortSignal.timeout(POST_TIMEOUT_MS),+ });+ await res.body?.cancel().catch(() => {});+ if (res.ok || (res.status < 500 && res.status !== 429)) return;+ } catch {+ // Retried once.+ }+ }+}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 64678a73..e581e0d4 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -110,10 +110,16 @@ import {withComputerApiCors,COMPUTER_API_PREFIX,} from "./computer_api";+import {+ type EdgeRequestFacts,+ type EdgeTelemetryEnv,+ newEdgeRequestFacts,+ reportEdgeRequest,+} from "./computer_telemetry";import { computerEnabledFor } from "./computer";import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";-export interface Env extends DashboardEnv, AgentFeedbackEnv {+export interface Env extends DashboardEnv, AgentFeedbackEnv, EdgeTelemetryEnv {CF_ADMIN_SECRET: string;STRIPE_WEBHOOK_SECRET: string;EVENT_SECRET: string;@@ -4711,15 +4717,35 @@ async function handleComputerApi(ctx: ExecutionContext,path: string,): Promise<Response> {- const method = req.method.toUpperCase();- if (method === "OPTIONS") return computerApiPreflight(req, env);+ if (req.method.toUpperCase() === "OPTIONS") return computerApiPreflight(req, env);+ // One `edge.request` per call (work 084 instrumentation), sent off the+ // response path; the duration ends when the response's headers are ready.const suffix = path.slice("/api/managed-agents".length);+ const facts = newEdgeRequestFacts();+ let response: Response | null = null;+ try {+ response = await computerApiCall(req, env, ctx, suffix, facts);+ return response;+ } finally {+ reportEdgeRequest(env, ctx, req, suffix, facts, response);+ }+}++async function computerApiCall(+ req: Request,+ env: Env,+ ctx: ExecutionContext,+ suffix: string,+ facts: EdgeRequestFacts,+): Promise<Response> {+ const method = req.method.toUpperCase();if (!isComputerApiRoute(method, suffix)) {return computerApiError(req, 404, "not_found", "No such route.");}const credential = computerApiKey(req);if ("conflict" in credential) {+ facts.auth = "conflicting";return computerApiError(req,401,@@ -4731,6 +4757,7 @@ async function handleComputerApi(let viaKey = false;if (credential.key) {viaKey = true;+ facts.via = "key";caller = await authenticateKey(credential.key, env, ctx);// Entries cached before the key fields existed: re-read the row once, so// blue always learns which key acted.@@ -4741,6 +4768,7 @@ async function handleComputerApi(// The only non-user credential is the act-as-org provisioning token, a// project-scoped credential: the computer API is a person's.if (caller?.scope) {+ facts.auth = "project_key";return computerApiError(req, 403, "forbidden", "This credential cannot use the computer API.", {reason: "project_key",});@@ -4753,6 +4781,8 @@ async function handleComputerApi(() => true,);if (!allowed) {+ facts.auth = "ok";+ facts.rateLimited = true;const response = computerApiError(req, 429, "rate_limited", "Too many requests for this key. Slow down.", {retryAfterMs: COMPUTER_API_RATE_LIMIT_RETRY_SEC * 1000,});@@ -4763,9 +4793,11 @@ async function handleComputerApi(} else {const session = await authDashboard(req, env);if (session) {+ facts.via = "dashboard";// A cookie rides along on cross-site requests SameSite=Lax still// allows (sibling subdomains); unsafe methods need an allowed Origin.if (!SAFE_METHODS.has(method) && !computerApiOriginAllowed(req, env)) {+ facts.auth = "origin";return computerApiError(req, 403, "forbidden", "Cross-origin request refused.", {reason: "origin_not_allowed",});@@ -4776,6 +4808,7 @@ async function handleComputerApi(.bind(session.orgID, session.userID).first<{ role: string }>();if (!membership) {+ facts.auth = "not_member";return computerApiError(req, 401, "unauthenticated", "Sign in again.");}caller = {@@ -4789,9 +4822,13 @@ async function handleComputerApi(}}if (!caller) {+ facts.auth = credential.key ? "invalid" : "missing";return computerApiError(req, 401, "unauthenticated", "Missing or invalid API key.");}+ facts.orgId = caller.orgID;+ if (caller.key?.id) facts.keyId = caller.key.id;if (!computerEnabledFor(env, caller.orgID)) {+ facts.auth = "disabled";return computerApiError(req, 404, "not_found", "No such route.");}@@ -4799,6 +4836,7 @@ async function handleComputerApi(if (workspace) {// The wire Worker checks the caller's key itself; a cookie is not one.if (!viaKey) {+ facts.auth = "key_required";return computerApiError(req,403,@@ -4807,8 +4845,12 @@ async function handleComputerApi({ reason: "key_required" },);}+ facts.auth = "ok";+ facts.upstream = "wire";return proxyComputerWorkspace(req, env, workspace);}+ facts.auth = "ok";+ facts.upstream = "blue";return proxyManagedAgents(req, env, caller, "/api/managed-agents");}diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 4f7824ff..ed60612b 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -20,6 +20,12 @@ routes = [{ pattern = "*.sb.opencomputer.dev/*", zone_name = "opencomputer.dev" },]+# The deployed version on computer-API telemetry (work 084). The optional+# TINYBIRD_API_URL and TINYBIRD_APPEND_TOKEN secrets switch it on; unset, the+# edge sends nothing.+[version_metadata]+binding = "CF_VERSION_METADATA"+# Workers Logs: without this, exceptions behind a Cloudflare 1101 Ray ID are# only visible to a live `wrangler tail`.[observability]diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex fd318d84..75bafbd2 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -39,6 +39,12 @@ routes = [{ pattern = "app2.opensandbox.ai", zone_name = "opensandbox.ai", custom_domain = true },]+# The deployed version on computer-API telemetry (work 084). The optional+# TINYBIRD_API_URL and TINYBIRD_APPEND_TOKEN secrets switch it on; unset, the+# edge sends nothing.+[version_metadata]+binding = "CF_VERSION_METADATA"+# Static assets — the dashboard SPA. Built from `web/` by the deploy script# (web/dist/ → cloudflare-workers/api-edge/assets/). The Worker handles# explicit API/auth/webhook paths; anything else falls through to the SPA's