Skip to content

An open-source, faster Devin alternative

TypeScript

channels: make the provider a variant instead of assuming Slack

Brian Reardon8c52c5809d18
diff --git a/agent/src/index.ts b/agent/src/index.ts
index cd4e9b30..89d49bdf 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -88,31 +88,82 @@ export interface McpServerDefinition extends ResourceReference {
readonly connection?: ConnectionReference;
}
+/**
+ * A channel is a conversation the agent takes part in, keyed by an external
+ * participant. What differs between providers is transport, addressing, and
+ * authentication; what does not differ is that an inbound message continues the
+ * conversation it belongs to. Agents see the second part and never the first.
+ */
+export type ChannelProvider = "slack" | "sms" | "email";
+
export type SlackChannelEvent = "app_mention" | "message.im";
-export type ChannelTrigger = "mention" | "direct-message";
+/** Providers without a mention/DM distinction have exactly one inbound event. */
+export type MessageChannelEvent = "message.inbound";
+export type ChannelEvent = SlackChannelEvent | MessageChannelEvent;
+
+export type ChannelTrigger = "mention" | "direct-message" | "message";
-export interface ChannelDestinationDefinition {
+export interface ConversationDestination {
readonly type: "conversation";
readonly visibility: "public" | "private";
}
-export interface SlackChannelDefinition extends ResourceReference {
+/** Reply on the conversation the message arrived on. */
+export interface ReplyDestination {
+ readonly type: "reply";
+}
+
+export type ChannelDestinationDefinition =
+ | ConversationDestination
+ | ReplyDestination;
+
+interface ChannelDefinitionBase 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";
};
+ /**
+ * Agent runtime is billed by wall-clock time, and a conversation spends most
+ * of its life waiting for a human. Suspend the runtime this long after the
+ * last message; an inbound message resumes it. Without this a channel-backed
+ * conversation bills for the hours nobody is typing.
+ */
+ readonly idle: {
+ readonly suspendAfterSeconds: number;
+ };
}
+export interface SlackChannelDefinition extends ChannelDefinitionBase {
+ readonly type: "slack";
+ readonly scopes: {
+ readonly bot: readonly string[];
+ };
+ readonly events: readonly SlackChannelEvent[];
+}
+
+export interface SmsChannelDefinition extends ChannelDefinitionBase {
+ readonly type: "sms";
+ /** The number customers reply to, in E.164. */
+ readonly from: string;
+ readonly events: readonly MessageChannelEvent[];
+}
+
+export interface EmailChannelDefinition extends ChannelDefinitionBase {
+ readonly type: "email";
+ readonly address: string;
+ readonly events: readonly MessageChannelEvent[];
+}
+
+export type ChannelDefinition =
+ | SlackChannelDefinition
+ | SmsChannelDefinition
+ | EmailChannelDefinition;
+
export interface ChannelRegistrationDefinition extends ResourceReference {
readonly kind: "channel-registration";
readonly version: 1;
@@ -265,6 +316,9 @@ function identifier(value: string, kind: string): string {
return id;
}
+const OPENCOMPUTER_USER_AGENT =
+ "OpenComputer-Agent/1 (+https://opencomputer.dev)";
+
export function useSecret(name: string): SecretReference {
const id = identifier(name, "useSecret");
if (!/^[A-Z][A-Z0-9_]{0,127}$/.test(id)) {
@@ -373,6 +427,15 @@ export function defineConnection(input: {
throw new Error("Connection requests require an absolute path");
}
const headers = Object.fromEntries(new Headers(init.headers).entries());
+ // Some APIs reject a request that carries no User-Agent — GitHub answers
+ // 403 with an empty body, which is undiagnosable from the caller's side.
+ // Default one unless the connection or this request already sets it.
+ const declaresUserAgent = Object.keys(input.headers ?? {}).some(
+ (name) => name.toLowerCase() === "user-agent",
+ );
+ if (!declaresUserAgent && !("user-agent" in headers)) {
+ headers["user-agent"] = OPENCOMPUTER_USER_AGENT;
+ }
const body =
init.body === undefined || init.body === null
? undefined
@@ -433,10 +496,23 @@ const SLACK_EVENT_SCOPE: Readonly<Record<SlackChannelEvent, string>> = {
app_mention: "app_mentions:read",
"message.im": "im:history",
};
-const TRIGGER_EVENT: Readonly<Record<ChannelTrigger, SlackChannelEvent>> = {
+const TRIGGER_EVENT: Readonly<Record<ChannelTrigger, ChannelEvent>> = {
mention: "app_mention",
"direct-message": "message.im",
+ message: "message.inbound",
};
+const PROVIDER_TRIGGERS: Readonly<
+ Record<ChannelProvider, readonly ChannelTrigger[]>
+> = {
+ slack: ["mention", "direct-message"],
+ sms: ["message"],
+ email: ["message"],
+};
+// Suspend quickly by default. A resume costs a moment; an idle runtime costs
+// for every second nobody is typing, and on SMS or email that is most of them.
+const DEFAULT_IDLE_SUSPEND_SECONDS = 300;
+const E164 = /^\+[1-9]\d{7,14}$/;
+const EMAIL_ADDRESS = /^[^@\s]+@[^@\s.]+\.[^@\s]+$/;
function resourceIdentifier(value: string, kind: string): string {
const id = identifier(value, kind);
@@ -527,16 +603,130 @@ export function defineSchedule(input: {
});
}
-export function defineChannel(input: {
+interface ChannelInputBase {
id: string;
- type: "slack";
displayName?: string;
- scopes: { bot: readonly string[] };
- events?: readonly SlackChannelEvent[];
destinations?: Readonly<Record<string, ChannelDestinationDefinition>>;
routing?: { whenAmbiguous?: "ask" };
-}): SlackChannelDefinition {
+ idle?: { suspendAfterSeconds?: number };
+}
+
+export interface SlackChannelInput extends ChannelInputBase {
+ type: "slack";
+ scopes: { bot: readonly string[] };
+ events?: readonly SlackChannelEvent[];
+}
+
+export interface SmsChannelInput extends ChannelInputBase {
+ type: "sms";
+ from: string;
+}
+
+export interface EmailChannelInput extends ChannelInputBase {
+ type: "email";
+ address: string;
+}
+
+export type ChannelInput =
+ | SlackChannelInput
+ | SmsChannelInput
+ | EmailChannelInput;
+
+function channelCommon(input: ChannelInputBase): {
+ id: string;
+ displayName?: string;
+ routing: { whenAmbiguous: "ask" };
+ idle: { suspendAfterSeconds: number };
+} {
const id = resourceIdentifier(input.id, "defineChannel");
+ const seconds =
+ input.idle?.suspendAfterSeconds ?? DEFAULT_IDLE_SUSPEND_SECONDS;
+ if (!Number.isInteger(seconds) || seconds < 30 || seconds > 86_400) {
+ throw new Error(
+ "Channel idle.suspendAfterSeconds must be a whole number of seconds between 30 and 86400",
+ );
+ }
+ return {
+ id,
+ ...(input.displayName?.trim()
+ ? { displayName: input.displayName.trim() }
+ : {}),
+ routing: { whenAmbiguous: input.routing?.whenAmbiguous ?? "ask" },
+ idle: { suspendAfterSeconds: seconds },
+ };
+}
+
+/**
+ * Providers other than Slack address a single participant, so their only
+ * destination is a reply on the conversation the message arrived on.
+ */
+function replyDestinations(
+ input: ChannelInputBase,
+ provider: ChannelProvider,
+): Record<string, Readonly<ChannelDestinationDefinition>> {
+ const destinations: Record<string, Readonly<ChannelDestinationDefinition>> =
+ {};
+ for (const [name, destination] of Object.entries(input.destinations ?? {})) {
+ const destinationId = resourceIdentifier(name, "Channel destination");
+ if (destination.type !== "reply") {
+ throw new Error(
+ `${provider} destination ${destinationId} must be { type: "reply" }`,
+ );
+ }
+ destinations[destinationId] = Object.freeze({ type: "reply" as const });
+ }
+ if (!Object.keys(destinations).length) {
+ destinations.reply = Object.freeze({ type: "reply" as const });
+ }
+ return destinations;
+}
+
+export function defineChannel(input: SlackChannelInput): SlackChannelDefinition;
+export function defineChannel(input: SmsChannelInput): SmsChannelDefinition;
+export function defineChannel(input: EmailChannelInput): EmailChannelDefinition;
+export function defineChannel(input: ChannelInput): ChannelDefinition {
+ const common = channelCommon(input);
+
+ if (input.type === "sms") {
+ const from = input.from.trim();
+ if (!E164.test(from)) {
+ throw new Error(
+ `SMS channel ${common.id} needs a from number in E.164, such as +15125550100`,
+ );
+ }
+ return Object.freeze({
+ kind: "channel" as const,
+ version: 1 as const,
+ type: "sms" as const,
+ ...common,
+ from,
+ events: Object.freeze(["message.inbound" as const]),
+ destinations: Object.freeze(replyDestinations(input, "sms")),
+ routing: Object.freeze(common.routing),
+ idle: Object.freeze(common.idle),
+ });
+ }
+
+ if (input.type === "email") {
+ const address = input.address.trim().toLowerCase();
+ if (!EMAIL_ADDRESS.test(address)) {
+ throw new Error(
+ `Email channel ${common.id} needs a deliverable address, such as [email protected]`,
+ );
+ }
+ return Object.freeze({
+ kind: "channel" as const,
+ version: 1 as const,
+ type: "email" as const,
+ ...common,
+ address,
+ events: Object.freeze(["message.inbound" as const]),
+ destinations: Object.freeze(replyDestinations(input, "email")),
+ routing: Object.freeze(common.routing),
+ idle: Object.freeze(common.idle),
+ });
+ }
+
const scopes = [...new Set(input.scopes.bot.map((scope) => scope.trim()))];
if (
!scopes.length ||
@@ -557,6 +747,11 @@ export function defineChannel(input: {
> = {};
for (const [name, destination] of Object.entries(input.destinations ?? {})) {
const destinationId = resourceIdentifier(name, "Channel destination");
+ if (destination.type !== "conversation") {
+ throw new Error(
+ `Slack destination ${destinationId} must be { type: "conversation" }`,
+ );
+ }
const required =
destination.visibility === "private" ? "groups:read" : "channels:read";
if (!scopes.includes(required)) {
@@ -574,31 +769,36 @@ export function defineChannel(input: {
return Object.freeze({
kind: "channel" as const,
version: 1 as const,
- id,
- type: input.type,
- ...(input.displayName?.trim()
- ? { displayName: input.displayName.trim() }
- : {}),
+ type: "slack" as const,
+ ...common,
scopes: Object.freeze({ bot: Object.freeze(scopes) }),
events: Object.freeze(events),
destinations: Object.freeze(destinations),
- routing: Object.freeze({
- whenAmbiguous: input.routing?.whenAmbiguous ?? "ask",
- }),
+ routing: Object.freeze(common.routing),
+ idle: Object.freeze(common.idle),
});
}
export function registerChannel(
- channel: SlackChannelDefinition,
+ channel: ChannelDefinition,
input: { on: readonly ChannelTrigger[] },
): ChannelRegistrationDefinition {
const triggers = [...new Set(input.on)];
if (!triggers.length) {
throw new Error("registerChannel requires at least one trigger");
}
+ const supported = PROVIDER_TRIGGERS[channel.type];
+ // Each variant narrows `events` to its own literal union; widen once so the
+ // membership check reads the same for every provider.
+ const declared: readonly ChannelEvent[] = channel.events;
for (const trigger of triggers) {
+ if (!supported.includes(trigger)) {
+ throw new Error(
+ `Channel ${channel.id} is a ${channel.type} channel, which supports ${supported.join(" and ")}, not ${trigger}`,
+ );
+ }
const event = TRIGGER_EVENT[trigger];
- if (!channel.events.includes(event)) {
+ if (!declared.includes(event)) {
throw new Error(
`Channel ${channel.id} does not declare the event required by ${trigger}`,
);
diff --git a/cli/src/project.test.ts b/cli/src/project.test.ts
index e3b474c3..a3617e7c 100644
--- a/cli/src/project.test.ts
+++ b/cli/src/project.test.ts
@@ -174,6 +174,7 @@ export default registerOutbox(reviewRequests);
},
},
routing: { whenAmbiguous: "ask" },
+ idle: { suspendAfterSeconds: 300 },
},
],
channelRegistrations: [
@@ -775,3 +776,123 @@ export default function Agent() {
await rm(parent, { recursive: true, force: true });
}
});
+
+test("the compiler accepts SMS and email channels alongside Slack", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-providers-"));
+ const root = resolve(parent, "app");
+ try {
+ const initialized = await initializeAgentProject(root);
+ await mkdir(resolve(root, "opencomputer", "channels"), { recursive: true });
+ await mkdir(resolve(initialized.agentRoot, "channels"), { recursive: true });
+
+ await writeFile(
+ resolve(root, "opencomputer", "channels", "shop-sms.ts"),
+ `import { defineChannel } from "@opencomputer/agent";
+
+export default defineChannel({
+ id: "shop-sms",
+ type: "sms",
+ from: "+15125550100",
+ idle: { suspendAfterSeconds: 60 },
+});
+`,
+ );
+ await writeFile(
+ resolve(root, "opencomputer", "channels", "support-email.ts"),
+ `import { defineChannel } from "@opencomputer/agent";
+
+export default defineChannel({
+ id: "support-email",
+ type: "email",
+ address: "[email protected]",
+});
+`,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "channels", "shop-sms.ts"),
+ `import { registerChannel } from "@opencomputer/agent";
+import shopSms from "../../../channels/shop-sms.js";
+export default registerChannel(shopSms, { on: ["message"] });
+`,
+ );
+
+ const built = await readProjectResources(root);
+ const sms = built.manifest.channels.find((c) => c.id === "shop-sms");
+ const email = built.manifest.channels.find((c) => c.id === "support-email");
+
+ assert.deepEqual(sms, {
+ id: "shop-sms",
+ type: "sms",
+ routing: { whenAmbiguous: "ask" },
+ idle: { suspendAfterSeconds: 60 },
+ from: "+15125550100",
+ events: ["message.inbound"],
+ destinations: { reply: { type: "reply" } },
+ });
+ // Addresses normalize to lower case so a conversation key is stable.
+ assert.equal(email?.address, "[email protected]");
+ assert.deepEqual(email?.idle, { suspendAfterSeconds: 300 });
+ assert.deepEqual(built.manifest.channelRegistrations, [
+ { agentId: "hello-world", channelId: "shop-sms", triggers: ["message"] },
+ ]);
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
+test("the compiler rejects a trigger the provider cannot deliver", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-trigger-"));
+ const root = resolve(parent, "app");
+ try {
+ const initialized = await initializeAgentProject(root);
+ await mkdir(resolve(root, "opencomputer", "channels"), { recursive: true });
+ await mkdir(resolve(initialized.agentRoot, "channels"), { recursive: true });
+ await writeFile(
+ resolve(root, "opencomputer", "channels", "shop-sms.ts"),
+ `import { defineChannel } from "@opencomputer/agent";
+export default defineChannel({ id: "shop-sms", type: "sms", from: "+15125550100" });
+`,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "channels", "shop-sms.ts"),
+ `import { registerChannel } from "@opencomputer/agent";
+import shopSms from "../../../channels/shop-sms.js";
+export default registerChannel(shopSms, { on: ["mention"] });
+`,
+ );
+ await assert.rejects(
+ readProjectResources(root),
+ /trigger mention is not available on a sms channel/,
+ );
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
+test("the compiler rejects malformed provider addresses", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-addr-"));
+ const root = resolve(parent, "app");
+ try {
+ await initializeAgentProject(root);
+ await mkdir(resolve(root, "opencomputer", "channels"), { recursive: true });
+ const channel = resolve(root, "opencomputer", "channels", "shop-sms.ts");
+ await writeFile(
+ channel,
+ `import { defineChannel } from "@opencomputer/agent";
+export default defineChannel({ id: "shop-sms", type: "sms", from: "512-555-0100" });
+`,
+ );
+ await assert.rejects(readProjectResources(root), /E\.164/);
+
+ await rm(channel);
+ await writeFile(
+ resolve(root, "opencomputer", "channels", "support-email.ts"),
+ `import { defineChannel } from "@opencomputer/agent";
+export default defineChannel({ id: "support-email", type: "email", address: "not-an-address" });
+`,
+ );
+ await assert.rejects(readProjectResources(root), /deliverable email address/);
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
diff --git a/cli/src/project.ts b/cli/src/project.ts
index 473fb1f3..c2684faa 100644
--- a/cli/src/project.ts
+++ b/cli/src/project.ts
@@ -48,25 +48,33 @@ export interface McpServerManifest {
connection?: string;
}
+export type ChannelProviderManifest = "slack" | "sms" | "email";
+
export interface ChannelDestinationManifest {
- type: "conversation";
- visibility: "public" | "private";
+ type: "conversation" | "reply";
+ visibility?: "public" | "private";
}
export interface ChannelDefinitionManifest {
id: string;
- type: "slack";
+ type: ChannelProviderManifest;
displayName?: string;
- scopes: { bot: string[] };
- events: Array<"app_mention" | "message.im">;
+ /** Slack only. */
+ scopes?: { bot: string[] };
+ /** SMS only, E.164. */
+ from?: string;
+ /** Email only. */
+ address?: string;
+ events: string[];
destinations: Record<string, ChannelDestinationManifest>;
routing: { whenAmbiguous: "ask" };
+ idle: { suspendAfterSeconds: number };
}
export interface ChannelRegistrationManifest {
agentId: string;
channelId: string;
- triggers: Array<"mention" | "direct-message">;
+ triggers: Array<"mention" | "direct-message" | "message">;
}
export interface OutboxDefinitionManifest {
@@ -928,6 +936,110 @@ function importedResourceId(
return module;
}
+/** Shared across every provider: routing, display name, idle policy. */
+function channelCommonManifest(
+ input: ts.ObjectLiteralExpression,
+ path: string,
+): {
+ displayName?: string;
+ routing: { whenAmbiguous: "ask" };
+ idle: { suspendAfterSeconds: number };
+} {
+ 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"`);
+ }
+ }
+ let suspendAfterSeconds = 300;
+ const idleExpression = objectProperty(input, "idle");
+ if (idleExpression) {
+ if (!ts.isObjectLiteralExpression(idleExpression)) {
+ throw new Error(`${path} idle must be an object literal`);
+ }
+ const seconds = objectProperty(idleExpression, "suspendAfterSeconds");
+ if (seconds) {
+ if (!ts.isNumericLiteral(seconds)) {
+ throw new Error(
+ `${path} idle.suspendAfterSeconds must be a literal number`,
+ );
+ }
+ suspendAfterSeconds = Number(seconds.text);
+ if (
+ !Number.isInteger(suspendAfterSeconds) ||
+ suspendAfterSeconds < 30 ||
+ suspendAfterSeconds > 86_400
+ ) {
+ throw new Error(
+ `${path} idle.suspendAfterSeconds must be between 30 and 86400`,
+ );
+ }
+ }
+ }
+ const displayNameExpression = objectProperty(input, "displayName");
+ return {
+ ...(displayNameExpression
+ ? {
+ displayName: literalStringValue(
+ displayNameExpression,
+ `${path} displayName`,
+ ),
+ }
+ : {}),
+ routing: { whenAmbiguous: "ask" as const },
+ idle: { suspendAfterSeconds },
+ };
+}
+
+/**
+ * SMS and email address one participant, so their only destination is a reply
+ * on the conversation the message arrived on. Declaring none is the common
+ * case and yields a single `reply` destination.
+ */
+function replyDestinationsManifest(
+ input: ts.ObjectLiteralExpression,
+ path: string,
+): Record<string, ChannelDestinationManifest> {
+ const destinations: Record<string, ChannelDestinationManifest> = {};
+ const expression = objectProperty(input, "destinations");
+ if (expression) {
+ if (!ts.isObjectLiteralExpression(expression)) {
+ throw new Error(`${path} destinations must be an object literal`);
+ }
+ for (const property of expression.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 type = literalStringValue(
+ objectProperty(property.initializer, "type"),
+ `${path} destination ${name} type`,
+ );
+ if (type !== "reply") {
+ throw new Error(
+ `${path} destination ${name} must be { type: "reply" }`,
+ );
+ }
+ destinations[name] = { type: "reply" };
+ }
+ }
+ if (!Object.keys(destinations).length) destinations.reply = { type: "reply" };
+ return destinations;
+}
+
function channelDefinition(
source: string,
path: string,
@@ -945,7 +1057,52 @@ function channelDefinition(
objectProperty(input, "type"),
`${path} channel type`,
);
- if (type !== "slack") throw new Error(`${path} supports only type "slack"`);
+ const common = channelCommonManifest(input, path);
+
+ if (type === "sms") {
+ const from = literalStringValue(
+ objectProperty(input, "from"),
+ `${path} SMS from number`,
+ );
+ if (!/^\+[1-9]\d{7,14}$/.test(from)) {
+ throw new Error(
+ `${path} from must be an E.164 number such as +15125550100`,
+ );
+ }
+ return {
+ id,
+ type: "sms",
+ ...common,
+ from,
+ events: ["message.inbound"],
+ destinations: replyDestinationsManifest(input, path),
+ };
+ }
+
+ if (type === "email") {
+ const address = literalStringValue(
+ objectProperty(input, "address"),
+ `${path} email address`,
+ ).toLowerCase();
+ if (!/^[^@\s]+@[^@\s.]+\.[^@\s]+$/.test(address)) {
+ throw new Error(`${path} address must be a deliverable email address`);
+ }
+ return {
+ id,
+ type: "email",
+ ...common,
+ address,
+ events: ["message.inbound"],
+ destinations: replyDestinationsManifest(input, path),
+ };
+ }
+
+ if (type !== "slack") {
+ throw new Error(
+ `${path} has unsupported channel type ${JSON.stringify(type)}. Supported: slack, sms, email`,
+ );
+ }
+
const scopesExpression = objectProperty(input, "scopes");
if (!scopesExpression || !ts.isObjectLiteralExpression(scopesExpression)) {
throw new Error(`${path} scopes must be an object literal`);
@@ -1019,27 +1176,13 @@ function channelDefinition(
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`) }
- : {}),
+ ...common,
scopes: { bot: scopes },
- events: events as ChannelDefinitionManifest["events"],
+ events,
destinations,
- routing: { whenAmbiguous: "ask" },
};
}
@@ -1074,10 +1217,22 @@ function channelRegistration(
const triggerEvents: Record<string, string> = {
mention: "app_mention",
"direct-message": "message.im",
+ message: "message.inbound",
+ };
+ const providerTriggers: Record<string, string[]> = {
+ slack: ["mention", "direct-message"],
+ sms: ["message"],
+ email: ["message"],
};
+ const supported = providerTriggers[channel.type] ?? [];
for (const trigger of triggers) {
+ if (!supported.includes(trigger)) {
+ throw new Error(
+ `${path} trigger ${trigger} is not available on a ${channel.type} channel (supported: ${supported.join(", ")})`,
+ );
+ }
const event = triggerEvents[trigger];
- if (!event || !channel.events.includes(event as "app_mention" | "message.im")) {
+ if (!event || !channel.events.includes(event)) {
throw new Error(`${path} trigger ${trigger} is not declared by ${channelId}`);
}
}
@@ -1639,6 +1794,7 @@ function agentApiRuntimeSource(): string {
if (!value) throw new Error("OpenComputer hooks can only run while rendering an agent");
return value;
}
+const OPENCOMPUTER_USER_AGENT = "OpenComputer-Agent/1 (+https://opencomputer.dev)";
function id(value, kind) {
const normalized = String(value).trim();
if (!normalized) throw new Error(kind + " requires a non-empty id");
@@ -1680,6 +1836,11 @@ export const defineConnection = (input) => {
if (!path.startsWith("/")) throw new Error("Connection requests require an absolute path");
const headers = {};
new Headers(init.headers).forEach((value, name) => { headers[name] = value; });
+ // Some APIs reject a request that carries no User-Agent — GitHub answers
+ // 403 with an empty body, which is undiagnosable from the caller's side.
+ // Default one unless the connection or the request already sets it.
+ const declaresUserAgent = Object.keys(input.headers || {}).some((name) => name.toLowerCase() === "user-agent");
+ if (!declaresUserAgent && !("user-agent" in headers)) headers["user-agent"] = OPENCOMPUTER_USER_AGENT;
if (init.body != null && typeof init.body !== "string") throw new Error("Managed connection request bodies must currently be strings");
if (typeof init.body === "string" && init.body.length > 5 * 1024 * 1024) throw new Error("Managed connection request bodies cannot exceed 5 MiB");
return fetch(base.replace(/\\\/$/, "") + "/" + encodeURIComponent(connectionId) + "/fetch", {
diff --git a/docs/agents/channels.mdx b/docs/agents/channels.mdx
index f6ece772..1622dd87 100644
--- a/docs/agents/channels.mdx
+++ b/docs/agents/channels.mdx
@@ -1,13 +1,71 @@
---
-title: "Slack channels"
-description: "Declare Slack capabilities in code and connect them per environment"
+title: "Channels"
+description: "Declare a conversational surface in code and connect it per environment"
---
Channels connect a project to a messaging provider. The channel definition is
-code-owned; provider credentials and Slack conversation IDs are configured in
+code-owned; provider credentials and conversation IDs are configured in
the dashboard for each environment.
-The current channel provider is Slack.
+A channel is a conversation keyed by an external participant. What differs
+between providers is transport, addressing, and authentication; what does not
+differ is that an inbound message continues the conversation it belongs to.
+Agents see the second part and never the first — one `useInput().source ===
+"channel"` branch handles every provider.
+
+| Provider | `type` | Addressed by | Triggers |
+| --- | --- | --- | --- |
+| Slack | `"slack"` | bot scopes and events | `mention`, `direct-message` |
+| SMS | `"sms"` | `from`, an E.164 number | `message` |
+| Email | `"email"` | `address` | `message` |
+
+## Define an SMS or email channel
+
+Providers other than Slack address one participant, so they need no scopes and
+have a single inbound event:
+
+```tsx opencomputer/channels/shop-sms.ts
+import { defineChannel } from "@opencomputer/agent";
+
+export default defineChannel({
+ id: "shop-sms",
+ type: "sms",
+ from: "+15125550100",
+ idle: { suspendAfterSeconds: 120 },
+});
+```
+
+```tsx opencomputer/channels/support-email.ts
+import { defineChannel } from "@opencomputer/agent";
+
+export default defineChannel({
+ id: "support-email",
+ type: "email",
+ address: "[email protected]",
+});
+```
+
+Register them the same way as Slack, with the trigger the provider supports:
+
+```tsx opencomputer/agents/receptionist/channels/shop-sms.ts
+import { registerChannel } from "@opencomputer/agent";
+import shopSms from "../../../channels/shop-sms.js";
+
+export default registerChannel(shopSms, { on: ["message"] });
+```
+
+Registering a Slack trigger on an SMS channel is a build error, and the reverse
+is too.
+
+## Idle and cost
+
+Agent runtime is billed by wall-clock time, and a conversation spends most of
+its life waiting for a person. `idle.suspendAfterSeconds` says how long to hold
+the runtime after the last message; an inbound message resumes it. It defaults
+to 300 seconds, and the default matters most where replies are slowest — an SMS
+conversation that waits hours for an answer should not bill for those hours.
+
+## Slack
## Define a Slack channel