An open-source, faster Devin alternative
TypeScript
Edge: curate the setup record's error message, close the setups prefix, pin the callback mount
Igor Zalutski392f814ef88b
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.tsindex 4e7be684..4c5956e1 100644--- a/cloudflare-workers/api-edge/src/index.test.ts+++ b/cloudflare-workers/api-edge/src/index.test.ts@@ -477,3 +477,43 @@ describe("/internal/warm-org — auth boundary", () => {expect((await post()).status).not.toBe(401);});});++describe("/api/managed-agents/slack/callback — unauthenticated mount", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ // Slack calls this URL with no OpenComputer credentials; it is registered on+ // every app the automated setup creates, so the mount must stay above the+ // API-key check and forward the query untouched.+ it("forwards Slack's redirect to the backend callback without an API key", async () => {+ const fetchSpy = vi.fn(+ async (_target: URL | RequestInfo, _init?: RequestInit) =>+ new Response(null, {+ status: 302,+ headers: {+ location:+ "https://app.opencomputer.dev/projects/prj_test/connections?environment=development&slack=connected&setup=setup_1",+ },+ }),+ );+ vi.stubGlobal("fetch", fetchSpy);++ const resp = await worker.fetch(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/slack/callback?state=x&code=y",+ ),+ { ...env, MANAGED_AGENTS_API_URL: "https://managedagents.test" },+ ctx,+ );++ expect(resp.status).toBe(302);+ expect(resp.headers.get("location")).toBe(+ "https://app.opencomputer.dev/projects/prj_test/connections?environment=development&slack=connected&setup=setup_1",+ );+ expect(fetchSpy).toHaveBeenCalledTimes(1);+ expect(fetchSpy.mock.calls[0][0].toString()).toBe(+ "https://managedagents.test/v1/channels/slack/oauth/callback?state=x&code=y",+ );+ });+});diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 1327f95c..6c3ad9f7 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -1543,7 +1543,8 @@ describe("managed agents proxy", () => {app: { id: "A0APP", name: "Patch" },error: {code: "slack_authorization_denied",- message: "The installation was declined.",+ message:+ "The Slack installation was declined. Authorize the app again when you are ready.",recoverable: true,at: "2026-09-17T10:05:00.000Z",},@@ -1551,6 +1552,40 @@ describe("managed agents proxy", () => {createdAt: "2026-09-17T10:00:00.000Z",updatedAt: "2026-09-17T10:05:00.000Z",};+ const SETUP_ERROR_CODES = [+ "slack_setup_conflict",+ "slack_setup_active",+ "slack_already_connected",+ "slack_setup_unavailable",+ "slack_setup_not_found",+ "slack_configuration_token_invalid",+ "slack_configuration_token_expired",+ "slack_manifest_rejected",+ "slack_app_limit_reached",+ "slack_rate_limited",+ "slack_provider_unavailable",+ "slack_creation_uncertain",+ "slack_exchange_uncertain",+ "slack_authorization_denied",+ "slack_authorization_expired",+ "slack_app_mismatch",+ "slack_workspace_mismatch",+ "slack_scope_missing",+ "slack_enterprise_install_unsupported",+ "slack_setup_superseded",+ "slack_exchange_failed",+ "slack_setup_not_authorizable",+ "slack_setup_connected",+ ];+ const GENERIC_MESSAGES = [+ "The agent request could not be completed.",+ "The agent request was invalid.",+ "The agent request was not authorized.",+ "The requested agent resource was not found.",+ "The agent request conflicts with the current state.",+ "Too many agent requests. Try again shortly.",+ "The agent service is temporarily unavailable.",+ ];it("starts a setup and returns only the redacted record", async () => {const fetchSpy = vi@@ -1589,11 +1624,61 @@ describe("managed agents proxy", () => {);});+ it("replaces the record's error message with the curated one for its code", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ setup: {+ ...backendSetup,+ phase: "prepared",+ actions: ["create", "cancel"],+ error: {+ code: "slack_configuration_token_expired",+ message: "backend text with xoxe-private",+ recoverable: true,+ retryAfterMs: 1500,+ pointer: "/oauth_config",+ at: "2026-09-17T10:05:00.000Z",+ },+ },+ }),+ ),+ );++ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1",+ ),+ env,+ caller,+ "/api/managed-agents",+ );++ const body = (await response.json()) as {+ setup: { error: Record<string, unknown> };+ };+ expect(body.setup.error).toEqual({+ code: "slack_configuration_token_expired",+ message:+ "The configuration access token has expired. Generate a new one at api.slack.com/apps and try again.",+ recoverable: true,+ retryAfterMs: 1500,+ pointer: "/oauth_config",+ at: "2026-09-17T10:05:00.000Z",+ });+ expect(JSON.stringify(body)).not.toContain("xoxe");+ expect(JSON.stringify(body)).not.toContain("backend text");+ });+it("rediscovers a setup by target and passes the query through", async () => {- const fetchSpy = vi.fn().mockResolvedValue(Response.json({ setup: null }));+ const fetchSpy = vi+ .fn()+ .mockResolvedValueOnce(Response.json({ setup: backendSetup }))+ .mockResolvedValueOnce(Response.json({ setup: null }));vi.stubGlobal("fetch", fetchSpy);- const response = await proxyManagedAgents(+ const found = await proxyManagedAgents(new Request("https://app.opencomputer.dev/api/managed-agents/channels/slack/setups?agentId=coder&alias=development&channelId=slack",),@@ -1601,11 +1686,49 @@ describe("managed agents proxy", () => {caller,"/api/managed-agents",);+ const none = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/channels/slack/setups?agentId=other&alias=development",+ ),+ env,+ caller,+ "/api/managed-agents",+ );- expect(await response.json()).toEqual({ setup: null });+ expect(await found.json()).toEqual({ setup: publicSetup });+ expect(await none.json()).toEqual({ setup: null });expect(fetchSpy.mock.calls[0]?.[0].toString()).toBe("https://managedagents.test/v1/channels/slack/setups?agentId=coder&alias=development&channelId=slack",);+ expect(fetchSpy.mock.calls[1]?.[0].toString()).toBe(+ "https://managedagents.test/v1/channels/slack/setups?agentId=other&alias=development",+ );+ });++ it("answers 404 for setup routes outside the contract without contacting the backend", async () => {+ const fetchSpy = vi.fn(async () => Response.json({ setup: backendSetup }));+ vi.stubGlobal("fetch", fetchSpy);++ for (const [method, path] of [+ ["GET", "/channels/slack/setups/setup_1/authorize"],+ ["POST", "/channels/slack/setups/setup_1"],+ ["GET", "/channels/slack/setups/"],+ ["DELETE", "/channels/slack/setups/setup_1"],+ ["PUT", "/channels/slack/setups/setup_1/cancel"],+ ["GET", "/channels/slack/setups/setup_1/cancel/extra"],+ ]) {+ const response = await proxyManagedAgents(+ new Request(`https://app.opencomputer.dev/api/managed-agents${path}`, {+ method,+ }),+ env,+ caller,+ "/api/managed-agents",+ );+ expect(response.status, `${method} ${path}`).toBe(404);+ expect(await response.text()).not.toContain("webhookTokenHash");+ }+ expect(fetchSpy).not.toHaveBeenCalled();});it("reads and cancels a setup through the same whitelist", async () => {@@ -1732,6 +1855,85 @@ describe("managed agents proxy", () => {}});+ it("passes the active setup's id through on slack_setup_active", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json(+ {+ error: {+ code: "slack_setup_active",+ message: "backend text",+ setupId: "setup_9",+ attemptId: "private",+ },+ setup: backendSetup,+ },+ { status: 409 },+ ),+ ),+ );++ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/channels/slack/setups",+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: "{}",+ },+ ),+ env,+ caller,+ "/api/managed-agents",+ );++ expect(response.status).toBe(409);+ expect(await response.json()).toEqual({+ error: {+ code: "slack_setup_active",+ message:+ "A Slack setup is already in progress for this agent and environment. Resume it instead of starting another.",+ setupId: "setup_9",+ },+ });+ });++ it("never lets a documented setup error fall to a generic message", async () => {+ for (const code of SETUP_ERROR_CODES) {+ for (const status of [400, 404, 409, 429, 503]) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json(+ { error: { code, message: "backend text with xoxe-private" } },+ { status },+ ),+ ),+ );+ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/channels/slack/setups/setup_1/cancel",+ { method: "POST" },+ ),+ env,+ caller,+ "/api/managed-agents",+ );+ const body = (await response.json()) as {+ error: { code: string; message: string };+ };+ expect(response.status, code).toBe(status);+ expect(body.error.code, code).toBe(code);+ expect(GENERIC_MESSAGES, `${code} @ ${status}`).not.toContain(+ body.error.message,+ );+ expect(body.error.message).not.toContain("backend");+ expect(body.error.message).not.toContain("xoxe");+ }+ }+ });+it("lists the agents consuming each channel", async () => {vi.stubGlobal("fetch",@@ -1819,6 +2021,7 @@ describe("managed agents proxy", () => {headers: {"content-type": "text/html; charset=utf-8","x-frame-options": "DENY",+ location: "https://app.opencomputer.dev/projects/prj_test",},}),),diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 6b08efdf..382c8432 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -151,6 +151,12 @@ const SLACK_SETUP_ERROR_MESSAGES: Record<string, string> = {"Slack may have created the app, but the result was lost. Check your Slack app list before creating another.",slack_exchange_uncertain:"The installation could not be confirmed. Authorize the app again.",+ slack_exchange_failed:+ "Slack did not confirm the installation. Authorize the app again.",+ slack_setup_not_authorizable:+ "This setup cannot be authorized in its current state. Reload to see its next step.",+ slack_setup_connected:+ "This setup is already connected and cannot be cancelled. Disconnect the Slack connection instead.",slack_authorization_denied:"The Slack installation was declined. Authorize the app again when you are ready.",slack_authorization_expired:@@ -250,8 +256,16 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {const headers = new Headers({ "content-type": "application/json" });const retryAfter = upstream.headers.get("retry-after");if (retryAfter) headers.set("retry-after", retryAfter);+ // The one extra field an error may carry: the id of the setup already in+ // progress for the target, so the caller can resume it.+ const setupId =+ backendCode === "slack_setup_active" &&+ typeof backendError?.setupId === "string" &&+ /^[A-Za-z0-9_-]{1,128}$/.test(backendError.setupId)+ ? { setupId: backendError.setupId }+ : {};return new Response(- JSON.stringify({ error: { code: publicCode, message } }),+ JSON.stringify({ error: { code: publicCode, message, ...setupId } }),{ status: upstream.status, headers },);}@@ -599,6 +613,17 @@ const SLACK_SETUP_CANCEL_ROUTE = /^\/channels\/slack\/setups\/[^/]+\/cancel$/;* row also carries the generated app credentials, the manifest snapshot and* the webhook identity, none of which the dashboard needs to resume.*/+function isSlackSetupRoute(method: string, suffix: string): boolean {+ return (+ ((method === "GET" || method === "POST") &&+ SLACK_SETUPS_ROUTE.test(suffix)) ||+ (method === "GET" && SLACK_SETUP_ROUTE.test(suffix)) ||+ (method === "POST" &&+ (SLACK_SETUP_AUTHORIZE_ROUTE.test(suffix) ||+ SLACK_SETUP_CANCEL_ROUTE.test(suffix)))+ );+}+function publicSlackSetup(value: unknown): Record<string, unknown> {const setup = record(value) ?? {};const app = record(setup.app);@@ -625,7 +650,11 @@ function publicSlackSetup(value: unknown): Record<string, unknown> {? {error: {code: error.code,- message: error.message,+ message:+ typeof error.code === "string" &&+ Object.hasOwn(SLACK_SETUP_ERROR_MESSAGES, error.code)+ ? SLACK_SETUP_ERROR_MESSAGES[error.code]+ : "The last Slack setup step did not complete.",recoverable: error.recoverable === true,...(typeof error.retryAfterMs === "number"? { retryAfterMs: error.retryAfterMs }@@ -1626,6 +1655,11 @@ function publicSuccessBody(expiresAt: body.expiresAt,};}+ if (suffix.startsWith("/channels/slack/setups")) {+ // Every setup response is shaped explicitly above; nothing under this+ // prefix may fall through to the generic key filter.+ throw new Error("Unsupported managed agents response");+ }if ((method === "GET" && suffix.startsWith("/connections")) ||(method === "POST" && suffix.startsWith("/connections")) ||@@ -2006,6 +2040,11 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {if (method === "GET" && suffix === "/schedule-runs") return true;if (method === "POST" && /^\/schedules\/[^/]+\/run$/.test(suffix))return true;+ // Automated Slack setup: only the contract's routes, before the /channels+ // catch-all below can admit anything else under the prefix.+ if (suffix.startsWith("/channels/slack/setups")) {+ return isSlackSetupRoute(method, suffix);+ }if ((method === "GET" &&(/^\/connections(?:\/.*)?$/.test(suffix) ||diff --git a/docs/agents/api.mdx b/docs/agents/api.mdxindex 6bd592fc..f6547c77 100644--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@ -466,13 +466,15 @@ routes; call them from your own tooling to script the same flow.| Operation | Method and path | Body or query | Success || --- | --- | --- | --- || Start or continue | `POST /channels/slack/setups` | `{ agentId, alias, channelId?, name, requestKey, configurationToken? }` | `201` with `{ setup }` when created; `200` when the key names an existing setup |-| Find by target | `GET /channels/slack/setups` | `?agentId=&alias=&channelId=` | `200` with `{ setup }`, `null` when nothing is in progress |+| Find by target | `GET /channels/slack/setups` | `?agentId=&alias=&channelId=` | `200` with `{ setup }`: the latest setup for the target that was not cancelled, a connected one included, or `null` || Get | `GET /channels/slack/setups/<id>` | None | `200` with `{ setup }` || Authorize | `POST /channels/slack/setups/<id>/authorize` | None | `200` with `{ authorizationUrl, expiresAt }` || Cancel | `POST /channels/slack/setups/<id>/cancel` | None | `200` with `{ setup }` in phase `cancelled` |`alias` is `development` or `production`. `channelId` names a channel declared-in code; omit it for an agent whose deployment declares none. `requestKey` is+in code; omit it for an agent whose deployment declares none, and the setup+then reports `channelId: "slack"`. `name` is the bot's display name, 1 to 35+characters. `requestKey` is16 to 128 characters of letters, digits, `_` and `-` chosen by the caller: thesame key with the same target and name returns the same setup, so a retriedrequest never creates a second app, and a reused key with a different target@@ -538,16 +540,19 @@ Error codes, as HTTP errors or as `error.code` on the setup:| Code | Meaning || --- | --- || `slack_setup_conflict` | The request key was already used with a different target or name |-| `slack_setup_active` | Another setup is in progress for the target; find it by target and continue it |+| `slack_setup_active` | Another setup is in progress for the target; `error.setupId` names it, and finding it by target returns the same record || `slack_already_connected` | The target already has a connected app; disconnect it first || `slack_setup_unavailable` | Automatic setup is not available; use manual setup |+| `slack_setup_not_found` | `404`: no setup with that id in this project |+| `slack_setup_not_authorizable` | `409` on authorize: the setup's phase does not allow it; read the setup for its next step |+| `slack_setup_connected` | `409` on cancel: the setup is connected; disconnect the connection instead || `slack_configuration_token_invalid`, `slack_configuration_token_expired` | The token was rejected; generate a new one and submit it with the same key || `slack_manifest_rejected` | Slack rejected the generated app configuration; `pointer` names the field || `slack_app_limit_reached` | The workspace cannot hold another app || `slack_rate_limited` | Wait `retryAfterMs` and submit again |-| `slack_provider_unavailable` | Slack did not answer; submit or authorize again |+| `slack_provider_unavailable` | Slack declined with an unexpected error when creating the app, or did not answer during installation; submit or authorize again || `slack_creation_uncertain` | See phase `creation_uncertain` |-| `slack_exchange_uncertain`, `slack_authorization_denied`, `slack_authorization_expired` | The installation did not complete; authorize again |+| `slack_exchange_failed`, `slack_exchange_uncertain`, `slack_authorization_denied`, `slack_authorization_expired` | The installation did not complete; authorize again || `slack_app_mismatch`, `slack_workspace_mismatch`, `slack_scope_missing`, `slack_enterprise_install_unsupported` | The installation did not match the created app, its established workspace or its declared scopes; authorize again and approve that app in a single workspace || `slack_setup_superseded` | A manual connection or reconnect completed first |@@ -555,8 +560,8 @@ The authorization URL opens Slack's consent page for the created app and isvalid for ten minutes; authorizing again issues a new one. Slack sends theoutcome to `https://app.opencomputer.dev/api/managed-agents/slack/callback`,which is registered on every app created this way, and the browser is then-redirected to the project's Connections tab with `slack=<result>` and-`setup=<id>` in the query. `result` is `connected` or one of+redirected to the project's Connections tab with `environment=<alias>`,+`slack=<result>` and `setup=<id>` in the query. `result` is `connected` or one of`authorization_denied`, `authorization_expired`, `exchange_failed`,`app_mismatch`, `workspace_mismatch`, `scope_missing`,`enterprise_install_unsupported`, `superseded` and `provider_unavailable`.diff --git a/docs/agents/channels.mdx b/docs/agents/channels.mdxindex 1a26920b..3f82b9ff 100644--- a/docs/agents/channels.mdx+++ b/docs/agents/channels.mdx@@ -143,10 +143,10 @@ OpenComputer asks the user which agent should handle it instead of guessing.## Connect Slack-Each environment gets its own dedicated Slack app. OpenComputer creates it-from the capabilities declared in code and installs it into your workspace;-you approve the installation in Slack. Nothing about the app is copied by-hand.+Each declared channel gets its own Slack app per environment, and so does an+agent whose deployment declares none. OpenComputer creates the app from the+capabilities declared in code and installs it into your workspace; you paste+one short-lived token and approve the installation in Slack.After the deployment is synchronized:diff --git a/docs/agents/github.mdx b/docs/agents/github.mdxindex 420c8490..96879ecb 100644--- a/docs/agents/github.mdx+++ b/docs/agents/github.mdx@@ -55,8 +55,8 @@ Effective authority is therefore the intersection of:Deploy the agent, open its project in the OpenComputer dashboard, select theenvironment and open **Connections**. Install the managed OpenComputer GitHub-App into a user or organization account. GitHub lets the installer select all repositories or a-specific set of repositories.+App into a user or organization account. GitHub lets the installer select all+repositories or a specific set of repositories.That GitHub installation selection is the complete repository boundary. Thereis no second OpenComputer repository allowlist. If the installer selects alldiff --git a/web/src/managed-agents/slack-setup.test.ts b/web/src/managed-agents/slack-setup.test.tsindex 5abcaf7c..04a72c1a 100644--- a/web/src/managed-agents/slack-setup.test.ts+++ b/web/src/managed-agents/slack-setup.test.ts@@ -285,6 +285,24 @@ describe('setup copy', () => {).toMatchObject({primary: { action: 'authorize', label: 'Authorize in Slack' },})+ expect(+ describeSlackSetup(+ setup({+ phase: 'app_created',+ app: { id: 'A1', name: 'Patch' },+ actions: ['authorize', 'cancel'],+ error: {+ code: 'slack_exchange_failed',+ message: 'exchange failed',+ recoverable: true,+ at: '2026-09-17T00:00:00.000Z',+ },+ }),+ ),+ ).toMatchObject({+ title: 'Slack did not confirm the installation',+ primary: { action: 'authorize', label: 'Authorize again' },+ })expect(describeSlackSetup(setup({diff --git a/web/src/managed-agents/slack-setup.ts b/web/src/managed-agents/slack-setup.tsindex 86497419..1f6aceff 100644--- a/web/src/managed-agents/slack-setup.ts+++ b/web/src/managed-agents/slack-setup.ts@@ -280,6 +280,14 @@ export function describeSlackSetup(tone: 'error',primary: authorize,}+ case 'slack_exchange_failed':+ return {+ title: 'Slack did not confirm the installation',+ description:+ 'The installation could not be completed with Slack. Authorize again; the app is kept.',+ tone: 'error',+ primary: authorize,+ }case 'slack_exchange_uncertain':case 'slack_provider_unavailable':return {