Skip to content

An open-source, faster Devin alternative

TypeScript

Add hosted Slack channels to managed agents (#569)

Mohamed Habibbcf495108b6e
diff --git a/cli/package-lock.json b/cli/package-lock.json
index 3f42eca1..2b89444e 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/cli",
- "version": "0.3.8",
+ "version": "0.3.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/cli",
- "version": "0.3.8",
+ "version": "0.3.9",
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"@opentui/core": "^0.4.5",
diff --git a/cli/package.json b/cli/package.json
index 83cbfe0a..4228225e 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/cli",
- "version": "0.3.8",
+ "version": "0.3.9",
"description": "Build, test, connect, deploy, and share OpenComputer agents as code.",
"type": "module",
"bin": {
diff --git a/cli/src/api.test.ts b/cli/src/api.test.ts
new file mode 100644
index 00000000..6efae045
--- /dev/null
+++ b/cli/src/api.test.ts
@@ -0,0 +1,43 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { OpenComputerClient } from "./api.js";
+
+test("reads channels from the public managed-agents response", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async () =>
+ Response.json({
+ channels: [
+ {
+ id: "channel-1",
+ channel: "slack",
+ agentId: "agent-1",
+ alias: "production",
+ teamName: "OpenComputer",
+ status: "connected",
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ },
+ ],
+ });
+
+ try {
+ const client = new OpenComputerClient({
+ apiUrl: "https://app.opencomputer.dev",
+ apiKey: "osb_test",
+ });
+ assert.deepEqual(await client.channelConnections(), [
+ {
+ id: "channel-1",
+ channel: "slack",
+ agentId: "agent-1",
+ alias: "production",
+ teamName: "OpenComputer",
+ status: "connected",
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ },
+ ]);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
diff --git a/cli/src/api.ts b/cli/src/api.ts
index b64154ed..1feaf09a 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -291,9 +291,10 @@ export class OpenComputerClient {
async channelConnections(): Promise<ManagedSlackConnection[]> {
const result = await this.request<{
- connections: ManagedSlackConnection[];
+ channels?: ManagedSlackConnection[];
+ connections?: ManagedSlackConnection[];
}>("/api/managed-agents/channels");
- return result.connections;
+ return result.channels ?? result.connections ?? [];
}
completeSlackConnection(connectionId: string, botToken: string) {
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index 733d2ea2..796b61f8 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -723,6 +723,11 @@ export async function runCommand(
if (command === "channels") {
const action = args.shift();
+ if (action === "add" || action === "connect") {
+ throw new Error(
+ "Connect Slack from the deployed agent's Channels tab in the OpenComputer dashboard.",
+ );
+ }
if (action === "list") {
const localOnly = flag(args, "--local");
const remoteOnly = flag(args, "--remote");
@@ -888,7 +893,9 @@ export async function runCommand(
if (command === "slack-hook") {
const action = args.shift();
- if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ // Slack CLI app hooks append metadata such as --source=<directory>.
+ // The hook already resolves its repository from the working directory,
+ // so these Slack-owned arguments are intentionally ignored.
const root = await requireSlackAgentRoot();
const mode =
process.env.OPENCOMPUTER_SLACK_MODE === "remote" ? "remote" : "local";
diff --git a/cli/src/index.ts b/cli/src/index.ts
index d057b26c..dee3e89a 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -2,7 +2,7 @@
import { runCommand, type GlobalOptions } from "./commands.js";
-const VERSION = "0.3.8";
+const VERSION = "0.3.9";
const BANNER = String.raw` ____ ______ __
/ __ \____ ___ ____ / ____/___ ____ ___ ____ __ / /____ _____
@@ -54,8 +54,6 @@ Usage:
opencomputer connection add gmail [--alias <name>]
opencomputer connection list
opencomputer connection remove <alias|connection-id>
- opencomputer channels add slack
- opencomputer channels connect slack [--local|--remote]
opencomputer channels list [--local|--remote]
opencomputer channels disconnect slack [connection-id] [--local|--remote]
opencomputer deploy [--alias <alias>]
diff --git a/cli/src/project.test.ts b/cli/src/project.test.ts
index a2d2f3ee..e440bab1 100644
--- a/cli/src/project.test.ts
+++ b/cli/src/project.test.ts
@@ -11,6 +11,7 @@ import {
import { tmpdir } from "node:os";
import { resolve } from "node:path";
import test from "node:test";
+import ts from "typescript";
import type { ManagedAgentTemplate } from "./api.js";
import {
@@ -88,26 +89,48 @@ test("the compiler maps flat source into an OpenCode runtime", async () => {
try {
await initializeAgentProject(emailTemplate, root);
const runtime = await prepareAgent(root);
- assert.match(
- await readFile(resolve(runtime, "AGENTS.md"), "utf8"),
- /Email triage/,
+ const runtimeInstructions = await readFile(
+ resolve(runtime, "AGENTS.md"),
+ "utf8",
);
+ assert.match(runtimeInstructions, /You are an OpenComputer agent/);
+ assert.match(runtimeInstructions, /Never direct users to OpenCode/);
+ assert.match(runtimeInstructions, /Email triage/);
assert.equal(
(await stat(resolve(runtime, ".opencode", "tools", "gmail.ts"))).isFile(),
true,
);
- assert.equal(
- (await stat(resolve(runtime, "opencode.json"))).isFile(),
- true,
+ const connectionTool = await readFile(
+ resolve(runtime, ".opencode", "tools", "opencomputer-connections.ts"),
+ "utf8",
);
+ assert.match(connectionTool, /export const request = tool/);
+ assert.match(connectionTool, /opencomputer\/fetch/);
+ assert.match(connectionTool, /newAccount/);
assert.match(
- await readFile(resolve(runtime, "AGENTS.md"), "utf8"),
- /start with the `gmail_search` tool/,
+ connectionTool,
+ /schema\.enum\(\["gmail", "calendar", "drive", "sheets"\]\)/,
);
- assert.match(
- await readFile(resolve(runtime, "AGENTS.md"), "utf8"),
- /summary count exactly matches/,
+ assert.equal(connectionTool.includes('base.replace(/\\\/$/, "")'), true);
+ const transpiledConnectionTool = ts.transpileModule(connectionTool, {
+ compilerOptions: { module: ts.ModuleKind.ESNext },
+ reportDiagnostics: true,
+ });
+ assert.equal(
+ transpiledConnectionTool.diagnostics?.length ?? 0,
+ 0,
+ transpiledConnectionTool.diagnostics
+ ?.map((diagnostic) =>
+ ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
+ )
+ .join("\n"),
+ );
+ assert.equal(
+ (await stat(resolve(runtime, "opencode.json"))).isFile(),
+ true,
);
+ assert.match(runtimeInstructions, /start with the `gmail_search` tool/);
+ assert.match(runtimeInstructions, /summary count exactly matches/);
assert.equal(
(await stat(resolve(runtime, "README.md"))).isFile(),
true,
diff --git a/cli/src/project.ts b/cli/src/project.ts
index ab7a852f..3c600d04 100644
--- a/cli/src/project.ts
+++ b/cli/src/project.ts
@@ -386,6 +386,69 @@ export const send = tool({
`;
}
+function connectionControlToolSource(): string {
+ return `import { tool } from "@opencode-ai/plugin";
+
+async function connectionControl(
+ method: "GET" | "POST",
+ body?: unknown,
+): Promise<unknown> {
+ const base = process.env.OPENCOMPUTER_CONNECTIONS_URL;
+ const token = process.env.OPENCOMPUTER_CONNECTION_TOKEN;
+ if (!base || !token) {
+ throw new Error("OpenComputer connections are unavailable");
+ }
+ const response = await fetch(
+ \`\${base.replace(/\\\/$/, "")}/opencomputer/fetch\`,
+ {
+ method: "POST",
+ headers: {
+ authorization: \`Bearer \${token}\`,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ action: method === "GET" ? "list" : "request",
+ ...(body && typeof body === "object" ? body : {}),
+ }),
+ },
+ );
+ const result = await response.json() as {
+ error?: { message?: string };
+ message?: string;
+ [key: string]: unknown;
+ };
+ if (!response.ok) {
+ throw new Error(
+ result.error?.message ?? result.message ?? "Connection request failed",
+ );
+ }
+ return result;
+}
+
+export const list = tool({
+ description:
+ "List the connected accounts available to the current session identity. Use this to discover connection providers and aliases without exposing credentials.",
+ args: {},
+ async execute() {
+ return JSON.stringify(await connectionControl("GET"));
+ },
+});
+
+export const request = tool({
+ description:
+ "Ask the current user to connect an account. Use gmail for an email account. Set newAccount=true when the user asks for another account of the same service. In a messaging channel OpenComputer privately sends the authorization link to that user; otherwise the result includes the link.",
+ args: {
+ service: tool.schema.enum(["gmail", "calendar", "drive", "sheets"]),
+ label: tool.schema.string().optional(),
+ newAccount: tool.schema.boolean().optional(),
+ },
+ async execute(args) {
+ return JSON.stringify(await connectionControl("POST", args));
+ },
+});
+`;
+}
+
export async function writeManifest(
root: string,
manifest: AgentManifest,
@@ -722,7 +785,26 @@ export async function prepareAgent(root: string): Promise<string> {
await mkdir(runtime, { recursive: true });
await writeFile(
resolve(runtime, "AGENTS.md"),
- await readFile(resolve(root, "instructions.md"), "utf8"),
+ `# OpenComputer runtime identity
+
+You are an OpenComputer agent. OpenCode is an internal execution detail, not
+the product or support surface presented to users.
+
+- Identify yourself and your environment as OpenComputer.
+- Never direct users to OpenCode commands, settings, websites, repositories,
+ issue trackers, or support channels.
+- Before saying an external account is unavailable, use the built-in
+ OpenComputer connection tools to list or request the required connection.
+- When the user asks for another account of the same service, request a new
+ account instead of returning the existing default connection.
+- If a connection request reports private-message delivery, tell the user to
+ check their private messages. If it returns an authorization URL, show it.
+- If a connection tool fails, report its exact error. Do not invent alternate
+ controls or third-party support instructions.
+
+# Agent instructions
+
+${await readFile(resolve(root, "instructions.md"), "utf8")}`,
);
const openCodeConfig = resolve(root, "opencode.json");
if (await exists(openCodeConfig)) {
@@ -737,6 +819,11 @@ export async function prepareAgent(root: string): Promise<string> {
});
}
}
+ await mkdir(resolve(runtime, ".opencode", "tools"), { recursive: true });
+ await writeFile(
+ resolve(runtime, ".opencode", "tools", "opencomputer-connections.ts"),
+ connectionControlToolSource(),
+ );
const workspace = resolve(root, "workspace");
if (await exists(workspace)) {
await cp(workspace, runtime, { recursive: true });
diff --git a/cli/src/slack.test.ts b/cli/src/slack.test.ts
index 39b2d289..28f8b98b 100644
--- a/cli/src/slack.test.ts
+++ b/cli/src/slack.test.ts
@@ -5,6 +5,7 @@ import { resolve } from "node:path";
import test from "node:test";
import type { ManagedAgentTemplate } from "./api.js";
+import { runCommand } from "./commands.js";
import {
addSlackChannel,
initializeAgentProject,
@@ -68,3 +69,24 @@ test("Slack channel state renders local and remote manifests", async () => {
await rm(parent, { recursive: true, force: true });
}
});
+
+test("Slack hooks accept source metadata from the Slack CLI", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-slack-hook-"));
+ const root = resolve(parent, "research-agent");
+ const previousDirectory = process.cwd();
+ try {
+ await initializeAgentProject(template, root);
+ await addSlackChannel(root);
+ process.chdir(root);
+ await assert.doesNotReject(
+ runCommand(
+ "slack-hook",
+ ["manifest", `--source=${root}`],
+ { json: false },
+ ),
+ );
+ } finally {
+ process.chdir(previousDirectory);
+ await rm(parent, { recursive: true, force: true });
+ }
+});
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index cdbf1d28..d3847168 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -41,7 +41,10 @@ import * as snapshots from "./snapshots";
import * as templates from "./templates";
import * as webhooks from "./webhooks";
import { createAPIKey, hashAPIKey } from "./api_keys";
-import { proxyManagedAgents } from "./managed_agents";
+import {
+ handleManagedAgentChannelConnection,
+ proxyManagedAgents,
+} from "./managed_agents";
export interface Env extends DashboardEnv {
CF_ADMIN_SECRET: string;
@@ -2947,6 +2950,9 @@ export default {
// Managed Agents public API. Customers authenticate with their ordinary
// OpenComputer API key; the edge replaces it with a short-lived org
// assertion before calling the private deployment backend.
+ if (path.startsWith("/api/managed-agents/channel-connections/")) {
+ return handleManagedAgentChannelConnection(req, env);
+ }
if (
path === "/api/managed-agents" ||
path.startsWith("/api/managed-agents/")
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index ceba156b..0520aea1 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ handleManagedAgentChannelConnection,
mintManagedAgentsAssertion,
proxyManagedAgents,
} from "./managed_agents";
@@ -34,6 +35,88 @@ describe("managed agents proxy", () => {
expect(Number(payload.exp) - Number(payload.iat)).toBe(120);
});
+ it("does not consume a channel connection grant on link preview", async () => {
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await handleManagedAgentChannelConnection(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/channel-connections/org_test/0123456789abcdef0123456789abcdef",
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ expect(response.headers.get("content-security-policy")).not.toContain(
+ "form-action",
+ );
+ expect(await response.text()).toContain("Continue");
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("claims a channel grant and redirects to the provider", async () => {
+ const fetchSpy = vi.fn(async () =>
+ Response.json({
+ authorizationUrl: "https://connect.example.test/authorize",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+ const url =
+ "https://app.opencomputer.dev/api/managed-agents/channel-connections/org_test/0123456789abcdef0123456789abcdef";
+
+ const response = await handleManagedAgentChannelConnection(
+ new Request(url, { method: "POST" }),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ );
+
+ expect(response.status).toBe(303);
+ expect(response.headers.get("location")).toBe(
+ "https://connect.example.test/authorize",
+ );
+ const [target, init] = fetchSpy.mock.calls[0] as unknown as [
+ URL,
+ RequestInit,
+ ];
+ expect(target.toString()).toBe(
+ "https://managedagents.test/v1/channel-connections/claim",
+ );
+ expect(await new Response(init.body).json()).toEqual({
+ token: "0123456789abcdef0123456789abcdef",
+ });
+ expect(
+ decodePayload(
+ new Headers(init.headers).get("x-opencomputer-agent-token")!,
+ ),
+ ).toMatchObject({ org_id: "org_test" });
+ });
+
+ it("shows a completed state when the channel account is already connected", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => Response.json({ status: "connected" })),
+ );
+ const response = await handleManagedAgentChannelConnection(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/channel-connections/org_test/0123456789abcdef0123456789abcdef",
+ { method: "POST" },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.text()).toContain("already connected");
+ });
+
it("keeps API keys out of the private backend request", async () => {
const fetchSpy = vi.fn(async () => Response.json({ templates: [] }));
vi.stubGlobal("fetch", fetchSpy);
@@ -250,7 +333,9 @@ describe("managed agents proxy", () => {
const caller = { orgID: "org_test", userID: "user_test" };
const connections = await proxyManagedAgents(
- new Request("https://app.opencomputer.dev/api/managed-agents/connections"),
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/connections",
+ ),
env,
caller,
"/api/managed-agents",
@@ -294,6 +379,78 @@ describe("managed agents proxy", () => {
});
});
+ it("returns a public per-agent Slack manifest", async () => {
+ const fetchSpy = vi.fn().mockResolvedValue(
+ Response.json({
+ connection: {
+ id: "channel_slack",
+ agentId: "support-agent",
+ alias: "production",
+ status: "pending",
+ accountId: "private_org",
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ },
+ manifest: {
+ display_information: { name: "Support Helper" },
+ settings: {
+ event_subscriptions: {
+ request_url:
+ "https://managedagents.test/v1/webhooks/slack/id/token",
+ },
+ },
+ },
+ createUrl: "https://api.slack.com/apps",
+ steps: ["Create the app"],
+ runtimeToken: "private",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/channels/slack/connections",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ agentId: "support-agent@production",
+ name: "Support Helper",
+ }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(await response.json()).toEqual({
+ connection: {
+ id: "channel_slack",
+ channel: "slack",
+ agentId: "support-agent",
+ alias: "production",
+ status: "pending",
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ },
+ manifest: {
+ display_information: { name: "Support Helper" },
+ settings: {
+ event_subscriptions: {
+ request_url:
+ "https://managedagents.test/v1/webhooks/slack/id/token",
+ },
+ },
+ },
+ createUrl: "https://api.slack.com/apps",
+ steps: ["Create the app"],
+ });
+ });
+
it("does not expose arbitrary private backend routes", async () => {
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index 894858cb..31da31b9 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -170,6 +170,7 @@ function publicChannel(value: unknown): Record<string, unknown> {
channel: "slack",
agentId: channel.agentId,
alias: channel.alias,
+ appName: channel.appName,
teamName: channel.teamName,
status: channel.status,
createdAt: channel.createdAt,
@@ -266,6 +267,13 @@ function publicSuccessBody(
if (method === "POST" && suffix === "/benchmarks/warm-pool") {
return stripPrivateValues(body);
}
+ if (method === "POST" && suffix === "/channel-connections/claim") {
+ return {
+ authorizationUrl: body.authorizationUrl,
+ expiresAt: body.expiresAt,
+ status: body.status,
+ };
+ }
if (method === "GET" && suffix === "/deployments") {
return {
deployments: Array.isArray(body.deployments)
@@ -290,6 +298,20 @@ function publicSuccessBody(
: [],
};
}
+ if (method === "POST" && suffix === "/channels/slack/connections") {
+ return {
+ connection: publicChannel(body.connection),
+ manifest: stripPrivateValues(body.manifest),
+ createUrl: body.createUrl,
+ steps: strings(body.steps),
+ };
+ }
+ if (
+ (method === "PUT" || method === "DELETE") &&
+ /^\/channels\/slack\/connections\/[^/]+$/.test(suffix)
+ ) {
+ return publicChannel(body);
+ }
if (
(method === "GET" && suffix.startsWith("/connections")) ||
(method === "POST" && suffix.startsWith("/connections")) ||
@@ -491,6 +513,9 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
if (method === "GET" && suffix === "/me") return true;
if (method === "POST" && suffix === "/deployments") return true;
if (method === "POST" && suffix === "/benchmarks/warm-pool") return true;
+ if (method === "POST" && suffix === "/channel-connections/claim") {
+ return true;
+ }
if (method === "GET" && suffix === "/deployments") return true;
if (method === "GET" && /^\/deployments\/[^/]+$/.test(suffix)) return true;
if (
@@ -515,6 +540,129 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
);
}
+function channelConnectionPage(
+ action: string,
+ status: number,
+ error?: string,
+): Response {
+ const message = error
+ ? `<p role="alert">${error}</p>`
+ : `<p>Continue to securely connect an account to this agent in Slack.</p>
+ <form method="post" action="${action}">
+ <button type="submit">Continue</button>
+ </form>`;
+ return new Response(
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Connect account · OpenComputer</title><style>body{font:16px system-ui,sans-serif;max-width:34rem;margin:12vh auto;padding:2rem;color:#171717}h1{font-size:1.7rem}p{line-height:1.55;color:#555}button{font:inherit;background:#171717;color:#fff;border:0;border-radius:8px;padding:.8rem 1.2rem;cursor:pointer}</style></head><body><h1>Connect account</h1>${message}</body></html>`,
+ {
+ status,
+ headers: {
+ "content-type": "text/html; charset=utf-8",
+ "cache-control": "no-store",
+ "referrer-policy": "no-referrer",
+ "x-content-type-options": "nosniff",
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'",
+ },
+ },
+ );
+}
+
+export async function handleManagedAgentChannelConnection(
+ request: Request,
+ env: ManagedAgentsEnv,
+): Promise<Response> {
+ const url = new URL(request.url);
+ const match = url.pathname.match(
+ /^\/api\/managed-agents\/channel-connections\/([^/]+)\/([a-f0-9]{32})$/i,
+ );
+ if (!match) {
+ return channelConnectionPage(
+ url.pathname,
+ 404,
+ "This connection link is invalid.",
+ );
+ }
+ const accountId = decodeURIComponent(match[1]);
+ const token = match[2];
+ if (!/^[A-Za-z0-9._:-]{1,200}$/.test(accountId)) {
+ return channelConnectionPage(
+ url.pathname,
+ 404,
+ "This connection link is invalid.",
+ );
+ }
+ if (request.method === "GET" || request.method === "HEAD") {
+ const response = channelConnectionPage(url.pathname, 200);
+ return request.method === "HEAD"
+ ? new Response(null, {
+ status: response.status,
+ headers: response.headers,
+ })
+ : response;
+ }
+ if (request.method !== "POST") {
+ return channelConnectionPage(
+ url.pathname,
+ 405,
+ "This request is not supported.",
+ );
+ }
+ const internal = new Request(
+ new URL("/api/managed-agents/channel-connections/claim", url.origin),
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ token }),
+ },
+ );
+ const response = await proxyManagedAgents(
+ internal,
+ env,
+ { orgID: accountId, userID: null },
+ "/api/managed-agents",
+ );
+ if (!response.ok) {
+ return channelConnectionPage(
+ url.pathname,
+ response.status === 404 ? 404 : 502,
+ response.status === 404
+ ? "This connection link has expired or was already used. Ask the agent for a new one."
+ : "OpenComputer could not start the connection. Please try again.",
+ );
+ }
+ const body = record(await response.json().catch(() => null));
+ if (body?.status === "connected") {
+ return channelConnectionPage(
+ url.pathname,
+ 200,
+ "This account is already connected. You can return to Slack.",
+ );
+ }
+ let authorizationUrl: URL | null = null;
+ if (typeof body?.authorizationUrl === "string") {
+ try {
+ authorizationUrl = new URL(body.authorizationUrl);
+ } catch {
+ authorizationUrl = null;
+ }
+ }
+ if (!authorizationUrl || authorizationUrl.protocol !== "https:") {
+ return channelConnectionPage(
+ url.pathname,
+ 502,
+ "OpenComputer could not start the connection. Please try again.",
+ );
+ }
+ return new Response(null, {
+ status: 303,
+ headers: {
+ location: authorizationUrl.toString(),
+ "cache-control": "no-store",
+ "referrer-policy": "no-referrer",
+ "x-content-type-options": "nosniff",
+ },
+ });
+}
+
export async function proxyManagedAgents(
request: Request,
env: ManagedAgentsEnv,
diff --git a/docs/agents/architecture.mdx b/docs/agents/architecture.mdx
index 0167ea1c..1dbaba09 100644
--- a/docs/agents/architecture.mdx
+++ b/docs/agents/architecture.mdx
@@ -30,7 +30,7 @@ describe:
- behavior and approval rules in `instructions.md`
- runtime and model configuration
- tools and skills
-- required connections and channels
+- required connections
- initial workspace files and evaluations
The project contains declarations and code, not provider credentials.
@@ -82,7 +82,7 @@ Each session has:
- the exact deployed source version
- an isolated filesystem and process environment
- a workspace that the agent can use during the task
-- access to only the connections and channels declared for that agent
+- access to the connections allowed by that agent and channels attached to its deployment alias
- lifecycle management handled by OpenComputer
### Connections
@@ -151,13 +151,13 @@ stay outside Git and are never given directly to the model.
## Local and deployed execution
-| | Local session | Deployed session |
-|---|---|---|
-| Source | Current working directory | Immutable deployed artifact |
-| Runtime | OpenCode on your machine | OpenCode in an isolated OpenComputer sandbox |
-| Connections | Scoped through the local CLI | Scoped through the managed runtime |
-| Best for | Iteration and debugging | Durable, repeatable execution |
-| Command | `opencomputer session` | `opencomputer session create --remote` or `opencomputer run <agent>` |
+| | Local session | Deployed session |
+| ----------- | ---------------------------- | -------------------------------------------------------------------- |
+| Source | Current working directory | Immutable deployed artifact |
+| Runtime | OpenCode on your machine | OpenCode in an isolated OpenComputer sandbox |
+| Connections | Scoped through the local CLI | Scoped through the managed runtime |
+| Best for | Iteration and debugging | Durable, repeatable execution |
+| Command | `opencomputer session` | `opencomputer session create --remote` or `opencomputer run <agent>` |
This symmetry is intentional: develop the actual agent locally, then deploy
the same directory instead of rebuilding the workflow in a dashboard.
diff --git a/docs/agents/channels.mdx b/docs/agents/channels.mdx
index b67a3dc1..b441488f 100644
--- a/docs/agents/channels.mdx
+++ b/docs/agents/channels.mdx
@@ -1,52 +1,51 @@
---
title: "Channels"
-description: "Run deployed agents from Slack and other conversational interfaces"
+description: "Connect deployed agents to Slack and other conversational interfaces"
---
Channels make a deployed agent available from an external interface such as
Slack. The agent's behavior remains defined by its source repository; the
-channel supplies messages to sessions and returns the streamed result.
+channel supplies messages to managed sessions and returns the streamed result.
-## Channel declarations
+## Connect Slack
-Channel support is part of the agent repository. Adding Slack creates the
-channel declaration and Slack application manifest:
+Slack is connected after deployment and does not require channel source files,
+a Slack manifest in Git, or the Slack CLI.
-```bash
-opencomputer channels add slack
-```
-
-```text
-support-agent/
-├── channels/
-│ └── slack.ts
-└── slack/
- └── manifest.json
-```
-
-These files describe events and application behavior and are safe to commit.
-Slack installation credentials are managed separately from source code.
-
-Deploy the channel declaration before connecting the remote channel:
-
-```bash
-opencomputer deploy
-opencomputer channels connect slack --remote
-opencomputer channels list
-```
+<Steps>
+ <Step title="Deploy the agent">
+ Deploy the source with `opencomputer deploy`. A channel targets an alias,
+ such as `production`, so later deployments can advance that alias without
+ reinstalling the Slack app.
+ </Step>
+ <Step title="Open Channels">
+ In the OpenComputer dashboard, open the deployed agent and select the
+ **Channels** tab. Choose **Connect Slack**.
+ </Step>
+ <Step title="Name and create the Slack app">
+ Choose the app name people will see in Slack. Copy the generated manifest,
+ open Slack's app creation page, and create an app from that manifest.
+ </Step>
+ <Step title="Complete installation">
+ Follow the wizard to enter the App ID and Signing Secret, install the app,
+ and enter its Bot User OAuth Token. Secrets are stored encrypted and never
+ committed to the agent repository.
+ </Step>
+</Steps>
-The channel targets a deployed agent alias, so new deployments can advance
-that alias without reinstalling the Slack application.
+Each deployment alias has its own Slack app connection. For example,
+`support-agent@production` and `support-agent@staging` can be installed and
+tested independently.
## Sessions from channels
Each supported Slack conversation creates or resumes a managed agent session.
Messages in the same user thread continue the same multi-turn session, while
-other users and threads remain isolated.
+other users and threads remain isolated. Invite the app to a channel and
+@-mention it, or message it directly.
Channel sessions use the same deployed source and runtime behavior as sessions
-started from the CLI or dashboard. They appear in the agent's session history
-so you can inspect their status and activity.
+started from the CLI or dashboard. They appear in the agent's session history.
## Linking a channel identity
@@ -64,8 +63,9 @@ user links their own OpenComputer identity.
OpenComputer user.
</Step>
<Step title="Connect required services">
- If the agent requires Gmail or another service, OpenComputer shows the
- connection instructions for that user.
+ If the agent needs Gmail or another declared service, it can send that
+ Slack user a private connection link. Authorization never appears in the
+ shared channel.
</Step>
<Step title="Message the agent again">
The channel session can now use only the connections owned by the linked
@@ -76,34 +76,36 @@ user links their own OpenComputer identity.
This prevents a shared Slack channel from inheriting the installer's Gmail or
another teammate's connected accounts.
+OpenComputer identifies a Slack user within their Slack workspace and remembers
+the linked OpenComputer identity. The same person can therefore use their own
+connections across that workspace's OpenComputer agent apps without relinking
+each app. This identity boundary also keeps two Slack workspaces with matching
+user IDs separate.
+
## Connections and channels are different
-| Concept | Purpose | Ownership |
-| --- | --- | --- |
-| Connection | Authorizes an external service such as Gmail | Individual OpenComputer user |
-| Channel | Provides an interface for invoking a deployed agent | Agent deployment and installed workspace |
-| Channel identity link | Maps an external user to an OpenComputer user | Individual external user |
+| Concept | Purpose | Ownership |
+| --------------------- | --------------------------------------------------- | ---------------------------------------------- |
+| Connection | Authorizes an external service such as Gmail | Individual OpenComputer user |
+| Channel | Provides an interface for invoking a deployed agent | Agent deployment alias and installed workspace |
+| Channel identity link | Maps an external user to an OpenComputer user | Individual external user |
A channel does not grant service access by itself. It identifies who sent the
message, and the managed session resolves only that user's connections.
-## Disconnect a channel
-
-List remote channel installations and disconnect the one you no longer want:
-
-```bash
-opencomputer channels list --remote
-opencomputer channels disconnect slack <connection-id> --remote
-```
-
-Disconnecting a channel stops new messages from reaching the agent. It does not
-delete the agent, its deployments, or users' personal service connections.
+Disconnect Slack from the same Channels tab. This stops new messages without
+deleting the agent, its deployments, sessions, or personal service connections.
<CardGroup cols={2}>
<Card title="Connections" icon="plug" href="/agents/connections">
Authorize multiple user-scoped accounts with recognizable aliases.
</Card>
- <Card title="Agents architecture" icon="diagram-project" href="/agents/architecture">
- See how source, deployments, sessions, connections, and channels fit together.
+ <Card
+ title="Agents architecture"
+ icon="diagram-project"
+ href="/agents/architecture"
+ >
+ See how source, deployments, sessions, connections, and channels fit
+ together.
</Card>
</CardGroup>
diff --git a/docs/agents/connections.mdx b/docs/agents/connections.mdx
index 10a248d4..1ea9373d 100644
--- a/docs/agents/connections.mdx
+++ b/docs/agents/connections.mdx
@@ -72,10 +72,19 @@ The same managed connection works in both execution modes:
Provider credentials remain outside the agent's source, workspace, prompts,
and model output.
-When an agent needs a connection that the current user has not authorized,
-the session returns an authorization command and, when available, a dashboard
-link. This makes the same flow usable from the CLI, the playground, or a
-connected channel.
+Every agent runtime includes connection discovery and request tools. The agent
+can list the providers and aliases available to the current session identity,
+then ask that user to authorize a declared service when one is missing. These
+tools return connection metadata only; they never return provider credentials.
+
+In the CLI and playground, a connection request returns a secure dashboard
+link. In Slack, OpenComputer privately messages that link to the person who
+invoked the agent instead of posting it in the shared channel. After the user
+authorizes the account, later sessions can find the connection by its alias.
+
+An agent can request only connection providers declared by its deployed source.
+The user still chooses whether to authorize the account and which provider
+permissions to grant.
## List and remove connections
diff --git a/docs/agents/overview.mdx b/docs/agents/overview.mdx
index af21ca5b..a97250c8 100644
--- a/docs/agents/overview.mdx
+++ b/docs/agents/overview.mdx
@@ -11,8 +11,8 @@ without changing the agent's identity.
<CardGroup cols={2}>
<Card title="Agents as code" icon="code">
- Prompts, tools, skills, connections, and runtime settings live together in
- a normal directory you can review and commit.
+ Prompts, tools, skills, connections, and runtime settings live together in a
+ normal directory you can review and commit.
</Card>
<Card title="Local development" icon="terminal">
Run the agent locally with OpenCode, your project files, and managed
@@ -50,25 +50,23 @@ gmail-summarizer/
├── connections/
│ └── google.json
├── skills/
-├── channels/
├── workspace/
└── evals/
```
The important files are:
-| File | Purpose |
-|---|---|
-| `opencomputer.toml` | Committed identity for the agent. Keep its `id` stable across deployments. |
-| `instructions.md` | The agent's role, operating rules, and approval boundaries. |
-| `agent.ts` | Model and runtime permissions used by OpenCode. |
-| `opencomputer.config.ts` | OpenComputer runtime configuration. |
-| `tools/` | Code-native tools available to the agent. |
-| `connections/` | Declarations for managed services such as Gmail. |
-| `skills/` | Reusable domain knowledge and workflows. |
-| `channels/` | Interfaces such as Slack through which people can reach the agent. |
-| `workspace/` | Durable working files packaged with the agent. |
-| `evals/` | Repeatable checks for agent behavior. |
+| File | Purpose |
+| ------------------------ | -------------------------------------------------------------------------- |
+| `opencomputer.toml` | Committed identity for the agent. Keep its `id` stable across deployments. |
+| `instructions.md` | The agent's role, operating rules, and approval boundaries. |
+| `agent.ts` | Model and runtime permissions used by OpenCode. |
+| `opencomputer.config.ts` | OpenComputer runtime configuration. |
+| `tools/` | Code-native tools available to the agent. |
+| `connections/` | Declarations for managed services such as Gmail. |
+| `skills/` | Reusable domain knowledge and workflows. |
+| `workspace/` | Durable working files packaged with the agent. |
+| `evals/` | Repeatable checks for agent behavior. |
## Identity and versions
@@ -99,9 +97,9 @@ opencomputer deploy --alias production
closest to your job.
</Step>
<Step title="Develop locally">
- Edit the instructions, tools, and skills in your editor. Use
- `opencomputer session` for a single task or `opencomputer dev` for an
- interactive OpenCode session.
+ Edit the instructions, tools, and skills in your editor. Use `opencomputer
+ session` for a single task or `opencomputer dev` for an interactive OpenCode
+ session.
</Step>
<Step title="Connect services">
Authorize account-level connections through the CLI. OAuth credentials
@@ -134,18 +132,11 @@ By default, a completed remote turn suspends its runtime. A later
## Channels
-Channels let people invoke a deployed agent from another interface. To add
-Slack to an agent:
-
-```bash
-opencomputer channels add slack
-opencomputer deploy
-opencomputer channels connect slack --remote
-opencomputer channels list
-```
-
-The channel declaration and Slack project configuration live with the source.
-The installation credentials remain managed outside the repository.
+Channels let people invoke a deployed agent from another interface. After
+deploying, open the agent in the dashboard, select **Channels**, and connect a
+dedicated Slack app to the active deployment alias. OpenComputer generates the
+Slack manifest and guides you through installation; no Slack files or
+credentials are added to the agent repository.
<CardGroup cols={2}>
<Card title="Connections" icon="plug" href="/agents/connections">
@@ -157,10 +148,15 @@ The installation credentials remain managed outside the repository.
</CardGroup>
<CardGroup cols={2}>
- <Card title="Build a Gmail summarizer" icon="envelope" href="/agents/quickstart">
+ <Card
+ title="Build a Gmail summarizer"
+ icon="envelope"
+ href="/agents/quickstart"
+ >
Create, connect, test, and deploy an agent from a template.
</Card>
<Card title="Architecture" icon="diagram-project" href="/agents/architecture">
- See how local projects, deployments, sandboxes, and connections fit together.
+ See how local projects, deployments, sandboxes, and connections fit
+ together.
</Card>
</CardGroup>
diff --git a/web/src/managed-agents/Connections.tsx b/web/src/managed-agents/Connections.tsx
index 5b9bb452..71698542 100644
--- a/web/src/managed-agents/Connections.tsx
+++ b/web/src/managed-agents/Connections.tsx
@@ -11,6 +11,7 @@ import {
claimManagedAgentChannelIdentity,
getManagedAgentConnections,
getManagedAgents,
+ linkManagedAgentConnection,
} from './api'
function displayResourceName(value: string) {
@@ -22,9 +23,13 @@ function displayResourceName(value: string) {
export default function ManagedAgentConnections() {
const [searchParams, setSearchParams] = useSearchParams()
const channelLinkStarted = useRef(false)
+ const connectionStarted = useRef(false)
const [channelLinkState, setChannelLinkState] = useState<
'idle' | 'linking' | 'linked' | 'failed'
>('idle')
+ const [connectionRequestState, setConnectionRequestState] = useState<
+ 'idle' | 'connecting' | 'connected' | 'failed'
+ >('idle')
const requestedService = searchParams.get('service')
const requestedAlias = searchParams.get('alias') || 'default'
const connections = useQuery({
@@ -57,6 +62,35 @@ export default function ManagedAgentConnections() {
.catch(() => setChannelLinkState('failed'))
}, [searchParams, setSearchParams])
+ useEffect(() => {
+ if (
+ searchParams.get('connect') !== '1' ||
+ !requestedService ||
+ connectionStarted.current ||
+ channelLinkState === 'linking'
+ ) {
+ return
+ }
+ connectionStarted.current = true
+ setConnectionRequestState('connecting')
+ void linkManagedAgentConnection(requestedService, requestedAlias)
+ .then((result) => {
+ if (result.authorizationUrl) {
+ window.location.assign(result.authorizationUrl)
+ return
+ }
+ setConnectionRequestState('connected')
+ void connections.refetch()
+ })
+ .catch(() => setConnectionRequestState('failed'))
+ }, [
+ channelLinkState,
+ connections,
+ requestedAlias,
+ requestedService,
+ searchParams,
+ ])
+
return (
<div>
<PageHeader
@@ -84,11 +118,13 @@ export default function ManagedAgentConnections() {
{requestedAlias}”
</p>
<p className="text-muted-foreground mt-1 text-sm">
- Run{' '}
- <code className="bg-muted rounded px-1.5 py-0.5 font-mono text-xs">
- opencomputer connection add {requestedService} --alias{' '}
- {requestedAlias}
- </code>
+ {connectionRequestState === 'connecting'
+ ? 'Opening secure authorization…'
+ : connectionRequestState === 'connected'
+ ? 'This connection is ready for your sessions.'
+ : connectionRequestState === 'failed'
+ ? 'The connection could not be started. Reload this link to try again.'
+ : 'Continue to securely authorize this account.'}
</p>
</PanelContent>
</Panel>
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index 2075e154..5d4ae8b7 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -13,7 +13,6 @@ import {
GitCommitHorizontal,
Loader2,
Plus,
- Radio,
Send,
Square,
TerminalSquare,
@@ -43,11 +42,11 @@ import {
getManagedAgents,
getManagedAgentSessions,
type ManagedAgentEvent,
- type ManagedAgentChannel,
type ManagedAgentSession,
} from './api'
import { ManagedAgentChatTransport } from './chat-transport'
import { isNearScrollEnd } from './scroll-follow'
+import { ManagedSlackWizard } from './SlackWizard'
type DetailTab = 'playground' | 'deployments' | 'sessions' | 'channels'
@@ -470,57 +469,13 @@ export default function ManagedAgentDetail() {
const externalSessions = (sessions.data ?? []).filter(
(session) => session.source !== 'playground',
)
- const agentChannels = (channels.data ?? []).filter(
- (channel) => channel.agentId === agentId,
+ const activeAliasChannel = (channels.data ?? []).find(
+ (channel) =>
+ channel.agentId === agentId &&
+ channel.alias === (activeDeployment.data?.alias ?? agent?.activeAlias) &&
+ channel.status !== 'disconnected',
)
- const channelColumns: Column<ManagedAgentChannel>[] = [
- {
- key: 'channel',
- header: 'Channel',
- cell: (channel) => (
- <span className="flex items-center gap-2 text-sm capitalize">
- <Radio className="text-muted-foreground size-3.5" />
- {channel.channel}
- </span>
- ),
- },
- {
- key: 'workspace',
- header: 'Workspace',
- cell: (channel) => (
- <span className="text-muted-foreground text-sm">
- {channel.teamName || '—'}
- </span>
- ),
- },
- {
- key: 'alias',
- header: 'Deployment alias',
- cell: (channel) => (
- <span className="font-mono text-xs">{channel.alias}</span>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- cell: (channel) => <StatusBadge status={channel.status} />,
- },
- {
- key: 'updated',
- header: 'Updated',
- align: 'right',
- cell: (channel) => (
- <time
- className="text-muted-foreground text-xs"
- dateTime={channel.updatedAt}
- >
- {formatDate(channel.updatedAt)}
- </time>
- ),
- },
- ]
-
const sessionColumns: Column<ManagedAgentSession>[] = [
{
key: 'session',
@@ -639,7 +594,9 @@ export default function ManagedAgentDetail() {
<span>
{activeDeployment.data?.connections.length ?? 0} connections
</span>
- <span>{agentChannels.length} channels</span>
+ <span>
+ {activeAliasChannel?.status === 'connected' ? 1 : 0} channels
+ </span>
</div>
</div>
@@ -856,19 +813,18 @@ export default function ManagedAgentDetail() {
</PanelDescription>
</div>
</PanelHeader>
- <ResourceTable
- columns={channelColumns}
- rows={agentChannels}
- rowKey={(channel) => channel.id}
- loading={channels.isLoading}
- empty={
- <EmptyState
- icon={Radio}
- title="No channels connected"
- description="Connect Slack, Discord, or another channel from your checked-out agent project."
- />
- }
- />
+ {agent && activeDeployment.data ? (
+ <ManagedSlackWizard
+ agentId={agent.id}
+ alias={activeDeployment.data.alias}
+ agentName={displayManagedAgentName(agent)}
+ connection={activeAliasChannel}
+ />
+ ) : (
+ <PanelContent className="text-muted-foreground text-sm">
+ Loading channels…
+ </PanelContent>
+ )}
</Panel>
) : null}
</div>
diff --git a/web/src/managed-agents/Home.tsx b/web/src/managed-agents/Home.tsx
index 865a0a6d..03e2a4a8 100644
--- a/web/src/managed-agents/Home.tsx
+++ b/web/src/managed-agents/Home.tsx
@@ -116,10 +116,10 @@ Use the OpenComputer CLI and keep the agent as editable source code in this work
3. Initialize the source template in the current repository:
${cliCommand(origin, `init ${template.id} .`)}
4. Run \`npm install\` in the repository.
-5. Inspect and tailor the checked-in source: \`opencomputer.toml\`, \`instructions.md\`, \`agent.ts\`, \`tools/\`, \`connections/\`, \`channels/\`, \`skills/\`, \`workspace/\`, and \`evals/\`.
+5. Inspect and tailor the checked-in source: \`opencomputer.toml\`, \`instructions.md\`, \`agent.ts\`, \`tools/\`, \`connections/\`, \`skills/\`, \`workspace/\`, and \`evals/\`.
6. Keep the stable \`id\` in \`opencomputer.toml\`; future deployments of this repository must create new versions of that same agent.
-7. Add and authorize only supported integrations. For Gmail, use \`opencomputer tools add gmail\` and \`${cliCommand(origin, 'connect google')}\`. For Slack, use \`opencomputer channels add slack\`.
-8. Test the editable agent locally with OpenCode:
+7. Add and authorize only supported connections. For Gmail, use \`opencomputer tools add gmail\` and \`${cliCommand(origin, 'connect google')}\`. Connect Slack from the deployed agent's Channels tab after deployment.
+8. Test the editable agent locally with the OpenComputer CLI:
\`opencomputer session "${firstPrompt.replace(/"/g, '\\"')}"\`
9. Make any necessary source changes and test again.
10. Commit the agent source, including \`opencomputer.toml\`, to Git.
diff --git a/web/src/managed-agents/SlackWizard.tsx b/web/src/managed-agents/SlackWizard.tsx
new file mode 100644
index 00000000..1eb71611
--- /dev/null
+++ b/web/src/managed-agents/SlackWizard.tsx
@@ -0,0 +1,374 @@
+import { useState } from 'react'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { Check, Copy, ExternalLink, MessageSquare } from 'lucide-react'
+import { ConfirmDialog } from '@/components/confirm-dialog'
+import { Field, Input } from '@/components/form'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { StatusBadge } from '@/components/status-badge'
+import { notifyError } from '@/lib/errors'
+import { useTransientFlag } from '@/lib/use-transient-flag'
+import { cn } from '@/lib/utils'
+import {
+ completeManagedAgentSlack,
+ disconnectManagedAgentSlack,
+ startManagedAgentSlack,
+ type ManagedAgentChannel,
+ type ManagedSlackManifest,
+} from './api'
+
+type Step = 'create' | 'details' | 'install' | 'done'
+const STEPS = ['Create app', 'Details', 'Install', 'Done']
+
+function WizardSteps({ current }: { current: number }) {
+ return (
+ <ol className="flex items-center gap-2 pt-2">
+ {STEPS.map((label, index) => (
+ <li key={label} className="flex min-w-0 items-center gap-2">
+ <span
+ className={cn(
+ 'flex size-5 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold',
+ index <= current
+ ? 'bg-foreground text-background'
+ : 'bg-secondary text-muted-foreground',
+ )}
+ >
+ {index < current ? <Check className="size-3" /> : index + 1}
+ </span>
+ <span
+ className={cn(
+ 'truncate text-xs',
+ index === current
+ ? 'text-foreground font-medium'
+ : 'text-muted-foreground',
+ )}
+ >
+ {label}
+ </span>
+ {index < STEPS.length - 1 ? (
+ <span className="bg-border h-px w-4 shrink-0" />
+ ) : null}
+ </li>
+ ))}
+ </ol>
+ )
+}
+
+export function ManagedSlackWizard({
+ agentId,
+ alias,
+ agentName,
+ connection,
+}: {
+ agentId: string
+ alias: string
+ agentName: string
+ connection?: ManagedAgentChannel
+}) {
+ const queryClient = useQueryClient()
+ const [open, setOpen] = useState(false)
+ const [step, setStep] = useState<Step>('create')
+ const [appName, setAppName] = useState(agentName)
+ const [manifest, setManifest] = useState<ManagedSlackManifest>()
+ const [appId, setAppId] = useState('')
+ const [signingSecret, setSigningSecret] = useState('')
+ const [botToken, setBotToken] = useState('')
+ const [confirmDisconnect, setConfirmDisconnect] = useState(false)
+ const [copied, markCopied] = useTransientFlag(1500)
+
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ['managed-agent-channels'] })
+
+ const start = useMutation({
+ mutationFn: () =>
+ startManagedAgentSlack(`${agentId}@${alias}`, appName.trim(), false),
+ onSuccess: (result) => {
+ setManifest(result)
+ void invalidate()
+ },
+ onError: (error) => notifyError("Couldn't prepare the Slack app.", error),
+ })
+ const complete = useMutation({
+ mutationFn: () =>
+ completeManagedAgentSlack(manifest!.connection.id, {
+ appId: appId.trim(),
+ signingSecret: signingSecret.trim(),
+ botToken: botToken.trim(),
+ }),
+ onSuccess: () => {
+ setStep('done')
+ setSigningSecret('')
+ setBotToken('')
+ void invalidate()
+ },
+ onError: (error) =>
+ notifyError('Slack rejected those values. Double-check them.', error),
+ })
+ const disconnect = useMutation({
+ mutationFn: () => disconnectManagedAgentSlack(connection!.id),
+ onSuccess: () => {
+ setConfirmDisconnect(false)
+ void invalidate()
+ },
+ onError: (error) => notifyError("Couldn't disconnect Slack.", error),
+ })
+
+ const reset = () => {
+ setStep('create')
+ setManifest(undefined)
+ setAppId('')
+ setSigningSecret('')
+ setBotToken('')
+ }
+ const begin = () => {
+ reset()
+ setOpen(true)
+ }
+ const stepIndex =
+ step === 'create' ? 0 : step === 'details' ? 1 : step === 'install' ? 2 : 3
+
+ return (
+ <>
+ <div className="flex flex-wrap items-center justify-between gap-4 border-b px-5 py-4">
+ <div className="flex min-w-0 items-center gap-3">
+ <span className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-md">
+ <MessageSquare className="size-4" />
+ </span>
+ <div className="min-w-0">
+ <p className="text-sm font-medium">
+ {connection?.appName || agentName}
+ </p>
+ <p className="text-muted-foreground truncate text-xs">
+ {connection?.status === 'connected'
+ ? `Slack · ${connection.teamName || 'Connected workspace'}`
+ : `Connect a dedicated Slack app to @${alias}`}
+ </p>
+ {connection?.status === 'connected' ? (
+ <p className="text-muted-foreground mt-1 text-xs">
+ Invite this app to a channel before @mentioning it. Direct
+ messages work without an invite.
+ </p>
+ ) : null}
+ </div>
+ {connection ? <StatusBadge status={connection.status} /> : null}
+ </div>
+ <div className="flex items-center gap-2">
+ {connection?.status === 'connected' ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setConfirmDisconnect(true)}
+ >
+ Disconnect
+ </Button>
+ ) : null}
+ {connection?.status !== 'connected' ? (
+ <Button size="sm" variant="outline" onClick={begin}>
+ {connection ? 'Continue setup' : 'Connect Slack'}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next)
+ if (!next) reset()
+ }}
+ >
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>
+ {step === 'done' ? 'Slack is connected' : 'Connect Slack'}
+ </DialogTitle>
+ <DialogDescription>
+ This Slack app belongs only to {agentName} @{alias}.
+ </DialogDescription>
+ <WizardSteps current={stepIndex} />
+ </DialogHeader>
+
+ {step === 'create' ? (
+ <div className="space-y-4">
+ <Field
+ label="Slack app name"
+ htmlFor="managed-slack-app-name"
+ description="This is the name people will see in Slack."
+ >
+ <Input
+ id="managed-slack-app-name"
+ value={appName}
+ maxLength={35}
+ onChange={(event) => {
+ setAppName(event.target.value)
+ setManifest(undefined)
+ }}
+ />
+ </Field>
+ {!manifest ? (
+ <Button
+ variant="outline"
+ onClick={() => start.mutate()}
+ disabled={!appName.trim() || start.isPending}
+ >
+ {start.isPending ? 'Preparing…' : 'Generate Slack manifest'}
+ </Button>
+ ) : (
+ <>
+ <p className="text-muted-foreground text-sm">
+ Copy this manifest, then create the app from it in Slack.
+ </p>
+ <div className="flex flex-wrap items-center gap-3">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ void navigator.clipboard
+ .writeText(JSON.stringify(manifest.manifest, null, 2))
+ .then(markCopied)
+ }}
+ >
+ {copied ? <Check /> : <Copy />}
+ {copied ? 'Copied' : 'Copy manifest'}
+ </Button>
+ <a
+ href={manifest.createUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1.5 text-sm underline underline-offset-4"
+ >
+ Open Slack apps <ExternalLink className="size-3.5" />
+ </a>
+ </div>
+ <pre className="bg-muted/30 max-h-56 overflow-auto rounded-md border p-3 text-xs whitespace-pre-wrap">
+ {JSON.stringify(manifest.manifest, null, 2)}
+ </pre>
+ </>
+ )}
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => setOpen(false)}>
+ Cancel
+ </Button>
+ <Button disabled={!manifest} onClick={() => setStep('details')}>
+ Next: app details
+ </Button>
+ </DialogFooter>
+ </div>
+ ) : step === 'details' ? (
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ setStep('install')
+ }}
+ >
+ <p className="text-muted-foreground text-sm">
+ In Basic Information → App Credentials, copy these values.
+ </p>
+ <Field label="App ID" htmlFor="managed-slack-app-id">
+ <Input
+ id="managed-slack-app-id"
+ value={appId}
+ onChange={(event) => setAppId(event.target.value)}
+ placeholder="A01234ABCDE"
+ />
+ </Field>
+ <Field label="Signing Secret" htmlFor="managed-slack-secret">
+ <Input
+ id="managed-slack-secret"
+ type="password"
+ value={signingSecret}
+ onChange={(event) => setSigningSecret(event.target.value)}
+ placeholder="••••••••"
+ />
+ <p className="text-muted-foreground mt-1 text-xs">
+ Copy the field labeled Signing Secret, not Client Secret.
+ </p>
+ </Field>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setStep('create')}
+ >
+ Back
+ </Button>
+ <Button
+ type="submit"
+ disabled={!appId.trim() || !signingSecret.trim()}
+ >
+ Next: install
+ </Button>
+ </DialogFooter>
+ </form>
+ ) : step === 'install' ? (
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ complete.mutate()
+ }}
+ >
+ <p className="text-muted-foreground text-sm">
+ Install the app to your workspace, then copy its Bot User OAuth
+ Token.
+ </p>
+ <Field label="Bot User OAuth Token" htmlFor="managed-slack-token">
+ <Input
+ id="managed-slack-token"
+ type="password"
+ value={botToken}
+ onChange={(event) => setBotToken(event.target.value)}
+ placeholder="xoxb-…"
+ />
+ </Field>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setStep('details')}
+ >
+ Back
+ </Button>
+ <Button
+ type="submit"
+ disabled={!botToken.trim() || complete.isPending}
+ >
+ {complete.isPending ? 'Connecting…' : 'Connect Slack'}
+ </Button>
+ </DialogFooter>
+ </form>
+ ) : (
+ <div className="space-y-4">
+ <p className="text-sm">
+ {appName} is connected. Invite it to a channel and @-mention it,
+ or message it directly, to start a session.
+ </p>
+ <DialogFooter>
+ <Button onClick={() => setOpen(false)}>Done</Button>
+ </DialogFooter>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+
+ <ConfirmDialog
+ open={confirmDisconnect}
+ onOpenChange={setConfirmDisconnect}
+ title="Disconnect Slack?"
+ description="This agent will stop receiving Slack messages. Its bot token and signing secret will be removed."
+ confirmLabel="Disconnect"
+ destructive
+ pending={disconnect.isPending}
+ onConfirm={() => disconnect.mutate()}
+ />
+ </>
+ )
+}
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 6f336404..7681aacf 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -59,7 +59,11 @@ const channelSchema = z.object({
channel: z.string(),
agentId: z.string(),
alias: z.string(),
+ appName: z.string().nullish(),
teamName: z.string().nullish(),
+ appId: z.string().nullish(),
+ teamId: z.string().nullish(),
+ botUserId: z.string().nullish(),
status: z.string(),
createdAt: z.string(),
updatedAt: z.string(),
@@ -71,10 +75,25 @@ const connectionsResponseSchema = z.object({
const channelIdentityLinkSchema = z.object({ linked: z.literal(true) })
+const connectionLinkSchema = z.object({
+ connectionId: z.string(),
+ service: z.string(),
+ label: z.string(),
+ status: z.enum(['connected', 'pending']),
+ authorizationUrl: z.string().url().optional(),
+})
+
const channelsResponseSchema = z.object({
channels: z.array(channelSchema),
})
+const slackManifestResponseSchema = z.object({
+ connection: channelSchema,
+ manifest: z.record(z.string(), z.unknown()),
+ createUrl: z.string().url(),
+ steps: z.array(z.string()),
+})
+
const sessionCreateSchema = z.object({
session: z.object({ id: z.string() }),
deployment: deploymentSchema.optional(),
@@ -130,6 +149,7 @@ export type ManagedAgentEvent = z.infer<typeof eventSchema>
export type ManagedAgentSession = z.infer<typeof sessionSchema>
export type ManagedAgentConnection = z.infer<typeof connectionSchema>
export type ManagedAgentChannel = z.infer<typeof channelSchema>
+export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>
const UUID_NAME =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
@@ -178,6 +198,20 @@ export async function claimManagedAgentChannelIdentity(token: string) {
)
}
+export async function linkManagedAgentConnection(
+ service: string,
+ label: string,
+) {
+ return apiFetch(
+ '/managed-agents/connections/link',
+ {
+ method: 'POST',
+ body: JSON.stringify({ service, label }),
+ },
+ connectionLinkSchema,
+ )
+}
+
export async function getManagedAgentChannels() {
return (
await apiFetch(
@@ -188,6 +222,40 @@ export async function getManagedAgentChannels() {
).channels
}
+export async function startManagedAgentSlack(
+ agentId: string,
+ name: string,
+ reconnect = false,
+) {
+ return apiFetch(
+ '/managed-agents/channels/slack/connections',
+ {
+ method: 'POST',
+ body: JSON.stringify({ agentId, name, reconnect }),
+ },
+ slackManifestResponseSchema,
+ )
+}
+
+export async function completeManagedAgentSlack(
+ connectionId: string,
+ input: { appId: string; signingSecret: string; botToken: string },
+) {
+ return apiFetch(
+ `/managed-agents/channels/slack/connections/${encodeURIComponent(connectionId)}`,
+ { method: 'PUT', body: JSON.stringify(input) },
+ channelSchema,
+ )
+}
+
+export async function disconnectManagedAgentSlack(connectionId: string) {
+ return apiFetch(
+ `/managed-agents/channels/slack/connections/${encodeURIComponent(connectionId)}`,
+ { method: 'DELETE' },
+ channelSchema,
+ )
+}
+
export async function getManagedAgentDeployment(deploymentId: string) {
return apiFetch(
`/managed-agents/deployments/${encodeURIComponent(deploymentId)}`,