Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: allow the computer agent routes (work 081)

Igor Zalutski via Computerb713fdf66a08
diff --git a/cloudflare-workers/api-edge/src/computer.ts b/cloudflare-workers/api-edge/src/computer.ts
index ed4d4752..f324b919 100644
--- a/cloudflare-workers/api-edge/src/computer.ts
+++ b/cloudflare-workers/api-edge/src/computer.ts
@@ -19,7 +19,18 @@ export function isComputerRoute(method: string, suffix: string): boolean {
}
if (method === "GET" && suffix === "/computer/sessions") return true;
if (method === "POST" && suffix === "/computer/slack/install") return true;
- return method === "DELETE" && suffix === "/computer/slack";
+ 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";
}
// The backend's codes are stable; the messages are written here so no
@@ -39,6 +50,18 @@ export const COMPUTER_ERROR_MESSAGES: Record<string, string> = {
"No Slack workspace is linked to this organization.",
computer_slack_already_linked:
"That Slack workspace is already linked to another organization.",
+ // Choose your agent (work 081).
+ computer_agent_token_format:
+ "That's not a setup token. It starts with sk-ant-oat01-.",
+ computer_agent_token_rejected:
+ "That token didn't work. Run claude setup-token again and paste the new one.",
+ computer_agent_rate_limited: "Too many tries. Wait a few minutes.",
+ computer_agent_already_connected:
+ "Someone else already connected a subscription for this organization.",
+ computer_agent_connect_in_slack: "Connect from Slack: !claude connect",
+ computer_agent_disabled: "Your workspace admin turned this off.",
+ computer_agent_not_member:
+ "You're not a member of this organization's Slack workspace.",
};
/** Fallback copy for a computer route when the backend's code is unknown. */
@@ -82,9 +105,95 @@ function publicComputer(value: unknown): Record<string, unknown> | null {
};
}
+const AGENT_CHOICES = new Set(["claude", "codex", "credits"]);
+const SUBSCRIPTION_HEALTH = new Set([
+ "ok",
+ "unchecked",
+ "paused",
+ "limited",
+ "invalid",
+]);
+
+function publicSlackUser(value: unknown): Record<string, string> | null {
+ const user = record(value);
+ if (
+ !user ||
+ typeof user.id !== "string" ||
+ typeof user.name !== "string" ||
+ typeof user.teamName !== "string"
+ ) {
+ return null;
+ }
+ return { id: user.id, name: user.name, teamName: user.teamName };
+}
+
+// `undefined` when the value breaks the contract; `null` is a real "none".
+function publicSubscription(
+ value: unknown,
+): Record<string, unknown> | null | undefined {
+ if (value === null) return null;
+ const subscription = record(value);
+ if (
+ !subscription ||
+ subscription.provider !== "claude" ||
+ typeof subscription.health !== "string" ||
+ !SUBSCRIPTION_HEALTH.has(subscription.health) ||
+ typeof subscription.setAt !== "string"
+ ) {
+ return undefined;
+ }
+ return {
+ provider: "claude",
+ health: subscription.health,
+ ...(typeof subscription.limitedUntil === "string"
+ ? { limitedUntil: subscription.limitedUntil }
+ : {}),
+ setAt: subscription.setAt,
+ };
+}
+
+/**
+ * The person's agent block (work 081), rebuilt field by field. Null when the
+ * backend sends none or one that breaks the contract: the dashboard then
+ * skips the agent step rather than guessing.
+ */
+export function publicComputerAgent(
+ value: unknown,
+): Record<string, unknown> | null {
+ const agent = record(value);
+ if (!agent) return null;
+ const choice = agent.choice ?? null;
+ if (
+ choice !== null &&
+ !(typeof choice === "string" && AGENT_CHOICES.has(choice))
+ ) {
+ return null;
+ }
+ const subscription = publicSubscription(agent.subscription ?? null);
+ if (subscription === undefined) return null;
+ if (typeof agent.managedModel !== "string" || !agent.managedModel) {
+ return null;
+ }
+ const linkedSlackUser = publicSlackUser(agent.linkedSlackUser);
+ return {
+ choice,
+ linked: agent.linked === true,
+ ...(linkedSlackUser ? { linkedSlackUser } : {}),
+ subscription,
+ managedModel: agent.managedModel,
+ };
+}
+
+function requiredAgent(value: unknown): Record<string, unknown> {
+ const agent = publicComputerAgent(value);
+ if (!agent) throw new Error("Invalid computer agent");
+ return agent;
+}
+
function publicComputerStatus(body: Record<string, unknown>) {
const slack = record(body.slack) ?? {};
const github = record(body.github) ?? {};
+ const agent = publicComputerAgent(body.agent);
return {
computer: publicComputer(body.computer),
slack: {
@@ -113,6 +222,7 @@ function publicComputerStatus(body: Record<string, unknown>) {
: [],
},
plan: body.plan === "paid" ? "paid" : "free",
+ ...(agent ? { agent } : {}),
};
}
@@ -165,6 +275,23 @@ export function publicComputerBody(
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");
}
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 3a1aa5ea..88529d3b 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -6681,6 +6681,201 @@ describe("organization computer (work 052)", () => {
expect(fetchMock).not.toHaveBeenCalled();
});
+ // Choose your agent (work 081).
+ const agent = {
+ choice: null,
+ linked: true,
+ linkedSlackUser: { id: "U1", name: "igor", teamName: "Acme" },
+ subscription: {
+ provider: "claude",
+ health: "limited",
+ limitedUntil: "2026-10-22T15:00:00.000Z",
+ setAt: "2026-10-22T10:00:00.000Z",
+ },
+ managedModel: "Claude Opus 5.5",
+ };
+
+ it("passes the agent block of GET /computer field by field", async () => {
+ const { response } = await call(
+ "GET",
+ "/computer",
+ Response.json({
+ ...computerStatus,
+ agent: {
+ ...agent,
+ owner: "web:user_test",
+ linkedSlackUser: { ...agent.linkedSlackUser, email: "[email protected]" },
+ subscription: {
+ ...agent.subscription,
+ fingerprint: "fp_private",
+ usage5hPct: 42,
+ },
+ },
+ }),
+ );
+ await expect(response.json()).resolves.toEqual({ ...computerStatus, agent });
+ });
+
+ it("keeps the minimal agent block and omits absent optionals", async () => {
+ const minimal = {
+ choice: "credits",
+ linked: false,
+ subscription: null,
+ managedModel: "Claude Opus 5.5",
+ };
+ const { response } = await call(
+ "GET",
+ "/computer",
+ Response.json({ ...computerStatus, agent: minimal }),
+ );
+ await expect(response.json()).resolves.toEqual({
+ ...computerStatus,
+ agent: minimal,
+ });
+ });
+
+ it.each([
+ ["an unknown choice", { ...agent, choice: "gemini" }],
+ ["an unknown health", { ...agent, subscription: { ...agent.subscription, health: "great" } }],
+ ["an unknown provider", { ...agent, subscription: { ...agent.subscription, provider: "openai" } }],
+ ["no managed model", { ...agent, managedModel: undefined }],
+ ["a non-object", "claude"],
+ ])("drops an agent block with %s", async (_name, value) => {
+ const { response } = await call(
+ "GET",
+ "/computer",
+ Response.json({ ...computerStatus, agent: value }),
+ );
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual(computerStatus);
+ });
+
+ it("forwards a connect with its body and returns the contract", async () => {
+ const token = `sk-ant-oat01-${"a".repeat(40)}`;
+ const logs = [
+ vi.spyOn(console, "log").mockImplementation(() => {}),
+ vi.spyOn(console, "info").mockImplementation(() => {}),
+ vi.spyOn(console, "warn").mockImplementation(() => {}),
+ vi.spyOn(console, "error").mockImplementation(() => {}),
+ ];
+ let forwarded = "";
+ const fetchMock = vi.fn(async (_target: URL, init: RequestInit) => {
+ forwarded = await new Response(init.body).text();
+ return Response.json({
+ agent: { ...agent, choice: "claude" },
+ verified: false,
+ via: "none",
+ sealed: "private",
+ });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ try {
+ const response = await proxyManagedAgents(
+ new Request(
+ `https://app.opencomputer.dev${dashboard}/computer/agent/claude`,
+ {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ token }),
+ },
+ ),
+ env,
+ caller,
+ dashboard,
+ );
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ agent: { ...agent, choice: "claude" },
+ verified: false,
+ via: "none",
+ });
+ expect(JSON.parse(forwarded)).toEqual({ token });
+ const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
+ expect(target.toString()).toBe(
+ "https://managedagents.test/v1/computer/agent/claude",
+ );
+ expect(init.method).toBe("PUT");
+ for (const spy of logs) {
+ expect(JSON.stringify(spy.mock.calls)).not.toContain(token);
+ }
+ } finally {
+ for (const spy of logs) spy.mockRestore();
+ }
+ });
+
+ it("refuses a connect response with an unknown via", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const { response } = await call(
+ "PUT",
+ "/computer/agent/claude",
+ Response.json({ agent, verified: true, via: "somewhere" }),
+ );
+ error.mockRestore();
+ expect(response.status).toBe(502);
+ });
+
+ it.each([
+ ["POST", "/computer/agent/claude/resume"],
+ ["PUT", "/computer/agent/choice"],
+ ])("returns the agent from %s %s", async (method, path) => {
+ const { response, fetchMock } = await call(
+ method,
+ path,
+ Response.json({ agent: { ...agent, extra: true }, other: 1 }),
+ );
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ agent });
+ const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
+ expect(target.toString()).toBe(`https://managedagents.test/v1${path}`);
+ expect(init.method).toBe(method);
+ });
+
+ it("answers a disconnect with no content", async () => {
+ const { response, fetchMock } = await call(
+ "DELETE",
+ "/computer/agent/claude",
+ new Response(null, { status: 204 }),
+ );
+ expect(response.status).toBe(204);
+ expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
+ "https://managedagents.test/v1/computer/agent/claude",
+ );
+ });
+
+ it.each([
+ ["GET", "/computer/agent/claude"],
+ ["POST", "/computer/agent/claude"],
+ ["GET", "/computer/agent/choice"],
+ ["DELETE", "/computer/agent/choice"],
+ ["PUT", "/computer/agent/codex"],
+ ["GET", "/computer/agent/claude/resume"],
+ ])("refuses agent route %s %s outside the contract", async (method, path) => {
+ const { response, fetchMock } = await call(method, path, Response.json({}));
+ expect(response.status).toBe(404);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [422, "computer_agent_token_format", "That's not a setup token. It starts with sk-ant-oat01-."],
+ [422, "computer_agent_token_rejected", "That token didn't work. Run claude setup-token again and paste the new one."],
+ [429, "computer_agent_rate_limited", "Too many tries. Wait a few minutes."],
+ [409, "computer_agent_already_connected", "Someone else already connected a subscription for this organization."],
+ [409, "computer_agent_connect_in_slack", "Connect from Slack: !claude connect"],
+ [403, "computer_agent_disabled", "Your workspace admin turned this off."],
+ [403, "computer_agent_not_member", "You're not a member of this organization's Slack workspace."],
+ ])("maps %s %s to fixed copy", async (status, code, message) => {
+ const { response } = await call(
+ "PUT",
+ "/computer/agent/claude",
+ Response.json(
+ { error: { code, message: "upstream detail sk-ant-oat01-private" } },
+ { status },
+ ),
+ );
+ expect(response.status).toBe(status);
+ await expect(response.json()).resolves.toEqual({ error: { code, message } });
+ });
+
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.ts
index df97200f..4f6a897c 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -3791,7 +3791,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 has no response body in the contract.
+ // Unlinking Slack and disconnecting the agent have no response body.
if (method === "DELETE") {
return new Response(null, {
status: 204,