Skip to content

An open-source, faster Devin alternative

TypeScript

Add code-defined channels and outbox operations (#640)

Mohamed Habib9072c3bdffd4
diff --git a/agent/package-lock.json b/agent/package-lock.json
index e541f60a..b13d2d19 100644
--- a/agent/package-lock.json
+++ b/agent/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/agent",
- "version": "0.4.1",
+ "version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/agent",
- "version": "0.4.1",
+ "version": "0.5.0",
"devDependencies": {
"typescript": "^5.9.0"
},
diff --git a/agent/package.json b/agent/package.json
index 55658061..06753496 100644
--- a/agent/package.json
+++ b/agent/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/agent",
- "version": "0.4.1",
+ "version": "0.5.0",
"description": "Reactive agent authoring API for OpenComputer.",
"type": "module",
"main": "./dist/index.js",
diff --git a/agent/src/index.ts b/agent/src/index.ts
index d33e7206..4912cb30 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -59,6 +59,116 @@ export interface McpServerDefinition extends ResourceReference {
readonly connection?: ConnectionReference;
}
+export type SlackChannelEvent = "app_mention" | "message.im";
+export type ChannelTrigger = "mention" | "direct-message";
+
+export interface ChannelDestinationDefinition {
+ readonly type: "conversation";
+ readonly visibility: "public" | "private";
+}
+
+export interface SlackChannelDefinition extends ResourceReference {
+ readonly kind: "channel";
+ readonly version: 1;
+ readonly type: "slack";
+ readonly displayName?: string;
+ readonly scopes: {
+ readonly bot: readonly string[];
+ };
+ readonly events: readonly SlackChannelEvent[];
+ readonly destinations: Readonly<
+ Record<string, Readonly<ChannelDestinationDefinition>>
+ >;
+ readonly routing: {
+ readonly whenAmbiguous: "ask";
+ };
+}
+
+export interface ChannelRegistrationDefinition extends ResourceReference {
+ readonly kind: "channel-registration";
+ readonly version: 1;
+ readonly channelId: string;
+ readonly triggers: readonly ChannelTrigger[];
+}
+
+export interface OutboxPublishInput {
+ readonly type: string;
+ readonly content: DataValue;
+ readonly idempotencyKey: string;
+}
+
+export interface OutboxPublishResult {
+ readonly id: string;
+ readonly status: "pending" | "delivering" | "delivered" | "failed";
+ readonly duplicate: boolean;
+}
+
+export interface OutboxDefinition extends ResourceReference {
+ readonly kind: "outbox";
+ readonly version: 1;
+ readonly delivery: {
+ readonly channelId: string;
+ readonly destination: string;
+ };
+ publish(input: OutboxPublishInput): Promise<OutboxPublishResult>;
+}
+
+export interface OutboxRegistrationDefinition extends ResourceReference {
+ readonly kind: "outbox-registration";
+ readonly version: 1;
+ readonly outboxId: string;
+}
+
+function outboxEventType(value: string): string {
+ const type = value.trim();
+ if (!/^[a-z0-9]+(?:[a-z0-9.-]*[a-z0-9])?$/.test(type)) {
+ throw new Error("Outbox event types must use lowercase dot notation");
+ }
+ return type;
+}
+
+export async function publishOutbox(
+ outbox: string | ResourceReference,
+ input: OutboxPublishInput,
+): Promise<OutboxPublishResult> {
+ const id = resourceIdentifier(
+ typeof outbox === "string" ? outbox : outbox.id,
+ "publishOutbox",
+ );
+ const type = outboxEventType(input.type);
+ const idempotencyKey = input.idempotencyKey.trim();
+ if (!idempotencyKey || idempotencyKey.length > 256) {
+ throw new Error("Outbox idempotency keys must contain 1 to 256 characters");
+ }
+ const runtime = globalThis as typeof globalThis & {
+ process?: { env?: Record<string, string | undefined> };
+ };
+ const base = runtime.process?.env?.OPENCOMPUTER_OUTBOX_URL;
+ const token = runtime.process?.env?.OPENCOMPUTER_OUTBOX_TOKEN;
+ if (!base || !token) {
+ throw new Error("OpenComputer outbox delivery is unavailable");
+ }
+ const response = await fetch(
+ `${base.replace(/\/$/, "")}/${encodeURIComponent(id)}/items`,
+ {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${token}`,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ type,
+ content: input.content,
+ idempotencyKey,
+ }),
+ },
+ );
+ if (!response.ok) {
+ throw new Error(`Outbox publish failed with status ${response.status}`);
+ }
+ return (await response.json()) as OutboxPublishResult;
+}
+
export type ModelSelection =
| string
| { readonly provider: string; readonly model: string };
@@ -270,6 +380,142 @@ export function defineMcpServer(input: {
});
}
+const RESOURCE_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+const SLACK_SCOPE_PATTERN = /^[a-z][a-z0-9_.-]*:[a-z][a-z0-9_.-]*$/;
+const SLACK_EVENT_SCOPE: Readonly<Record<SlackChannelEvent, string>> = {
+ app_mention: "app_mentions:read",
+ "message.im": "im:history",
+};
+const TRIGGER_EVENT: Readonly<Record<ChannelTrigger, SlackChannelEvent>> = {
+ mention: "app_mention",
+ "direct-message": "message.im",
+};
+
+function resourceIdentifier(value: string, kind: string): string {
+ const id = identifier(value, kind);
+ if (!RESOURCE_ID_PATTERN.test(id)) {
+ throw new Error(
+ `${kind} IDs must use lowercase letters, numbers, and single hyphens`,
+ );
+ }
+ return id;
+}
+
+export function defineChannel(input: {
+ id: string;
+ type: "slack";
+ displayName?: string;
+ scopes: { bot: readonly string[] };
+ events?: readonly SlackChannelEvent[];
+ destinations?: Readonly<Record<string, ChannelDestinationDefinition>>;
+ routing?: { whenAmbiguous?: "ask" };
+}): SlackChannelDefinition {
+ const id = resourceIdentifier(input.id, "defineChannel");
+ const scopes = [...new Set(input.scopes.bot.map((scope) => scope.trim()))];
+ if (!scopes.length || scopes.some((scope) => !SLACK_SCOPE_PATTERN.test(scope))) {
+ throw new Error("Slack bot scopes must be non-empty Slack scope names");
+ }
+ const events = [...new Set(input.events ?? [])];
+ for (const event of events) {
+ const required = SLACK_EVENT_SCOPE[event];
+ if (!scopes.includes(required)) {
+ throw new Error(`Slack event ${event} requires bot scope ${required}`);
+ }
+ }
+ const destinations: Record<string, Readonly<ChannelDestinationDefinition>> = {};
+ for (const [name, destination] of Object.entries(input.destinations ?? {})) {
+ const destinationId = resourceIdentifier(name, "Channel destination");
+ const required =
+ destination.visibility === "private" ? "groups:read" : "channels:read";
+ if (!scopes.includes(required)) {
+ throw new Error(`Slack destination ${destinationId} requires bot scope ${required}`);
+ }
+ if (!scopes.includes("chat:write")) {
+ throw new Error(`Slack destination ${destinationId} requires bot scope chat:write`);
+ }
+ destinations[destinationId] = Object.freeze({ ...destination });
+ }
+ return Object.freeze({
+ kind: "channel" as const,
+ version: 1 as const,
+ id,
+ type: input.type,
+ ...(input.displayName?.trim() ? { displayName: input.displayName.trim() } : {}),
+ scopes: Object.freeze({ bot: Object.freeze(scopes) }),
+ events: Object.freeze(events),
+ destinations: Object.freeze(destinations),
+ routing: Object.freeze({ whenAmbiguous: input.routing?.whenAmbiguous ?? "ask" }),
+ });
+}
+
+export function registerChannel(
+ channel: SlackChannelDefinition,
+ input: { on: readonly ChannelTrigger[] },
+): ChannelRegistrationDefinition {
+ const triggers = [...new Set(input.on)];
+ if (!triggers.length) {
+ throw new Error("registerChannel requires at least one trigger");
+ }
+ for (const trigger of triggers) {
+ const event = TRIGGER_EVENT[trigger];
+ if (!channel.events.includes(event)) {
+ throw new Error(
+ `Channel ${channel.id} does not declare the event required by ${trigger}`,
+ );
+ }
+ }
+ return Object.freeze({
+ kind: "channel-registration" as const,
+ version: 1 as const,
+ id: channel.id,
+ channelId: channel.id,
+ triggers: Object.freeze(triggers),
+ });
+}
+
+export function defineOutbox(input: {
+ id: string;
+ delivery: {
+ channel: SlackChannelDefinition;
+ destination: string;
+ };
+}): OutboxDefinition {
+ const id = resourceIdentifier(input.id, "defineOutbox");
+ const destination = resourceIdentifier(
+ input.delivery.destination,
+ "Outbox destination",
+ );
+ if (!input.delivery.channel.destinations[destination]) {
+ throw new Error(
+ `Outbox ${id} references unknown destination ${destination} on channel ${input.delivery.channel.id}`,
+ );
+ }
+ const delivery = Object.freeze({
+ channelId: input.delivery.channel.id,
+ destination,
+ });
+ return Object.freeze({
+ kind: "outbox" as const,
+ version: 1 as const,
+ id,
+ delivery,
+ async publish(input: OutboxPublishInput): Promise<OutboxPublishResult> {
+ return publishOutbox(id, input);
+ },
+ });
+}
+
+export function registerOutbox(
+ outbox: OutboxDefinition,
+): OutboxRegistrationDefinition {
+ return Object.freeze({
+ kind: "outbox-registration" as const,
+ version: 1 as const,
+ id: outbox.id,
+ outboxId: outbox.id,
+ });
+}
+
export function defineTool<Output extends DataValue = DataValue>(input: {
name: string;
description: string;
diff --git a/cli/package-lock.json b/cli/package-lock.json
index c31674ee..756eadf6 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/cli",
- "version": "0.5.2",
+ "version": "0.5.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/cli",
- "version": "0.5.2",
+ "version": "0.5.3",
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"ai": "^7.0.45",
diff --git a/cli/package.json b/cli/package.json
index 2108475a..b7164792 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/cli",
- "version": "0.5.2",
+ "version": "0.5.3",
"description": "Build, test, deploy, and share OpenComputer agents as code.",
"type": "module",
"bin": {
diff --git a/cli/src/api.ts b/cli/src/api.ts
index 61135164..c99a56f2 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -1,4 +1,5 @@
import type { ResolvedConfig } from "./config.js";
+import type { ProjectResourceManifest } from "./project.js";
export interface OpenComputerIdentity {
user_id: string | null;
@@ -34,6 +35,8 @@ export interface ManagedAgentDeployment {
id: string;
agentId: string;
alias: string;
+ projectDeploymentId?: string;
+ localAgentId?: string;
createdAt: string;
}
@@ -300,6 +303,13 @@ export class OpenComputerClient {
pathPrefix?: string;
redirectOrigins?: Array<{ origin: string; pathPrefix?: string }>;
}>;
+ projectDeployment?: {
+ id: string;
+ digest: string;
+ localAgentId: string;
+ agents: Array<{ localId: string; agentId: string; artifactDigest: string }>;
+ resources: ProjectResourceManifest;
+ };
source: {
digest: string;
size: number;
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index 7d8b8282..7f6a34ae 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -6,7 +6,7 @@ import {
} from "./api.js";
import { login, logout } from "./auth.js";
import { resolveConfig } from "./config.js";
-import { runCloudDevelopment } from "./dev.js";
+import { publishProjectDeployment, runCloudDevelopment } from "./dev.js";
import {
ensureProjectBinding,
findOpenComputerProjectRoot,
@@ -555,32 +555,37 @@ export async function runCommand(
if (command === "deploy") {
const alias = option(args, "--alias") ?? "production";
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
- const built = await buildAgentArtifact(await requireAgentRoot());
- process.stderr.write(
- `Built ${built.agentId} in ${String(built.elapsedMs)}ms\n`,
- );
- const deployment = await client.registerDeployment({
- agentId: built.agentId,
- name: built.name,
- alias,
- channels: built.channels,
- connections: built.connections,
- httpConnections: built.httpConnections,
- source: {
- digest: built.digest,
- size: built.body.byteLength,
- contentType: "application/vnd.opencomputer.agent+json",
- body: built.body.toString("utf8"),
- },
+ const root = await findOpenComputerProjectRoot(process.cwd());
+ if (!root) {
+ throw new Error(
+ "No OpenComputer project found. Run `opencomputer init <directory>` first.",
+ );
+ }
+ const binding = await ensureProjectBinding(client, config, root, {
+ interactive: !globals.json,
+ select: true,
});
- if (globals.json) printJSON(deployment);
- else {
- process.stdout.write(
- `Deployed ${deployment.agentId}@${deployment.alias}\n` +
- `Deployment: ${deployment.id}\n` +
- `Source ID: opencomputer.toml\n`,
+ const results = await publishProjectDeployment(
+ client,
+ root,
+ binding,
+ alias,
+ );
+ for (const { built } of results) {
+ process.stderr.write(
+ `Built ${built.agentId} in ${String(built.elapsedMs)}ms\n`,
);
}
+ if (globals.json) printJSON(results.map(({ deployment }) => deployment));
+ else {
+ for (const { deployment } of results) {
+ process.stdout.write(
+ `Deployed ${deployment.agentId}@${deployment.alias}\n` +
+ `Deployment: ${deployment.id}\n` +
+ `Source ID: opencomputer.toml\n`,
+ );
+ }
+ }
return;
}
diff --git a/cli/src/dev.ts b/cli/src/dev.ts
index 5797e8fb..8e402d72 100644
--- a/cli/src/dev.ts
+++ b/cli/src/dev.ts
@@ -15,7 +15,13 @@ import {
type ProjectBindingOptions,
} from "./binding.js";
import { startGateway } from "./local.js";
-import { buildAgentArtifact, readProjectAgents } from "./project.js";
+import {
+ buildAgentArtifact,
+ readProjectAgents,
+ readProjectResources,
+ type BuiltAgentArtifact,
+ type ProjectResourceManifest,
+} from "./project.js";
const DEVELOPMENT_ALIAS = "development";
const DEBOUNCE_MS = 180;
@@ -208,15 +214,43 @@ export async function publishDevelopment(
client: Pick<OpenComputerClient, "registerDeployment">,
root: string,
agentId?: string,
+ projectDeployment?: {
+ id: string;
+ digest: string;
+ localAgentId: string;
+ agents: Array<{ localId: string; agentId: string; artifactDigest: string }>;
+ resources: ProjectResourceManifest;
+ },
) {
const built = await buildAgentArtifact(root, agentId);
+ return registerBuiltDeployment(
+ client,
+ built,
+ DEVELOPMENT_ALIAS,
+ projectDeployment,
+ );
+}
+
+async function registerBuiltDeployment(
+ client: Pick<OpenComputerClient, "registerDeployment">,
+ built: BuiltAgentArtifact,
+ alias: string,
+ projectDeployment?: {
+ id: string;
+ digest: string;
+ localAgentId: string;
+ agents: Array<{ localId: string; agentId: string; artifactDigest: string }>;
+ resources: ProjectResourceManifest;
+ },
+) {
const deployment = await client.registerDeployment({
agentId: built.agentId,
name: built.name,
- alias: DEVELOPMENT_ALIAS,
+ alias,
channels: built.channels,
connections: built.connections,
httpConnections: built.httpConnections,
+ ...(projectDeployment ? { projectDeployment } : {}),
source: {
digest: built.digest,
size: built.body.byteLength,
@@ -239,16 +273,60 @@ export async function publishProjectDevelopment(
client: Pick<OpenComputerClient, "registerDeployment">,
projectRoot: string,
binding: ProjectBinding,
+) {
+ return publishProjectDeployment(
+ client,
+ projectRoot,
+ binding,
+ DEVELOPMENT_ALIAS,
+ );
+}
+
+export async function publishProjectDeployment(
+ client: Pick<OpenComputerClient, "registerDeployment">,
+ projectRoot: string,
+ binding: ProjectBinding,
+ alias: string,
) {
const agents = await readProjectAgents(projectRoot);
- const results = [];
+ const resources = await readProjectResources(projectRoot);
+ const builtAgents = [];
for (const [index, agent] of agents.entries()) {
- results.push(
- await publishDevelopment(
- client,
+ builtAgents.push({
+ source: agent,
+ built: await buildAgentArtifact(
agent.root,
cloudAgentId(binding, agent.localId, index),
),
+ });
+ }
+ const digest = createHash("sha256")
+ .update(
+ JSON.stringify({
+ resources: resources.digest,
+ agents: builtAgents.map(({ source, built }) => ({
+ id: source.localId,
+ artifact: built.digest,
+ })),
+ }),
+ )
+ .digest("hex");
+ const id = `project:${binding.projectId}:${digest}`;
+ const roster = builtAgents.map(({ source, built }) => ({
+ localId: source.localId,
+ agentId: built.agentId,
+ artifactDigest: built.digest,
+ }));
+ const results = [];
+ for (const { source, built } of builtAgents) {
+ results.push(
+ await registerBuiltDeployment(client, built, alias, {
+ id,
+ digest,
+ localAgentId: source.localId,
+ agents: roster,
+ resources: resources.manifest,
+ }),
);
}
return results;
diff --git a/cli/src/project.test.ts b/cli/src/project.test.ts
index 4bd2c1b0..851aa024 100644
--- a/cli/src/project.test.ts
+++ b/cli/src/project.test.ts
@@ -16,6 +16,7 @@ import {
findAgentRoot,
initializeAgentProject,
prepareAgent,
+ readProjectResources,
} from "./project.js";
test("init creates a multi-agent-ready project and React hello world app", async () => {
@@ -55,7 +56,7 @@ test("init creates a multi-agent-ready project and React hello world app", async
};
assert.equal(packageJSON.scripts.dev, "opencomputer dev");
assert.equal(packageJSON.scripts["dev:web"], undefined);
- assert.equal(packageJSON.dependencies["@opencomputer/agent"], "^0.4.0");
+ assert.equal(packageJSON.dependencies["@opencomputer/agent"], "^0.5.0");
assert.equal(packageJSON.dependencies["@opencomputer/react"], "^0.1.0");
assert.equal(packageJSON.devDependencies["@opencomputer/cli"], "^0.5.0");
assert.ok(packageJSON.devDependencies["@types/node"]);
@@ -117,6 +118,102 @@ test("init creates a multi-agent-ready project and React hello world app", async
}
});
+test("the compiler normalizes project channels, registrations, and outboxes", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-channels-"));
+ const root = resolve(parent, "app");
+ try {
+ const initialized = await initializeAgentProject(root, undefined, {
+ spa: false,
+ });
+ const opencomputer = resolve(root, "opencomputer");
+ await mkdir(resolve(opencomputer, "channels"), { recursive: true });
+ await mkdir(resolve(opencomputer, "outboxes"), { recursive: true });
+ await mkdir(resolve(initialized.agentRoot, "channels"), { recursive: true });
+ await mkdir(resolve(initialized.agentRoot, "outboxes"), { recursive: true });
+ await writeFile(
+ resolve(opencomputer, "channels", "team-slack.ts"),
+ `import { defineChannel } from "@opencomputer/agent";
+export default defineChannel({
+ id: "team-slack",
+ type: "slack",
+ scopes: { bot: ["chat:write", "channels:read", "app_mentions:read"] },
+ events: ["app_mention"],
+ destinations: {
+ "pull-request-reviews": { type: "conversation", visibility: "public" },
+ },
+ routing: { whenAmbiguous: "ask" },
+});
+`,
+ );
+ await writeFile(
+ resolve(opencomputer, "outboxes", "review-requests.ts"),
+ `import { defineOutbox } from "@opencomputer/agent";
+import teamSlack from "../channels/team-slack.js";
+export default defineOutbox({
+ id: "review-requests",
+ delivery: { channel: teamSlack, destination: "pull-request-reviews" },
+});
+`,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "channels", "team-slack.ts"),
+ `import { registerChannel } from "@opencomputer/agent";
+import teamSlack from "../../../channels/team-slack.js";
+export default registerChannel(teamSlack, { on: ["mention"] });
+`,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "outboxes", "review-requests.ts"),
+ `import { registerOutbox } from "@opencomputer/agent";
+import reviewRequests from "../../../outboxes/review-requests.js";
+export default registerOutbox(reviewRequests);
+`,
+ );
+
+ const built = await readProjectResources(root);
+ assert.match(built.digest, /^[a-f0-9]{64}$/);
+ assert.deepEqual(built.manifest, {
+ version: 1,
+ channels: [
+ {
+ id: "team-slack",
+ type: "slack",
+ scopes: {
+ bot: ["app_mentions:read", "channels:read", "chat:write"],
+ },
+ events: ["app_mention"],
+ destinations: {
+ "pull-request-reviews": {
+ type: "conversation",
+ visibility: "public",
+ },
+ },
+ routing: { whenAmbiguous: "ask" },
+ },
+ ],
+ channelRegistrations: [
+ {
+ agentId: "hello-world",
+ channelId: "team-slack",
+ triggers: ["mention"],
+ },
+ ],
+ outboxes: [
+ {
+ id: "review-requests",
+ channelId: "team-slack",
+ destination: "pull-request-reviews",
+ },
+ ],
+ outboxRegistrations: [
+ { agentId: "hello-world", outboxId: "review-requests" },
+ ],
+ });
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
test("init can create an agent-only project", async () => {
const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-agent-only-"));
const root = resolve(parent, "hello-agent");
@@ -352,6 +449,71 @@ export default function Agent() {
}
});
+test("packaged tools can publish to a registered outbox by id", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-outbox-publish-"));
+ const root = resolve(parent, "app");
+ const originalFetch = globalThis.fetch;
+ const originalUrl = process.env.OPENCOMPUTER_OUTBOX_URL;
+ const originalToken = process.env.OPENCOMPUTER_OUTBOX_TOKEN;
+ try {
+ const initialized = await initializeAgentProject(root);
+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });
+ await writeFile(
+ resolve(initialized.agentRoot, "tools", "notify.ts"),
+ `import { defineTool, publishOutbox } from "@opencomputer/agent";
+export const notify = defineTool({
+ name: "notify_reviewer",
+ description: "Notify a pull request reviewer",
+ async run() {
+ return publishOutbox("review-requests", {
+ type: "pull-request.ready",
+ idempotencyKey: "example/repo#42",
+ content: { title: "Review requested", url: "https://example.com/pull/42" },
+ });
+ },
+});
+`,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "agent.ts"),
+ `import { useTool } from "@opencomputer/agent";
+import { notify } from "./tools/notify.js";
+export default function Agent() { useTool(notify); return "Notify reviewers."; }
+`,
+ );
+
+ const runtimeRoot = await prepareAgent(initialized.agentRoot);
+ const manifest = JSON.parse(
+ await readFile(resolve(runtimeRoot, ".opencomputer", "reactive.json"), "utf8"),
+ ) as { tools: string[] };
+ assert.ok(manifest.tools.includes("notify_reviewer"));
+ process.env.OPENCOMPUTER_OUTBOX_URL = "http://outbox.test/outboxes";
+ process.env.OPENCOMPUTER_OUTBOX_TOKEN = "runtime-token";
+ let request: { url: string; init?: RequestInit } | undefined;
+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ request = { url: String(url), init };
+ return Response.json({ id: "item-1", status: "pending", duplicate: false }, { status: 202 });
+ }) as typeof fetch;
+ const runtime = await import(
+ `${pathToFileURL(resolve(runtimeRoot, "opencomputer-agent.js")).href}?test=${crypto.randomUUID()}`
+ ) as { publishOutbox(id: string, input: unknown): Promise<unknown> };
+ await runtime.publishOutbox("review-requests", {
+ type: "pull-request.ready",
+ idempotencyKey: "example/repo#42",
+ content: { title: "Review requested" },
+ });
+ assert.equal(request?.url, "http://outbox.test/outboxes/review-requests/items");
+ assert.equal(new Headers(request?.init?.headers).get("authorization"), "Bearer runtime-token");
+ } finally {
+ globalThis.fetch = originalFetch;
+ if (originalUrl === undefined) delete process.env.OPENCOMPUTER_OUTBOX_URL;
+ else process.env.OPENCOMPUTER_OUTBOX_URL = originalUrl;
+ if (originalToken === undefined) delete process.env.OPENCOMPUTER_OUTBOX_TOKEN;
+ else process.env.OPENCOMPUTER_OUTBOX_TOKEN = originalToken;
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
test("the compiler rejects hard-coded sensitive connection headers", async () => {
const parent = await mkdtemp(
resolve(tmpdir(), "opencomputer-egress-secret-"),
diff --git a/cli/src/project.ts b/cli/src/project.ts
index 89534d45..9d12332b 100644
--- a/cli/src/project.ts
+++ b/cli/src/project.ts
@@ -46,6 +46,51 @@ export interface McpServerManifest {
connection?: string;
}
+export interface ChannelDestinationManifest {
+ type: "conversation";
+ visibility: "public" | "private";
+}
+
+export interface ChannelDefinitionManifest {
+ id: string;
+ type: "slack";
+ displayName?: string;
+ scopes: { bot: string[] };
+ events: Array<"app_mention" | "message.im">;
+ destinations: Record<string, ChannelDestinationManifest>;
+ routing: { whenAmbiguous: "ask" };
+}
+
+export interface ChannelRegistrationManifest {
+ agentId: string;
+ channelId: string;
+ triggers: Array<"mention" | "direct-message">;
+}
+
+export interface OutboxDefinitionManifest {
+ id: string;
+ channelId: string;
+ destination: string;
+}
+
+export interface OutboxRegistrationManifest {
+ agentId: string;
+ outboxId: string;
+}
+
+export interface ProjectResourceManifest {
+ version: 1;
+ channels: ChannelDefinitionManifest[];
+ channelRegistrations: ChannelRegistrationManifest[];
+ outboxes: OutboxDefinitionManifest[];
+ outboxRegistrations: OutboxRegistrationManifest[];
+}
+
+export interface BuiltProjectResources {
+ manifest: ProjectResourceManifest;
+ digest: string;
+}
+
export interface ProjectAgentSource {
localId: string;
root: string;
@@ -367,7 +412,7 @@ export default function Agent() {
deploy: "opencomputer deploy",
},
dependencies: {
- "@opencomputer/agent": "^0.4.0",
+ "@opencomputer/agent": "^0.5.0",
...(spa
? {
"@opencomputer/react": "^0.1.0",
@@ -799,6 +844,358 @@ function literalStringValue(
return expression.text;
}
+function literalStringArray(
+ expression: ts.Expression | undefined,
+ label: string,
+): string[] {
+ if (!expression || !ts.isArrayLiteralExpression(expression)) {
+ throw new Error(`${label} must be an array literal`);
+ }
+ return expression.elements.map((element) =>
+ literalStringValue(element, `${label} item`),
+ );
+}
+
+function staticPropertyName(name: ts.PropertyName, label: string): string {
+ if (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) return name.text;
+ throw new Error(`${label} must use static property names`);
+}
+
+function defaultExportCall(
+ source: string,
+ path: string,
+ helper: string,
+): ts.CallExpression {
+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
+ const statement = file.statements.find(
+ (candidate): candidate is ts.ExportAssignment =>
+ ts.isExportAssignment(candidate) &&
+ ts.isCallExpression(candidate.expression) &&
+ ts.isIdentifier(candidate.expression.expression) &&
+ candidate.expression.expression.text === helper,
+ );
+ if (!statement || !ts.isCallExpression(statement.expression)) {
+ throw new Error(`${path} must default-export ${helper}()`);
+ }
+ return statement.expression;
+}
+
+function importedResourceId(
+ source: string,
+ path: string,
+ localName: string,
+ label: string,
+): string {
+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
+ const declaration = file.statements.find(
+ (statement): statement is ts.ImportDeclaration =>
+ ts.isImportDeclaration(statement) &&
+ statement.importClause?.name?.text === localName,
+ );
+ if (!declaration || !ts.isStringLiteralLike(declaration.moduleSpecifier)) {
+ throw new Error(`${path} must default-import the ${label} definition`);
+ }
+ const module = basename(declaration.moduleSpecifier.text).replace(
+ /\.(?:js|ts)$/,
+ "",
+ );
+ if (!AGENT_ID_PATTERN.test(module)) {
+ throw new Error(`${path} imports an invalid ${label} resource name`);
+ }
+ return module;
+}
+
+function channelDefinition(
+ source: string,
+ path: string,
+): ChannelDefinitionManifest {
+ const call = defaultExportCall(source, path, "defineChannel");
+ const input = call.arguments[0];
+ if (!input || !ts.isObjectLiteralExpression(input)) {
+ throw new Error(`${path} defineChannel() requires an object literal`);
+ }
+ const id = literalStringValue(objectProperty(input, "id"), `${path} channel id`);
+ if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
+ throw new Error(`${path} filename must match its valid channel id`);
+ }
+ const type = literalStringValue(
+ objectProperty(input, "type"),
+ `${path} channel type`,
+ );
+ if (type !== "slack") throw new Error(`${path} supports only type "slack"`);
+ const scopesExpression = objectProperty(input, "scopes");
+ if (!scopesExpression || !ts.isObjectLiteralExpression(scopesExpression)) {
+ throw new Error(`${path} scopes must be an object literal`);
+ }
+ const scopes = [
+ ...new Set(
+ literalStringArray(
+ objectProperty(scopesExpression, "bot"),
+ `${path} Slack bot scopes`,
+ ),
+ ),
+ ].sort();
+ const events = [
+ ...new Set(
+ objectProperty(input, "events")
+ ? literalStringArray(objectProperty(input, "events"), `${path} events`)
+ : [],
+ ),
+ ].sort();
+ const allowedEvents = new Set(["app_mention", "message.im"]);
+ if (events.some((event) => !allowedEvents.has(event))) {
+ throw new Error(`${path} declares an unsupported Slack event`);
+ }
+ const requiredEventScopes: Record<string, string> = {
+ app_mention: "app_mentions:read",
+ "message.im": "im:history",
+ };
+ for (const event of events) {
+ const required = requiredEventScopes[event]!;
+ if (!scopes.includes(required)) {
+ throw new Error(`${path} event ${event} requires bot scope ${required}`);
+ }
+ }
+ const destinations: Record<string, ChannelDestinationManifest> = {};
+ const destinationsExpression = objectProperty(input, "destinations");
+ if (destinationsExpression) {
+ if (!ts.isObjectLiteralExpression(destinationsExpression)) {
+ throw new Error(`${path} destinations must be an object literal`);
+ }
+ for (const property of destinationsExpression.properties) {
+ if (!ts.isPropertyAssignment(property)) {
+ throw new Error(`${path} destinations cannot use spreads`);
+ }
+ const name = staticPropertyName(property.name, `${path} destination`);
+ if (!AGENT_ID_PATTERN.test(name)) {
+ throw new Error(`${path} has invalid destination ${name}`);
+ }
+ if (!ts.isObjectLiteralExpression(property.initializer)) {
+ throw new Error(`${path} destination ${name} must be an object literal`);
+ }
+ const destinationType = literalStringValue(
+ objectProperty(property.initializer, "type"),
+ `${path} destination ${name} type`,
+ );
+ const visibility = literalStringValue(
+ objectProperty(property.initializer, "visibility"),
+ `${path} destination ${name} visibility`,
+ );
+ if (
+ destinationType !== "conversation" ||
+ (visibility !== "public" && visibility !== "private")
+ ) {
+ throw new Error(`${path} destination ${name} is unsupported`);
+ }
+ const required = visibility === "private" ? "groups:read" : "channels:read";
+ if (!scopes.includes(required) || !scopes.includes("chat:write")) {
+ throw new Error(
+ `${path} destination ${name} requires ${required} and chat:write`,
+ );
+ }
+ destinations[name] = { type: "conversation", visibility };
+ }
+ }
+ const routingExpression = objectProperty(input, "routing");
+ if (routingExpression && !ts.isObjectLiteralExpression(routingExpression)) {
+ throw new Error(`${path} routing must be an object literal`);
+ }
+ if (routingExpression) {
+ const ambiguity = objectProperty(routingExpression, "whenAmbiguous");
+ if (ambiguity && literalStringValue(ambiguity, `${path} ambiguity policy`) !== "ask") {
+ throw new Error(`${path} supports only routing.whenAmbiguous = "ask"`);
+ }
+ }
+ const displayNameExpression = objectProperty(input, "displayName");
+ return {
+ id,
+ type: "slack",
+ ...(displayNameExpression
+ ? { displayName: literalStringValue(displayNameExpression, `${path} displayName`) }
+ : {}),
+ scopes: { bot: scopes },
+ events: events as ChannelDefinitionManifest["events"],
+ destinations,
+ routing: { whenAmbiguous: "ask" },
+ };
+}
+
+function channelRegistration(
+ source: string,
+ path: string,
+ agentId: string,
+ channels: ReadonlyMap<string, ChannelDefinitionManifest>,
+): ChannelRegistrationManifest {
+ const call = defaultExportCall(source, path, "registerChannel");
+ const channelExpression = call.arguments[0];
+ const input = call.arguments[1];
+ if (!channelExpression || !ts.isIdentifier(channelExpression)) {
+ throw new Error(`${path} must register an imported channel definition`);
+ }
+ if (!input || !ts.isObjectLiteralExpression(input)) {
+ throw new Error(`${path} registerChannel() requires an object literal`);
+ }
+ const channelId = importedResourceId(
+ source,
+ path,
+ channelExpression.text,
+ "channel",
+ );
+ const channel = channels.get(channelId);
+ if (!channel) throw new Error(`${path} references unknown channel ${channelId}`);
+ const triggers = [
+ ...new Set(
+ literalStringArray(objectProperty(input, "on"), `${path} triggers`),
+ ),
+ ].sort();
+ const triggerEvents: Record<string, string> = {
+ mention: "app_mention",
+ "direct-message": "message.im",
+ };
+ for (const trigger of triggers) {
+ const event = triggerEvents[trigger];
+ if (!event || !channel.events.includes(event as "app_mention" | "message.im")) {
+ throw new Error(`${path} trigger ${trigger} is not declared by ${channelId}`);
+ }
+ }
+ return {
+ agentId,
+ channelId,
+ triggers: triggers as ChannelRegistrationManifest["triggers"],
+ };
+}
+
+function outboxDefinition(
+ source: string,
+ path: string,
+ channels: ReadonlyMap<string, ChannelDefinitionManifest>,
+): OutboxDefinitionManifest {
+ const call = defaultExportCall(source, path, "defineOutbox");
+ const input = call.arguments[0];
+ if (!input || !ts.isObjectLiteralExpression(input)) {
+ throw new Error(`${path} defineOutbox() requires an object literal`);
+ }
+ const id = literalStringValue(objectProperty(input, "id"), `${path} outbox id`);
+ if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
+ throw new Error(`${path} filename must match its valid outbox id`);
+ }
+ const delivery = objectProperty(input, "delivery");
+ if (!delivery || !ts.isObjectLiteralExpression(delivery)) {
+ throw new Error(`${path} delivery must be an object literal`);
+ }
+ const channelExpression = objectProperty(delivery, "channel");
+ if (!channelExpression || !ts.isIdentifier(channelExpression)) {
+ throw new Error(`${path} delivery.channel must reference an imported channel`);
+ }
+ const channelId = importedResourceId(
+ source,
+ path,
+ channelExpression.text,
+ "channel",
+ );
+ const destination = literalStringValue(
+ objectProperty(delivery, "destination"),
+ `${path} destination`,
+ );
+ if (!channels.get(channelId)?.destinations[destination]) {
+ throw new Error(
+ `${path} references unknown destination ${destination} on ${channelId}`,
+ );
+ }
+ return { id, channelId, destination };
+}
+
+function outboxRegistration(
+ source: string,
+ path: string,
+ agentId: string,
+ outboxes: ReadonlyMap<string, OutboxDefinitionManifest>,
+): OutboxRegistrationManifest {
+ const call = defaultExportCall(source, path, "registerOutbox");
+ const expression = call.arguments[0];
+ if (!expression || !ts.isIdentifier(expression)) {
+ throw new Error(`${path} must register an imported outbox definition`);
+ }
+ const outboxId = importedResourceId(source, path, expression.text, "outbox");
+ if (!outboxes.has(outboxId)) {
+ throw new Error(`${path} references unknown outbox ${outboxId}`);
+ }
+ return { agentId, outboxId };
+}
+
+async function typescriptFiles(directory: string): Promise<string[]> {
+ if (!(await exists(directory))) return [];
+ return (await readdir(directory, { withFileTypes: true }))
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".ts"))
+ .map((entry) => resolve(directory, entry.name))
+ .sort();
+}
+
+export async function readProjectResources(
+ projectRoot: string,
+): Promise<BuiltProjectResources> {
+ const opencomputer = resolve(projectRoot, "opencomputer");
+ const channelDefinitions = await Promise.all(
+ (await typescriptFiles(resolve(opencomputer, "channels"))).map(async (path) =>
+ channelDefinition(await readFile(path, "utf8"), path),
+ ),
+ );
+ const channels = new Map(channelDefinitions.map((channel) => [channel.id, channel]));
+ if (channels.size !== channelDefinitions.length) {
+ throw new Error("Project channel IDs must be unique");
+ }
+ const outboxDefinitions = await Promise.all(
+ (await typescriptFiles(resolve(opencomputer, "outboxes"))).map(async (path) =>
+ outboxDefinition(await readFile(path, "utf8"), path, channels),
+ ),
+ );
+ const outboxes = new Map(outboxDefinitions.map((outbox) => [outbox.id, outbox]));
+ if (outboxes.size !== outboxDefinitions.length) {
+ throw new Error("Project outbox IDs must be unique");
+ }
+ const agents = await readProjectAgents(projectRoot);
+ const channelRegistrations: ChannelRegistrationManifest[] = [];
+ const outboxRegistrations: OutboxRegistrationManifest[] = [];
+ for (const agent of agents) {
+ for (const path of await typescriptFiles(resolve(agent.root, "channels"))) {
+ channelRegistrations.push(
+ channelRegistration(
+ await readFile(path, "utf8"),
+ path,
+ agent.localId,
+ channels,
+ ),
+ );
+ }
+ for (const path of await typescriptFiles(resolve(agent.root, "outboxes"))) {
+ outboxRegistrations.push(
+ outboxRegistration(
+ await readFile(path, "utf8"),
+ path,
+ agent.localId,
+ outboxes,
+ ),
+ );
+ }
+ }
+ const manifest: ProjectResourceManifest = {
+ version: 1,
+ channels: channelDefinitions.sort((left, right) => left.id.localeCompare(right.id)),
+ channelRegistrations: channelRegistrations.sort((left, right) =>
+ `${left.channelId}:${left.agentId}`.localeCompare(`${right.channelId}:${right.agentId}`),
+ ),
+ outboxes: outboxDefinitions.sort((left, right) => left.id.localeCompare(right.id)),
+ outboxRegistrations: outboxRegistrations.sort((left, right) =>
+ `${left.outboxId}:${left.agentId}`.localeCompare(`${right.outboxId}:${right.agentId}`),
+ ),
+ };
+ const serialized = JSON.stringify(manifest);
+ return {
+ manifest,
+ digest: createHash("sha256").update(serialized).digest("hex"),
+ };
+}
+
function secretNameFromExpression(expression: ts.Expression): string {
if (
!ts.isCallExpression(expression) ||
@@ -1094,6 +1491,23 @@ export const defineTool = (input) => {
if (input.output && typeof input.output !== "object") throw new Error("defineTool output must be a JSON Schema object");
return Object.freeze({ kind: "tool", version: 1, ...input, id: toolId, name: toolId });
};
+export const publishOutbox = async (outbox, input) => {
+ const outboxId = id(typeof outbox === "string" ? outbox : outbox.id, "publishOutbox");
+ const type = String(input.type).trim();
+ if (!/^[a-z0-9]+(?:[a-z0-9.-]*[a-z0-9])?$/.test(type)) throw new Error("Outbox event types must use lowercase dot notation");
+ const idempotencyKey = String(input.idempotencyKey).trim();
+ if (!idempotencyKey || idempotencyKey.length > 256) throw new Error("Outbox idempotency keys must contain 1 to 256 characters");
+ const base = globalThis.process?.env?.OPENCOMPUTER_OUTBOX_URL;
+ const token = globalThis.process?.env?.OPENCOMPUTER_OUTBOX_TOKEN;
+ if (!base || !token) throw new Error("OpenComputer outbox delivery is unavailable");
+ const response = await fetch(base.replace(/\\\/$/, "") + "/" + encodeURIComponent(outboxId) + "/items", {
+ method: "POST",
+ headers: { authorization: "Bearer " + token, "content-type": "application/json" },
+ body: JSON.stringify({ type, content: input.content, idempotencyKey }),
+ });
+ if (!response.ok) throw new Error("Outbox publish failed with status " + response.status);
+ return await response.json();
+};
export const useInput = () => hooks().useInput();
export const useCurrentInput = useInput;
export const useModel = (model) => hooks().useModel(model);
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index e39a4788..5a7bbac0 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -387,6 +387,102 @@ describe("managed agents proxy", () => {
});
});
+ it("lists one environment's outboxes without private delivery details", async () => {
+ const fetchSpy = vi.fn().mockResolvedValue(
+ Response.json({
+ agentId: "reviewer-agent",
+ environment: "development",
+ deploymentId: "reviewer-agent:digest",
+ accountId: "private_org",
+ outboxes: [
+ {
+ id: "review-requests",
+ channelId: "team-slack",
+ channelName: "Team Slack",
+ destination: "pull-request-reviews",
+ readiness: "ready",
+ targetDisplayName: "#pull-request-reviews",
+ connectionId: "private_connection",
+ items: [
+ {
+ id: "outbox_item",
+ outboxId: "review-requests",
+ eventType: "pull-request.ready",
+ sessionId: "session_public",
+ contentPreview: {
+ title: "Pull request ready",
+ body: "Please review it.",
+ url: "https://example.com/pull/42",
+ secret: "private",
+ },
+ status: "failed",
+ attemptCount: 1,
+ error: "Slack chat.postMessage failed: internal_detail",
+ createdAt: "2026-08-15T00:00:00.000Z",
+ updatedAt: "2026-08-15T00:01:00.000Z",
+ externalMessageId: "private_message",
+ },
+ ],
+ },
+ ],
+ }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/outboxes?agentId=reviewer-agent&environment=development",
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(fetchSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ href:
+ "https://managedagents.test/v1/outboxes?agentId=reviewer-agent&environment=development",
+ }),
+ expect.anything(),
+ );
+ expect(await response.json()).toEqual({
+ agentId: "reviewer-agent",
+ environment: "development",
+ deploymentId: "reviewer-agent:digest",
+ outboxes: [
+ {
+ id: "review-requests",
+ channelId: "team-slack",
+ channelName: "Team Slack",
+ destination: "pull-request-reviews",
+ readiness: "ready",
+ targetDisplayName: "#pull-request-reviews",
+ items: [
+ {
+ id: "outbox_item",
+ outboxId: "review-requests",
+ eventType: "pull-request.ready",
+ sessionId: "session_public",
+ contentPreview: {
+ title: "Pull request ready",
+ body: "Please review it.",
+ url: "https://example.com/pull/42",
+ },
+ status: "failed",
+ attemptCount: 1,
+ error: "Delivery failed.",
+ createdAt: "2026-08-15T00:00:00.000Z",
+ updatedAt: "2026-08-15T00:01:00.000Z",
+ },
+ ],
+ },
+ ],
+ });
+ });
+
it("returns a public per-agent Slack manifest", async () => {
const fetchSpy = vi.fn().mockResolvedValue(
Response.json({
@@ -459,6 +555,49 @@ describe("managed agents proxy", () => {
});
});
+ it("returns actionable Slack destination verification errors", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ {
+ error: {
+ code: "destination_verification_failed",
+ message: "Slack conversations.info failed: channel_not_found",
+ },
+ },
+ { status: 409 },
+ ),
+ ),
+ );
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/channels/slack/connections/channel_slack/destinations/pull-request-reviews",
+ {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ conversationId: "C012ABCDEF" }),
+ },
+ ),
+ {
+ 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(409);
+ expect(await response.json()).toEqual({
+ error: {
+ code: "destination_verification_failed",
+ message:
+ "Slack could not find that conversation. Check its ID and invite the app first.",
+ },
+ });
+ });
+
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 8b64c78b..6e451dc1 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -85,6 +85,8 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
/^[a-z][a-z0-9_]{0,63}$/.test(backendError.code)
? backendError.code
: "agent_request_failed";
+ const backendMessage =
+ typeof backendError?.message === "string" ? backendError.message : "";
let message = "The agent request could not be completed.";
if (upstream.status === 400) {
message =
@@ -96,7 +98,24 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
} else if (upstream.status === 404) {
message = "The requested agent resource was not found.";
} else if (upstream.status === 409) {
- message = "The agent request conflicts with the current state.";
+ if (backendCode === "destination_verification_failed") {
+ if (backendMessage === "Invite the Slack app to this conversation first") {
+ message = backendMessage;
+ } else if (backendMessage === "Slack conversation is archived") {
+ message = "That Slack conversation is archived.";
+ } else if (backendMessage.includes("channel_not_found")) {
+ message =
+ "Slack could not find that conversation. Check its ID and invite the app first.";
+ } else if (backendMessage.includes("missing_scope")) {
+ message =
+ "The Slack app is missing a required permission. Reinstall it from the current manifest.";
+ } else {
+ message =
+ "Slack could not verify that conversation. Check its ID and app membership.";
+ }
+ } else {
+ message = "The agent request conflicts with the current state.";
+ }
} else if (upstream.status === 429) {
message = "Too many agent requests. Try again shortly.";
} else if (upstream.status >= 500) {
@@ -132,6 +151,9 @@ function publicDeployment(value: unknown): Record<string, unknown> {
channels: strings(deployment.channels),
connections: strings(deployment.connections),
createdAt: deployment.createdAt,
+ ...(deployment.projectDeployment
+ ? { projectDeployment: stripPrivateValues(deployment.projectDeployment) }
+ : {}),
};
}
@@ -197,6 +219,7 @@ function publicChannel(value: unknown): Record<string, unknown> {
return {
id: channel.id,
channel: "slack",
+ channelId: channel.channelId,
agentId: channel.agentId,
alias: channel.alias,
appName: channel.appName,
@@ -207,6 +230,46 @@ function publicChannel(value: unknown): Record<string, unknown> {
status: channel.status,
createdAt: channel.createdAt,
updatedAt: channel.updatedAt,
+ ...(Array.isArray(channel.destinations)
+ ? { destinations: channel.destinations.map(stripPrivateValues) }
+ : {}),
+ };
+}
+
+function publicOutboxItem(value: unknown): Record<string, unknown> {
+ const item = record(value) ?? {};
+ const content = record(item.contentPreview) ?? {};
+ return {
+ id: item.id,
+ outboxId: item.outboxId,
+ eventType: item.eventType,
+ sessionId: item.sessionId,
+ contentPreview: {
+ ...(typeof content.title === "string" ? { title: content.title } : {}),
+ ...(typeof content.body === "string" ? { body: content.body } : {}),
+ ...(typeof content.url === "string" ? { url: content.url } : {}),
+ },
+ status: item.status,
+ destination: item.destination,
+ attemptCount: item.attemptCount,
+ ...(item.error ? { error: "Delivery failed." } : {}),
+ createdAt: item.createdAt,
+ updatedAt: item.updatedAt,
+ };
+}
+
+function publicOutbox(value: unknown): Record<string, unknown> {
+ const outbox = record(value) ?? {};
+ return {
+ id: outbox.id,
+ channelId: outbox.channelId,
+ channelName: outbox.channelName,
+ destination: outbox.destination,
+ readiness: outbox.readiness,
+ targetDisplayName: outbox.targetDisplayName,
+ items: Array.isArray(outbox.items)
+ ? outbox.items.map(publicOutboxItem)
+ : [],
};
}
@@ -363,6 +426,16 @@ function publicSuccessBody(
: [],
};
}
+ if (method === "GET" && suffix === "/outboxes") {
+ return {
+ agentId: body.agentId,
+ environment: body.environment,
+ deploymentId: body.deploymentId,
+ outboxes: Array.isArray(body.outboxes)
+ ? body.outboxes.map(publicOutbox)
+ : [],
+ };
+ }
if (method === "POST" && suffix === "/channels/slack/connections") {
return {
connection: publicChannel(body.connection),
@@ -564,6 +637,9 @@ async function deploySourceAgent(
httpConnections: Array.isArray(body.httpConnections)
? body.httpConnections
: [],
+ ...(body.projectDeployment && typeof body.projectDeployment === "object"
+ ? { projectDeployment: body.projectDeployment }
+ : {}),
artifact,
}),
redirect: "manual",
@@ -595,6 +671,7 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
}
if (method === "GET" && suffix === "/deployments") return true;
if (method === "GET" && /^\/deployments\/[^/]+$/.test(suffix)) return true;
+ if (method === "GET" && suffix === "/outboxes") return true;
if (
(method === "GET" &&
(/^\/connections(?:\/.*)?$/.test(suffix) ||
diff --git a/create-start/package.json b/create-start/package.json
index be923e45..51328794 100644
--- a/create-start/package.json
+++ b/create-start/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/create-start",
- "version": "0.5.2",
+ "version": "0.5.3",
"description": "Create a hello-world OpenComputer agent application.",
"type": "module",
"bin": {
@@ -18,7 +18,7 @@
"node": ">=22.0.0"
},
"dependencies": {
- "@opencomputer/cli": "0.5.2"
+ "@opencomputer/cli": "0.5.3"
},
"publishConfig": {
"access": "public"
diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.ts
index 985e772e..9afc0f23 100644
--- a/web/src/components/app-shell-nav.ts
+++ b/web/src/components/app-shell-nav.ts
@@ -10,6 +10,7 @@ import {
Package,
Radio,
Rocket,
+ Send,
Webhook,
type LucideIcon,
} from 'lucide-react'
@@ -65,6 +66,11 @@ export function managedAgentsNav(options: {
label: 'Channels',
icon: Radio,
},
+ {
+ to: `${projectPath}/outboxes`,
+ label: 'Outboxes',
+ icon: Send,
+ },
{
to: `${projectPath}/schedules`,
label: 'Schedules',
diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.ts
index 274b06d1..cdb899de 100644
--- a/web/src/components/app-shell.test.ts
+++ b/web/src/components/app-shell.test.ts
@@ -21,6 +21,7 @@ describe('managed agents navigation', () => {
'Deployments',
'Sessions',
'Channels',
+ 'Outboxes',
'Schedules',
'Secrets',
'Debug playground',
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index 9bd52e7e..b2e45819 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -66,12 +66,14 @@ import {
} from './session-history'
import { ManagedProjectSecrets } from './Secrets'
import { ManagedSlackWizard } from './SlackWizard'
+import { ManagedAgentOutboxes } from './Outboxes'
type DetailTab =
| 'playground'
| 'deployments'
| 'sessions'
| 'channels'
+ | 'outboxes'
| 'schedules'
| 'secrets'
@@ -571,6 +573,7 @@ export default function ManagedAgentDetail({
'deployments',
'sessions',
'channels',
+ 'outboxes',
'schedules',
'secrets',
])
@@ -660,12 +663,15 @@ export default function ManagedAgentDetail({
search: playgroundSessionSearch(location.search, sessionId),
})
}
- const activeAliasChannel = (channels.data ?? []).find(
+ const activeAliasChannels = (channels.data ?? []).filter(
(channel) =>
channel.agentId === agentId &&
channel.alias === (activeDeployment.data?.alias ?? agent?.activeAlias) &&
channel.status !== 'disconnected',
)
+ const activeAliasChannel = activeAliasChannels[0]
+ const declaredChannels =
+ activeDeployment.data?.projectDeployment?.resources.channels ?? []
const sessionColumns: Column<ManagedAgentSession>[] = [
{
@@ -735,6 +741,7 @@ export default function ManagedAgentDetail({
{ id: 'deployments', label: 'Deployments' },
{ id: 'sessions', label: 'Sessions' },
{ id: 'channels', label: 'Channels' },
+ ...(project ? ([{ id: 'outboxes', label: 'Outboxes' }] as const) : []),
...(project ? ([{ id: 'schedules', label: 'Schedules' }] as const) : []),
...(project ? ([{ id: 'secrets', label: 'Secrets' }] as const) : []),
]
@@ -829,7 +836,12 @@ export default function ManagedAgentDetail({
<div className="text-muted-foreground hidden gap-5 pb-3 text-xs lg:flex">
<span>{agent?.deploymentCount ?? 0} deployments</span>
<span>
- {activeAliasChannel?.status === 'connected' ? 1 : 0} channels
+ {
+ activeAliasChannels.filter(
+ (channel) => channel.status === 'connected',
+ ).length
+ }{' '}
+ channels
</span>
</div>
</div>
@@ -1057,12 +1069,31 @@ export default function ManagedAgentDetail({
</div>
</PanelHeader>
{agent && activeDeployment.data ? (
- <ManagedSlackWizard
- agentId={agent.id}
- alias={activeDeployment.data.alias}
- agentName={displayManagedAgentName(agent)}
- connection={activeAliasChannel}
- />
+ declaredChannels.length ? (
+ declaredChannels.map((declaredChannel) => (
+ <ManagedSlackWizard
+ key={declaredChannel.id}
+ agentId={agent.id}
+ alias={activeDeployment.data.alias}
+ agentName={displayManagedAgentName(agent)}
+ channelName={
+ declaredChannel.displayName ?? declaredChannel.id
+ }
+ connection={activeAliasChannels.find(
+ (channel) => channel.channelId === declaredChannel.id,
+ )}
+ channelId={declaredChannel.id}
+ destinations={Object.keys(declaredChannel.destinations)}
+ />
+ ))
+ ) : (
+ <ManagedSlackWizard
+ agentId={agent.id}
+ alias={activeDeployment.data.alias}
+ agentName={displayManagedAgentName(agent)}
+ connection={activeAliasChannel}
+ />
+ )
) : (
<PanelContent className="text-muted-foreground text-sm">
Loading channels…
@@ -1071,6 +1102,15 @@ export default function ManagedAgentDetail({
</Panel>
) : null}
+ {activeTab === 'outboxes' && project && agent ? (
+ <ManagedAgentOutboxes
+ projectId={project.project.id}
+ agentId={agent.id}
+ environment={environment}
+ deployed={Boolean(projectEnvironment?.activeDeploymentId)}
+ />
+ ) : null}
+
{activeTab === 'schedules' && project ? (
<ProjectResourcePanel
title="Schedules"
diff --git a/web/src/managed-agents/Outboxes.test.ts b/web/src/managed-agents/Outboxes.test.ts
new file mode 100644
index 00000000..a09ffd99
--- /dev/null
+++ b/web/src/managed-agents/Outboxes.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest'
+import type { ManagedAgentOutbox } from './api'
+import { flattenOutboxDeliveries } from './Outboxes'
+
+function route(
+ id: string,
+ items: ManagedAgentOutbox['items'],
+): ManagedAgentOutbox {
+ return {
+ id,
+ channelId: 'team-slack',
+ channelName: 'Team Slack',
+ destination: 'pull-request-reviews',
+ readiness: 'ready',
+ items,
+ }
+}
+
+function item(
+ id: string,
+ createdAt: string,
+): ManagedAgentOutbox['items'][number] {
+ return {
+ id,
+ outboxId: 'reviews',
+ eventType: 'pull_request.created',
+ contentPreview: { title: id },
+ status: 'delivered',
+ attemptCount: 1,
+ createdAt,
+ updatedAt: createdAt,
+ }
+}
+
+describe('flattenOutboxDeliveries', () => {
+ it('orders publications across routes by newest first', () => {
+ const deliveries = flattenOutboxDeliveries([
+ route('reviews', [item('older', '2026-08-15T10:00:00.000Z')]),
+ route('personal', [item('newer', '2026-08-15T11:00:00.000Z')]),
+ ])
+
+ expect(deliveries.map(({ item: delivery }) => delivery.id)).toEqual([
+ 'newer',
+ 'older',
+ ])
+ })
+})
diff --git a/web/src/managed-agents/Outboxes.tsx b/web/src/managed-agents/Outboxes.tsx
new file mode 100644
index 00000000..3f6cfcbd
--- /dev/null
+++ b/web/src/managed-agents/Outboxes.tsx
@@ -0,0 +1,418 @@
+import { useState, type ReactNode } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { Send } from 'lucide-react'
+import { Link } from 'react-router-dom'
+import { EmptyState } from '@/components/empty-state'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { ResourceTable, type Column } from '@/components/resource-table'
+import { StatusBadge } from '@/components/status-badge'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { getManagedAgentOutboxes, type ManagedAgentOutbox } from './api'
+import { projectContextSearch } from './project-context'
+
+function formatDate(value: string) {
+ return new Date(value).toLocaleString()
+}
+
+function safeExternalUrl(value?: string) {
+ if (!value) return undefined
+ try {
+ const url = new URL(value)
+ return url.protocol === 'https:' || url.protocol === 'http:'
+ ? url.toString()
+ : undefined
+ } catch {
+ return undefined
+ }
+}
+
+function readinessMeta(readiness: ManagedAgentOutbox['readiness']) {
+ return readiness === 'ready'
+ ? { status: 'ready', label: 'Ready' }
+ : readiness === 'channel_not_connected'
+ ? { status: 'unavailable', label: 'Connect channel' }
+ : { status: 'unavailable', label: 'Map destination' }
+}
+
+export type OutboxDelivery = {
+ outbox: ManagedAgentOutbox
+ item: ManagedAgentOutbox['items'][number]
+}
+
+export function flattenOutboxDeliveries(outboxes: ManagedAgentOutbox[]) {
+ return outboxes
+ .flatMap((outbox) => outbox.items.map((item) => ({ outbox, item })))
+ .sort((left, right) =>
+ right.item.createdAt.localeCompare(left.item.createdAt),
+ )
+}
+
+function DetailField({
+ label,
+ children,
+}: {
+ label: string
+ children: ReactNode
+}) {
+ return (
+ <div>
+ <dt className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
+ {label}
+ </dt>
+ <dd className="mt-1 text-sm">{children}</dd>
+ </div>
+ )
+}
+
+export function ManagedAgentOutboxes({
+ projectId,
+ agentId,
+ environment,
+ deployed,
+}: {
+ projectId: string
+ agentId: string
+ environment: 'development' | 'production'
+ deployed: boolean
+}) {
+ const [selectedItemId, setSelectedItemId] = useState<string>()
+ const outboxes = useQuery({
+ queryKey: ['managed-agent-outboxes', agentId, environment],
+ queryFn: () => getManagedAgentOutboxes(agentId, environment),
+ enabled: deployed,
+ refetchInterval: 3_000,
+ })
+
+ if (!deployed) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={Send}
+ title={`No active ${environment} deployment`}
+ description="Deploy this project to the environment before publishing outbox items."
+ />
+ </Panel>
+ )
+ }
+
+ if (outboxes.isError) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={Send}
+ title="Outboxes are temporarily unavailable"
+ description="Try loading this environment again."
+ />
+ </Panel>
+ )
+ }
+
+ if (outboxes.isLoading) {
+ return (
+ <Panel>
+ <PanelContent className="text-muted-foreground py-8 text-sm">
+ Loading outboxes…
+ </PanelContent>
+ </Panel>
+ )
+ }
+
+ if (!outboxes.data?.outboxes.length) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={Send}
+ title={`No ${environment} outboxes`}
+ description="Register an outbox for this agent and deploy it to this environment."
+ />
+ </Panel>
+ )
+ }
+
+ const routes = outboxes.data.outboxes
+ const deliveries = flattenOutboxDeliveries(routes)
+ const selected = deliveries.find(({ item }) => item.id === selectedItemId)
+
+ const routeColumns: Column<ManagedAgentOutbox>[] = [
+ {
+ key: 'outbox',
+ header: 'Outbox',
+ cell: (outbox) => (
+ <span className="text-sm font-medium">{outbox.id}</span>
+ ),
+ },
+ {
+ key: 'route',
+ header: 'Route',
+ cell: (outbox) => (
+ <span className="text-muted-foreground text-xs">
+ {outbox.channelName} → {outbox.destination}
+ {outbox.targetDisplayName ? ` → ${outbox.targetDisplayName}` : ''}
+ </span>
+ ),
+ },
+ {
+ key: 'readiness',
+ header: 'Readiness',
+ align: 'right',
+ cell: (outbox) => {
+ const readiness = readinessMeta(outbox.readiness)
+ return <StatusBadge status={readiness.status} label={readiness.label} />
+ },
+ },
+ ]
+
+ const deliveryColumns: Column<OutboxDelivery>[] = [
+ {
+ key: 'message',
+ header: 'Message',
+ cell: ({ item }) => (
+ <div className="max-w-80">
+ <p className="truncate text-sm font-medium">
+ {item.contentPreview.title || item.contentPreview.body || 'Message'}
+ </p>
+ {item.contentPreview.title && item.contentPreview.body ? (
+ <p className="text-muted-foreground mt-1 truncate text-xs">
+ {item.contentPreview.body}
+ </p>
+ ) : null}
+ </div>
+ ),
+ },
+ {
+ key: 'route',
+ header: 'Route',
+ cell: ({ outbox }) => {
+ const readiness = readinessMeta(outbox.readiness)
+ return (
+ <div className="space-y-1">
+ <p className="text-xs font-medium">{outbox.id}</p>
+ <StatusBadge status={readiness.status} label={readiness.label} />
+ </div>
+ )
+ },
+ },
+ {
+ key: 'session',
+ header: 'Session',
+ cell: ({ item }) =>
+ item.sessionId ? (
+ <Link
+ className="font-mono text-xs underline underline-offset-2"
+ onClick={(event) => event.stopPropagation()}
+ to={{
+ pathname: `/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(item.sessionId)}`,
+ search: projectContextSearch('', agentId, environment),
+ }}
+ >
+ {item.sessionId.slice(0, 12)}…
+ </Link>
+ ) : (
+ <span className="text-muted-foreground text-xs">Not recorded</span>
+ ),
+ },
+ {
+ key: 'delivery',
+ header: 'Delivery',
+ cell: ({ item }) => (
+ <div className="space-y-1">
+ <StatusBadge status={item.status} />
+ <p className="text-muted-foreground text-[11px]">
+ {item.attemptCount}{' '}
+ {item.attemptCount === 1 ? 'attempt' : 'attempts'}
+ </p>
+ </div>
+ ),
+ },
+ {
+ key: 'published',
+ header: 'Published',
+ align: 'right',
+ cell: ({ item }) => (
+ <time
+ className="text-muted-foreground text-xs"
+ dateTime={item.createdAt}
+ >
+ {formatDate(item.createdAt)}
+ </time>
+ ),
+ },
+ ]
+
+ const selectedUrl = safeExternalUrl(selected?.item.contentPreview.url)
+ const selectedReadiness = selected
+ ? readinessMeta(selected.outbox.readiness)
+ : undefined
+
+ return (
+ <div className="space-y-4">
+ <Panel className="overflow-hidden">
+ <PanelHeader className="py-3">
+ <div>
+ <PanelTitle>Configured routes</PanelTitle>
+ <PanelDescription className="mt-1">
+ Delivery readiness for this {environment} environment.
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ <ResourceTable
+ columns={routeColumns}
+ rows={routes}
+ rowKey={(outbox) => outbox.id}
+ />
+ </Panel>
+
+ <Panel className="overflow-hidden">
+ <PanelHeader>
+ <div>
+ <PanelTitle>Publications</PanelTitle>
+ <PanelDescription className="mt-1">
+ Most recent deliveries across all outboxes in this environment.
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ <ResourceTable
+ columns={deliveryColumns}
+ rows={deliveries}
+ rowKey={({ item }) => item.id}
+ onRowClick={({ item }) => setSelectedItemId(item.id)}
+ empty={
+ <EmptyState
+ title="No publications in this environment"
+ description="New outbox items will appear here automatically."
+ className="py-9"
+ />
+ }
+ />
+ </Panel>
+
+ <Dialog
+ open={Boolean(selected)}
+ onOpenChange={(open) => {
+ if (!open) setSelectedItemId(undefined)
+ }}
+ >
+ <DialogContent className="sm:max-w-2xl">
+ {selected ? (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ {selected.item.contentPreview.title || 'Outbox publication'}
+ </DialogTitle>
+ <DialogDescription>
+ Delivery and provenance for this publication.
+ </DialogDescription>
+ </DialogHeader>
+
+ {selected.item.contentPreview.body ? (
+ <p className="bg-muted/40 max-h-56 overflow-y-auto rounded-md border p-3 text-sm whitespace-pre-wrap">
+ {selected.item.contentPreview.body}
+ </p>
+ ) : null}
+ {selectedUrl ? (
+ <a
+ href={selectedUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="text-sm break-all underline underline-offset-2"
+ >
+ {selectedUrl}
+ </a>
+ ) : null}
+
+ <dl className="grid grid-cols-1 gap-x-6 gap-y-4 border-t pt-4 sm:grid-cols-2">
+ <DetailField label="Delivery">
+ <span className="inline-flex items-center gap-2">
+ <StatusBadge status={selected.item.status} />
+ <span className="text-muted-foreground text-xs">
+ {selected.item.attemptCount}{' '}
+ {selected.item.attemptCount === 1
+ ? 'attempt'
+ : 'attempts'}
+ </span>
+ </span>
+ </DetailField>
+ <DetailField label="Route readiness">
+ <StatusBadge
+ status={selectedReadiness!.status}
+ label={selectedReadiness!.label}
+ />
+ </DetailField>
+ <DetailField label="Outbox">
+ <span className="font-mono text-xs">
+ {selected.outbox.id}
+ </span>
+ </DetailField>
+ <DetailField label="Event">
+ <span className="font-mono text-xs">
+ {selected.item.eventType}
+ </span>
+ </DetailField>
+ <DetailField label="Route">
+ <span className="text-xs">
+ {selected.outbox.channelName} ({selected.outbox.channelId})
+ → {selected.outbox.destination}
+ {selected.outbox.targetDisplayName
+ ? ` → ${selected.outbox.targetDisplayName}`
+ : ''}
+ </span>
+ </DetailField>
+ <DetailField label="Session">
+ {selected.item.sessionId ? (
+ <Link
+ className="font-mono text-xs break-all underline underline-offset-2"
+ to={{
+ pathname: `/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(selected.item.sessionId)}`,
+ search: projectContextSearch('', agentId, environment),
+ }}
+ >
+ {selected.item.sessionId}
+ </Link>
+ ) : (
+ <span className="text-muted-foreground text-xs">
+ Not recorded for this historical item
+ </span>
+ )}
+ </DetailField>
+ <DetailField label="Published">
+ <time dateTime={selected.item.createdAt}>
+ {formatDate(selected.item.createdAt)}
+ </time>
+ </DetailField>
+ <DetailField label="Last updated">
+ <time dateTime={selected.item.updatedAt}>
+ {formatDate(selected.item.updatedAt)}
+ </time>
+ </DetailField>
+ <DetailField label="Publication ID">
+ <span className="font-mono text-xs break-all">
+ {selected.item.id}
+ </span>
+ </DetailField>
+ {selected.item.error ? (
+ <DetailField label="Failure">
+ <span className="text-status-error text-xs">
+ {selected.item.error}
+ </span>
+ </DetailField>
+ ) : null}
+ </dl>
+ </>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ </div>
+ )
+}
diff --git a/web/src/managed-agents/SlackWizard.tsx b/web/src/managed-agents/SlackWizard.tsx
index ad10a2e0..8aca90ff 100644
--- a/web/src/managed-agents/SlackWizard.tsx
+++ b/web/src/managed-agents/SlackWizard.tsx
@@ -20,11 +20,12 @@ import {
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { StatusBadge } from '@/components/status-badge'
-import { notifyError } from '@/lib/errors'
+import { notifyError, notifySuccess } from '@/lib/errors'
import { useTransientFlag } from '@/lib/use-transient-flag'
import { cn } from '@/lib/utils'
import {
completeManagedAgentSlack,
+ bindManagedAgentSlackDestination,
disconnectManagedAgentSlack,
startManagedAgentSlack,
type ManagedAgentChannel,
@@ -35,6 +36,67 @@ type Step = 'create' | 'details' | 'install' | 'done'
const CREATE_STEPS = ['Create app', 'Details', 'Install', 'Verify']
const EDIT_STEPS = ['Credentials', 'Token', 'Verify']
+function SlackDestinationSetup({
+ connection,
+ destination,
+ onSaved,
+}: {
+ connection: ManagedAgentChannel
+ destination: string
+ onSaved: () => void
+}) {
+ const existing = connection.destinations.find(
+ (binding) => binding.name === destination,
+ )
+ const [conversationId, setConversationId] = useState(
+ existing?.conversationId ?? '',
+ )
+ const bind = useMutation({
+ mutationFn: () =>
+ bindManagedAgentSlackDestination(
+ connection.id,
+ destination,
+ conversationId.trim(),
+ ),
+ onSuccess: (binding) => {
+ notifySuccess(
+ `${destination} mapped to ${binding.displayName}.`,
+ 'Slack notifications can now use this destination.',
+ )
+ onSaved()
+ },
+ onError: (error) =>
+ notifyError("Couldn't verify that Slack conversation.", error),
+ })
+ const confirmed = bind.data ?? existing
+ return (
+ <div className="space-y-2 border-t px-5 py-4">
+ <p className="text-sm font-medium">{destination}</p>
+ <p className="text-muted-foreground text-xs">
+ {confirmed
+ ? `Mapped to ${confirmed.displayName}`
+ : 'Invite the app to a Slack conversation, then paste its ID.'}
+ </p>
+ <div className="flex gap-2">
+ <Input
+ aria-label={`${destination} Slack conversation ID`}
+ value={conversationId}
+ onChange={(event) => setConversationId(event.target.value)}
+ placeholder="C012ABCDEF"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!conversationId.trim() || bind.isPending}
+ onClick={() => bind.mutate()}
+ >
+ {bind.isPending ? 'Verifying…' : confirmed ? 'Update' : 'Verify'}
+ </Button>
+ </div>
+ </div>
+ )
+}
+
function WizardSteps({ current, steps }: { current: number; steps: string[] }) {
return (
<ol className="flex items-center gap-2 pt-2">
@@ -73,12 +135,18 @@ export function ManagedSlackWizard({
agentId,
alias,
agentName,
+ channelName,
connection,
+ channelId,
+ destinations = [],
}: {
agentId: string
alias: string
agentName: string
+ channelName?: string
connection?: ManagedAgentChannel
+ channelId?: string
+ destinations?: string[]
}) {
const queryClient = useQueryClient()
const [open, setOpen] = useState(false)
@@ -98,7 +166,12 @@ export function ManagedSlackWizard({
const start = useMutation({
mutationFn: () =>
- startManagedAgentSlack(`${agentId}@${alias}`, appName.trim(), false),
+ startManagedAgentSlack(
+ `${agentId}@${alias}`,
+ appName.trim(),
+ false,
+ channelId,
+ ),
onSuccess: (result) => {
setManifest(result)
void invalidate()
@@ -202,13 +275,19 @@ export function ManagedSlackWizard({
</span>
<div className="min-w-0">
<p className="text-sm font-medium">
- {connection?.appName || agentName}
+ {channelName || connection?.appName || agentName}
</p>
<p className="text-muted-foreground truncate text-xs">
+ {channelId ? `${channelId} · ` : ''}
{connection?.status === 'connected'
? `Slack · ${connection.teamName || 'Connected workspace'}`
: `Connect a dedicated Slack app to @${alias}`}
</p>
+ {destinations.length ? (
+ <p className="text-muted-foreground mt-1 truncate text-xs">
+ Destinations: {destinations.join(', ')}
+ </p>
+ ) : null}
{connection?.status === 'connected' ? (
<p className="text-muted-foreground mt-1 text-xs">
{connection.verificationError
@@ -246,6 +325,17 @@ export function ManagedSlackWizard({
</div>
</div>
+ {connection?.status === 'connected'
+ ? destinations.map((destination) => (
+ <SlackDestinationSetup
+ key={destination}
+ connection={connection}
+ destination={destination}
+ onSaved={() => void invalidate()}
+ />
+ ))
+ : null}
+
<Dialog
open={open}
onOpenChange={(next) => {
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index ea2ab99f..1e585f09 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -18,6 +18,29 @@ const deploymentSchema = z.object({
channels: z.array(z.string()),
connections: z.array(z.string()),
createdAt: z.string(),
+ projectDeployment: z
+ .object({
+ id: z.string(),
+ digest: z.string(),
+ localAgentId: z.string(),
+ resources: z.object({
+ channels: z.array(
+ z.object({
+ id: z.string(),
+ type: z.literal('slack'),
+ displayName: z.string().optional(),
+ destinations: z.record(
+ z.string(),
+ z.object({
+ type: z.literal('conversation'),
+ visibility: z.enum(['public', 'private']),
+ }),
+ ),
+ }),
+ ),
+ }),
+ })
+ .optional(),
})
const deploymentsResponseSchema = z.object({
@@ -76,6 +99,7 @@ const connectionSchema = z.object({
const channelSchema = z.object({
id: z.string(),
channel: z.string(),
+ channelId: z.string().optional().default('slack'),
agentId: z.string(),
alias: z.string(),
appName: z.string().nullish(),
@@ -88,6 +112,17 @@ const channelSchema = z.object({
status: z.string(),
createdAt: z.string(),
updatedAt: z.string(),
+ destinations: z
+ .array(
+ z.object({
+ name: z.string(),
+ conversationId: z.string(),
+ displayName: z.string(),
+ verifiedAt: z.string(),
+ }),
+ )
+ .optional()
+ .default([]),
})
const connectionsResponseSchema = z.object({
@@ -108,6 +143,45 @@ const channelsResponseSchema = z.object({
channels: z.array(channelSchema),
})
+const outboxItemSchema = z.object({
+ id: z.string(),
+ outboxId: z.string(),
+ eventType: z.string(),
+ sessionId: z.string().optional(),
+ contentPreview: z.object({
+ title: z.string().optional(),
+ body: z.string().optional(),
+ url: z.string().optional(),
+ }),
+ status: z.string(),
+ destination: z.string().optional(),
+ attemptCount: z.number(),
+ error: z.string().optional(),
+ createdAt: z.string(),
+ updatedAt: z.string(),
+})
+
+const outboxSchema = z.object({
+ id: z.string(),
+ channelId: z.string(),
+ channelName: z.string(),
+ destination: z.string(),
+ readiness: z.enum([
+ 'ready',
+ 'channel_not_connected',
+ 'destination_not_bound',
+ ]),
+ targetDisplayName: z.string().optional(),
+ items: z.array(outboxItemSchema),
+})
+
+const outboxesResponseSchema = z.object({
+ agentId: z.string(),
+ environment: z.enum(['development', 'production']),
+ deploymentId: z.string(),
+ outboxes: z.array(outboxSchema),
+})
+
const slackManifestResponseSchema = z.object({
connection: channelSchema,
manifest: z.record(z.string(), z.unknown()),
@@ -207,6 +281,8 @@ export type ManagedAgentRenderDebug = z.infer<typeof renderDebugSchema>
export type ManagedAgentSession = z.infer<typeof sessionSchema>
export type ManagedAgentConnection = z.infer<typeof connectionSchema>
export type ManagedAgentChannel = z.infer<typeof channelSchema>
+export type ManagedAgentOutbox = z.infer<typeof outboxSchema>
+export type ManagedAgentOutboxItem = z.infer<typeof outboxItemSchema>
export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>
export type ManagedProjectSecret = z.infer<typeof secretSchema>
@@ -347,21 +423,52 @@ export async function getManagedAgentChannels() {
).channels
}
+export async function getManagedAgentOutboxes(
+ agentId: string,
+ environment: 'development' | 'production',
+) {
+ const query = new URLSearchParams({ agentId, environment })
+ return apiFetch(
+ `/managed-agents/outboxes?${query.toString()}`,
+ undefined,
+ outboxesResponseSchema,
+ )
+}
+
export async function startManagedAgentSlack(
agentId: string,
name: string,
reconnect = false,
+ channelId?: string,
) {
return apiFetch(
'/managed-agents/channels/slack/connections',
{
method: 'POST',
- body: JSON.stringify({ agentId, name, reconnect }),
+ body: JSON.stringify({ agentId, name, reconnect, channelId }),
},
slackManifestResponseSchema,
)
}
+export async function bindManagedAgentSlackDestination(
+ connectionId: string,
+ destination: string,
+ conversationId: string,
+) {
+ return apiFetch(
+ `/managed-agents/channels/slack/connections/${encodeURIComponent(connectionId)}/destinations/${encodeURIComponent(destination)}`,
+ { method: 'PUT', body: JSON.stringify({ conversationId }) },
+ z.object({
+ connectionId: z.string(),
+ destination: z.string(),
+ conversationId: z.string(),
+ displayName: z.string(),
+ verifiedAt: z.string(),
+ }),
+ )
+}
+
export async function completeManagedAgentSlack(
connectionId: string,
input: { appId: string; signingSecret: string; botToken: string },