An open-source, faster Devin alternative
TypeScript
feat: manage project service connections
Mohamed Habibe69f1a7bb17e
diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsindex 9c63d2d1..795e2ef7 100644--- a/cli/src/api.test.ts+++ b/cli/src/api.test.ts@@ -3,6 +3,92 @@ import test from "node:test";import { APIError, OpenComputerClient } from "./api.js";+test("project service connections use project-scoped attachment routes", async (context) => {+ const requests: Request[] = [];+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ requests.push(request);+ if (request.method === "GET") return Response.json({ attachments: [] });+ if (request.method === "DELETE") return new Response(null, { status: 204 });+ return Response.json({+ projectId: "prj_1",+ provider: "linear",+ label: "default",+ connectionId: "conn_1",+ connection: { id: "conn_1", provider: "linear", label: "default", status: "connected" },+ createdAt: "2026-10-07T00:00:00.000Z",+ updatedAt: "2026-10-07T00:00:00.000Z",+ });+ },+ );+ const client = new OpenComputerClient({+ apiUrl: "https://app.opencomputer.dev",+ apiKey: "test",+ });++ await client.projectServiceConnections("prj_1");+ await client.attachProjectServiceConnection({+ projectId: "prj_1",+ connectionId: "conn_1",+ });+ await client.detachProjectServiceConnection({+ projectId: "prj_1",+ connectionId: "conn_1",+ });++ assert.deepEqual(+ requests.map((request) => [request.method, new URL(request.url).pathname]),+ [+ ["GET", "/api/managed-agents/projects/prj_1/service-connections"],+ ["POST", "/api/managed-agents/projects/prj_1/service-connections"],+ ["DELETE", "/api/managed-agents/projects/prj_1/service-connections"],+ ],+ );+ assert.deepEqual(await requests[1]!.json(), { connectionId: "conn_1" });+ assert.deepEqual(await requests[2]!.json(), { connectionId: "conn_1" });+});++test("reconnect asks the backend to preserve and reauthorize the logical connection", async (context) => {+ let request: Request | undefined;+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request, init?: RequestInit) => {+ request = new Request(input, init);+ return Response.json({+ service: "linear",+ label: "engineering",+ status: "pending",+ connectionId: "conn_1",+ authorizationUrl: "https://connect.example/linear",+ });+ },+ );+ const client = new OpenComputerClient({+ apiUrl: "https://app.opencomputer.dev",+ apiKey: "test",+ });++ await client.linkServiceConnection({+ service: "linear",+ label: "engineering",+ reconnect: true,+ });++ assert.equal(+ new URL(request!.url).pathname,+ "/api/managed-agents/connections/linear/link",+ );+ assert.deepEqual(await request!.json(), {+ service: "linear",+ label: "engineering",+ reconnect: true,+ });+});+// Review reproduction (U6): the header names the operation the caller's key// stands for, not the request it was sent with. The body is the backend's// to compare; hashing it here turned a retry with different inputs into adiff --git a/cli/src/api.ts b/cli/src/api.tsindex 3bb506e2..20caaf9f 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -121,6 +121,16 @@ export interface ServiceConnection {status: string;}+export interface ProjectServiceAttachment {+ projectId: string;+ provider: string;+ label: string;+ connectionId: string;+ connection: ServiceConnection;+ createdAt: string;+ updatedAt: string;+}+export interface ModelAccessConnection {id: string;organizationId: string;@@ -823,7 +833,11 @@ export class OpenComputerClient {* no credential passes through the CLI, and the person consenting never* signs in to OpenComputer.*/- linkServiceConnection(input: { service: string; label?: string }) {+ linkServiceConnection(input: {+ service: string;+ label?: string;+ reconnect?: boolean;+ }) {const provider =input.service === "github" || input.service === "linear"? input.service@@ -840,10 +854,48 @@ export class OpenComputerClient {body: JSON.stringify({service: input.service,...(input.label ? { label: input.label } : {}),+ ...(input.reconnect ? { reconnect: true } : {}),}),});}+ async projectServiceConnections(+ projectId: string,+ ): Promise<ProjectServiceAttachment[]> {+ const result = await this.request<{+ attachments: ProjectServiceAttachment[];+ }>(+ `/api/managed-agents/projects/${encodeURIComponent(projectId)}/service-connections`,+ );+ return result.attachments ?? [];+ }++ attachProjectServiceConnection(input: {+ projectId: string;+ connectionId: string;+ }) {+ return this.request<ProjectServiceAttachment>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/service-connections`,+ {+ method: "POST",+ body: JSON.stringify({ connectionId: input.connectionId }),+ },+ );+ }++ detachProjectServiceConnection(input: {+ projectId: string;+ connectionId: string;+ }) {+ return this.request<void>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/service-connections`,+ {+ method: "DELETE",+ body: JSON.stringify({ connectionId: input.connectionId }),+ },+ );+ }+/*** Live status for one connected account.*diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 39bb3787..44fa1f0a 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -1617,6 +1617,7 @@ export async function runCommand(scopes?: string[];}): string {if (connection.provider === "github") return "github";+ if (connection.provider === "linear") return "linear";const scopes = (connection.scopes ?? []).join(" ");if (scopes.includes("/auth/calendar")) return "calendar";if (scopes.includes("/auth/spreadsheets")) return "sheets";@@ -1759,6 +1760,34 @@ export async function runCommand(// open, and the token is minted and refreshed server-side.const action = args.shift();+ const findConnection = async (target: string, service?: string) => {+ const connections = await client.serviceConnections();+ let matches = connections.filter(+ (connection) => connection.label === target || connection.id === target,+ );+ if (service) {+ matches = matches.filter(+ (connection) => serviceOfConnection(connection) === service,+ );+ }+ if (!matches.length) {+ throw new Error(+ `No connection named ${JSON.stringify(target)}${service ? ` for ${service}` : ""}. ` ++ `Run \`opencomputer connection list\` to see them.`,+ );+ }+ if (matches.length > 1) {+ const services = [...new Set(matches.map(serviceOfConnection))];+ throw new Error(+ `${matches.length} connections use the alias ${JSON.stringify(target)}` ++ (services.length > 1+ ? ` — add --service <${services.join("|")}> to choose one.`+ : `. Use the connection id instead; \`opencomputer connection list\` shows them.`),+ );+ }+ return matches[0]!;+ };+if (action === "add" || action === "connect") {const service = args.shift();if (service === "github") {@@ -1839,6 +1868,34 @@ export async function runCommand(}if (action === "list" || action === "ls" || action === undefined) {+ const projectReference = option(args, "--project");+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ if (projectReference) {+ const project = await selectedProject(+ client,+ config,+ projectReference === "current" ? undefined : projectReference,+ );+ const attachments = await client.projectServiceConnections(+ project.projectId,+ );+ if (globals.json) {+ printJSON(attachments);+ return;+ }+ if (!attachments.length) {+ process.stdout.write("No service connections are attached to this project.\n");+ return;+ }+ for (const attachment of attachments) {+ process.stdout.write(+ `${attachment.label.padEnd(18)} ${attachment.provider.padEnd(7)} ` ++ `${attachment.connection.status.padEnd(10)} ` ++ `${(attachment.connection.displayName ?? "").padEnd(26)} ${attachment.connectionId}\n`,+ );+ }+ return;+ }const listed = await client.serviceConnections();// The listing route does not re-check with the provider, so an account// authorized minutes ago can still read `pending`. The status route does@@ -1881,43 +1938,133 @@ export async function runCommand(return;}- if (action === "remove" || action === "disconnect") {+ if (action === "status") {const target = args.shift();if (!target) {throw new Error(- "Use `opencomputer connection remove <alias|connection-id>`",+ "Use `opencomputer connection status <alias|connection-id>`",);}const service = option(args, "--service");if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);- const connections = await client.serviceConnections();- // Accept either the alias a person remembers or the id the API returns.- let matches = connections.filter(- (connection) => connection.label === target || connection.id === target,- );- if (service) {- matches = matches.filter(- (connection) => serviceOfConnection(connection) === service,+ const connection = await findConnection(target, service);+ const resolved = service ?? serviceOfConnection(connection);+ const status = await client.serviceConnectionStatus({+ service: resolved,+ label: connection.label,+ });+ if (globals.json) printJSON({ ...connection, ...status });+ else+ process.stdout.write(+ `${connection.label} (${resolved}): ${status.status}\n`,+ );+ return;+ }++ if (action === "reconnect") {+ const target = args.shift();+ if (!target) {+ throw new Error(+ "Use `opencomputer connection reconnect <alias|connection-id>`",);}- if (!matches.length) {+ const service = option(args, "--service");+ const noWait = flag(args, "--no-wait");+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const connection = await findConnection(target, service);+ const resolved = service ?? serviceOfConnection(connection);+ const result = await client.linkServiceConnection({+ service: resolved,+ label: connection.label,+ reconnect: true,+ });+ if (globals.json) {+ printJSON(result);+ return;+ }+ process.stdout.write(+ `Reconnect ${resolved} as "${connection.label}" by opening:\n\n ${result.authorizationUrl}\n\n`,+ );+ if (noWait) return;+ const deadline = result.expiresAt+ ? Date.parse(result.expiresAt)+ : Date.now() + 5 * 60_000;+ process.stdout.write("Waiting for authorization… (Ctrl-C to stop)\n");+ while (Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 2_000));+ try {+ const status = await client.serviceConnectionStatus({+ service: resolved,+ label: connection.label,+ });+ if (status.status === "connected") {+ process.stdout.write(+ `Reconnected ${resolved} as "${connection.label}".\n`,+ );+ return;+ }+ } catch {+ // Keep waiting through transient reconciliation errors.+ }+ }+ process.stdout.write(+ "Still not authorized. Run `opencomputer connection status " ++ `${connection.label} --service ${resolved}\` to check.\n`,+ );+ return;+ }++ if (action === "attach" || action === "detach") {+ const target = args.shift();+ if (!target) {throw new Error(- `No connection named ${JSON.stringify(target)}${service ? ` for ${service}` : ""}. ` +- `Run \`opencomputer connection list\` to see them.`,+ `Use \`opencomputer connection ${action} <alias|connection-id>\``,);}- if (matches.length > 1) {- // Deleting the wrong account is not recoverable from here, so narrow- // it or refuse. The id in `connection list` is always unambiguous.- const services = [...new Set(matches.map(serviceOfConnection))];+ const service = option(args, "--service");+ const projectReference = option(args, "--project");+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const connection = await findConnection(target, service);+ const project = await selectedProject(+ client,+ config,+ projectReference === "current" ? undefined : projectReference,+ );+ if (action === "attach") {+ const attachment = await client.attachProjectServiceConnection({+ projectId: project.projectId,+ connectionId: connection.id,+ });+ if (globals.json) printJSON(attachment);+ else+ process.stdout.write(+ `Attached ${connection.label} (${serviceOfConnection(connection)}) to project ${project.projectId}.\n`,+ );+ } else {+ await client.detachProjectServiceConnection({+ projectId: project.projectId,+ connectionId: connection.id,+ });+ if (globals.json)+ printJSON({ detached: connection.id, projectId: project.projectId });+ else+ process.stdout.write(+ `Detached ${connection.label} (${serviceOfConnection(connection)}) from project ${project.projectId}.\n`,+ );+ }+ return;+ }++ if (action === "remove" || action === "disconnect") {+ const target = args.shift();+ if (!target) {throw new Error(- `${matches.length} connections use the alias ${JSON.stringify(target)}` +- (services.length > 1- ? ` — add --service <${services.join("|")}> to choose one.`- : `. Remove it by connection id instead; \`opencomputer connection list\` shows them.`),+ "Use `opencomputer connection remove <alias|connection-id>`",);}- const connection = matches[0]!;+ const service = option(args, "--service");+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const connection = await findConnection(target, service);const resolved = service ?? serviceOfConnection(connection);await client.disconnectServiceConnection({service: resolved,@@ -1929,7 +2076,9 @@ export async function runCommand(return;}- throw new Error("Use `opencomputer connection add|list|remove`.");+ throw new Error(+ "Use `opencomputer connection connect|reconnect|list|status|attach|detach|remove`.",+ );}if (command === "model-access") {diff --git a/cli/src/index.ts b/cli/src/index.tsindex 3de6c1a4..ef8360cd 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -84,8 +84,12 @@ Usage:opencomputer env set <name> --value-stdin [--environment development|production] [--agent <agent>|current]opencomputer env list [--environment development|production] [--agent <agent>|current]opencomputer env remove <name> [--environment development|production] [--agent <agent>|current]- opencomputer connection add <gmail|calendar|drive|sheets|linear> [--alias <name>] [--no-wait]- opencomputer connection list+ opencomputer connection connect <gmail|calendar|drive|sheets|linear> [--alias <name>] [--no-wait]+ opencomputer connection reconnect <alias|connection-id> [--service <name>] [--no-wait]+ opencomputer connection list [--project <id|slug|current>]+ opencomputer connection status <alias|connection-id> [--service <name>]+ opencomputer connection attach <alias|connection-id> [--service <name>] [--project <id|slug|current>]+ opencomputer connection detach <alias|connection-id> [--service <name>] [--project <id|slug|current>]opencomputer connection remove <alias|connection-id> [--service <name>]opencomputer github status [--project <id|slug>]opencomputer github connect [--new | --connection <id|account>] [--environment development|production] [--project <id|slug>] [--no-wait]diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 4e6103cb..fd79143d 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -1406,6 +1406,45 @@ describe("managed agents proxy", () => {expect(JSON.stringify(body)).not.toContain("private-account");});+ it("proxies project service attachment management", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ Response.json({+ projectId: "prj_test",+ provider: "linear",+ label: "default",+ connectionId: "conn_1",+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_test/service-connections",+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ connectionId: "conn_1" }),+ },+ ),+ {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ },+ { orgID: "org_test", userID: "user_test" },+ "/api/managed-agents",+ );++ expect(response.status).toBe(200);+ const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];+ expect(target.toString()).toBe(+ "https://managedagents.test/v1/projects/prj_test/service-connections",+ );+ expect(init.method).toBe("POST");+ await expect(new Response(init.body).json()).resolves.toEqual({+ connectionId: "conn_1",+ });+ });+it("proxies bounded project database queries without exposing backend fields", async () => {const fetchSpy = vi.fn(async (_input: RequestInfo | URL) =>Response.json({diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 7bbd00ad..f915204a 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -660,6 +660,21 @@ function publicConnection(value: unknown): Record<string, unknown> {};}+function publicProjectServiceAttachment(+ value: unknown,+): Record<string, unknown> {+ const attachment = record(value) ?? {};+ return {+ projectId: attachment.projectId,+ provider: attachment.provider,+ label: attachment.label,+ connectionId: attachment.connectionId,+ connection: publicConnection(attachment.connection),+ createdAt: attachment.createdAt,+ updatedAt: attachment.updatedAt,+ };+}+function publicModelAccessConnection(value: unknown,includeAdminMetadata: boolean,@@ -1844,6 +1859,22 @@ function publicSuccessBody() {return stripPrivateValues(body);}+ if (+ method === "GET" &&+ /^\/projects\/[^/]+\/service-connections$/.test(suffix)+ ) {+ return {+ attachments: Array.isArray(body.attachments)+ ? body.attachments.map(publicProjectServiceAttachment)+ : [],+ };+ }+ if (+ method === "POST" &&+ /^\/projects\/[^/]+\/service-connections$/.test(suffix)+ ) {+ return publicProjectServiceAttachment(body);+ }if (method === "GET" && /^\/projects\/[^/]+\/webhooks$/.test(suffix)) {return {webhooks: Array.isArray(body.webhooks)@@ -2670,6 +2701,12 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {) {return true;}+ if (+ (method === "GET" || method === "POST" || method === "DELETE") &&+ /^\/projects\/[^/]+\/service-connections$/.test(suffix)+ ) {+ return true;+ }if ((method === "GET" || method === "PUT" || method === "DELETE") &&/^\/projects\/[^/]+\/model-routes(?:\/[^/]+)?$/.test(suffix)diff --git a/docs/agents/services.mdx b/docs/agents/services.mdxindex 15eb1201..8d12c5b5 100644--- a/docs/agents/services.mdx+++ b/docs/agents/services.mdx@@ -59,6 +59,14 @@ otherwise the call returns `409 connection_alias_required` and lists them.The provider segment in the URL is the grant, not the service — `google` forgmail, calendar, drive and sheets; `github` for GitHub; and `linear` for Linear.+`connection add` remains an alias for `connection connect`. If consent was+revoked or the connected account must change, start a fresh OAuth flow without+changing the logical connection or its project attachments:++```bash+opencomputer connection reconnect support --service gmail+```+**Listing what is connected:**<CodeGroup>@@ -74,6 +82,37 @@ curl "$OC_API_URL/api/managed-agents/connections" \```</CodeGroup>+## 2. Attach the account to a project++By default a connected account is personal: calls resolve it from the person+who started the session. That is useful in the playground, but channel sessions+such as Slack have a channel principal rather than the project owner's user+identity.++Attach a connected account when it should be the project's shared service+credential:++```bash+opencomputer connection attach default --service linear --project current+opencomputer connection list --project current+```++The attachment applies to the whole project, including all of its agents and+environments. An agent can use it only when its deployed code declares the+service with `useService()`. The session principal is still retained as the+actor for session ownership and audit; it no longer chooses the credential.++Detach removes only the project grant. It does not disconnect the underlying+OAuth account:++```bash+opencomputer connection detach default --service linear --project current+```++Removing the connection itself also removes its project attachments. Preview+inheritance follows the project's attachment; a preview does not create a+second OAuth connection.+<Note>A connection that is not yet `connected` is re-checked with the provider eachtime it is listed, so `pending` means what it says. A **`connected`** account@@ -101,7 +140,7 @@ curl -X DELETE \Every CLI command takes `--json` if you want to parse its output.-## 2. Declare the service+## 3. Declare the service```tsximport { useService, useTool } from "@opencomputer/agent";@@ -139,7 +178,7 @@ to run `git` and `gh` itself — that one injects a token into the sandbox rathethan proxying requests.</Note>-## 3. Call it from a tool+## 4. Call it from a tool`useService` goes in the agent; `callService` goes in a tool. An agent renderssynchronously and cannot wait for a request.@@ -217,9 +256,11 @@ other paths and methods fail at the broker.### Linear in sessions started from Linear-Which credential a call uses follows who owns the session. In a session-someone started, `service: "linear"` uses a Linear account connected as-above. In a session started from a [Linear agent connection](/agents/linear),+Which credential a call uses follows an explicit order. A session started from+a [Linear agent connection](/agents/linear) always uses that connection's own+Linear app. Otherwise, a project-attached Linear account wins; when the project+has no Linear attachment, OpenComputer falls back to an eligible account owned+by the session principal. In a session started from a Linear agent connection,the session belongs to the connection, and `service: "linear"` resolves tothat connection's own Linear app: the call acts as the agent, under the namepeople delegate to, with the app's token attached by the platform.@@ -231,7 +272,7 @@ people delegate to, with the app's token attached by the platform.The agent's code is the same in both kinds of session.-## 4. Several accounts+## 5. Several accountsAccounts are connected and disconnected long after the artifact is built, soask for them rather than naming them in source.@@ -307,8 +348,9 @@ collections rather than asking for them in one call.| `409 connection_alias_required` | Several accounts connected, no `label` given | Pass `label`; the message lists them || `403` from the service | The consent is narrower than the call needs | Reconnect the account with wider access || `listServices()` returns `[]` | The service is not declared | Add `useService("gmail")` |-| A connection stays `pending` | Nobody opened the link, or it expired | Send the link again with `connection add` |-| A `connected` account returns `401` | Access was revoked at the provider; the stored status has not caught up | Reconnect it — `connection add` with the same label |+| A connection stays `pending` | Nobody opened the link, or it expired | Run `connection reconnect` and send the new link |+| It works in the playground but not Slack | The account is personal, so the Slack principal cannot resolve it | Attach it with `connection attach <alias> --service <name> --project current` |+| A `connected` account returns `401` | Access was revoked at the provider; the stored status has not caught up | Run `connection reconnect` with the same label || A header you set is ignored | It is not in the allowlist above | Nothing — it cannot be sent || Throws *managed connections are unavailable* | No connection layer | You are running outside the platform |