Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(channels): add Telegram and Discord channels

Rahmanac5d08fba5d0
diff --git a/.env.example b/.env.example
index 92d8d2b2..35fc56cf 100644
--- a/.env.example
+++ b/.env.example
@@ -35,6 +35,8 @@ OS_SESSION_SECRET=
# OS_EXEC_ALLOW_DESTRUCTIVE=1
# Append-only audit trail of exec/file/browser/auth actions. Default path below.
# OS_AUDIT_LOG=~/.mso/audit.log
+# Optional override for the owner-private, metadata-only Channels store.
+# OS_CHANNEL_STORE=~/.mso/private/channels.json
# Transcript of the last Settings → About "Software update" run — the panel polls
# this file, and scripts/self-update.sh truncates it on every start. Rarely worth
# moving; it is here because the updater runs as a transient systemd unit and the
diff --git a/app/api/v1/channels/discord/[id]/route.test.ts b/app/api/v1/channels/discord/[id]/route.test.ts
new file mode 100644
index 00000000..a169b5ee
--- /dev/null
+++ b/app/api/v1/channels/discord/[id]/route.test.ts
@@ -0,0 +1,43 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const mocks = vi.hoisted(() => ({ receive: vi.fn(), dispatch: vi.fn(), rate: vi.fn() }));
+vi.mock("@/lib/host/rate-limit", () => ({ rateLimitedUntrusted: mocks.rate }));
+vi.mock("../../workflow-runtime", () => ({ channelWorkflowRuntime: () => ({ scope: "exec", resolveTool: () => undefined }) }));
+vi.mock("@/lib/channels", () => {
+ class ChannelError extends Error {
+ constructor(public readonly code: string, public readonly status = 400) { super(code); }
+ }
+ return { ChannelError, receiveDiscord: mocks.receive, dispatchChannelInbound: mocks.dispatch };
+});
+
+const { POST } = await import("./route");
+const request = () => new NextRequest("https://mso.example.test/api/v1/channels/discord/channel-2", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-signature-timestamp": "1", "x-signature-ed25519": "aa".repeat(64) },
+ body: JSON.stringify({ id: "1", type: 2 }),
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.rate.mockReturnValue(false);
+ mocks.receive.mockResolvedValue({ event: { provider: "discord", eventId: "1", kind: "command", receivedAt: new Date().toISOString(), raw: {} }, ping: false });
+ mocks.dispatch.mockResolvedValue({ workflow: null });
+});
+
+describe("Discord interactions route", () => {
+ it("returns Discord PONG without starting a workflow", async () => {
+ mocks.receive.mockResolvedValue({ event: null, ping: true });
+ const response = await POST(request(), { params: Promise.resolve({ id: "channel-2" }) });
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ type: 1 });
+ expect(mocks.dispatch).not.toHaveBeenCalled();
+ });
+
+ it("dispatches verified non-PING interactions", async () => {
+ const response = await POST(request(), { params: Promise.resolve({ id: "channel-2" }) });
+ expect(response.status).toBe(200);
+ expect(mocks.dispatch).toHaveBeenCalledTimes(1);
+ await expect(response.json()).resolves.toMatchObject({ type: 4 });
+ });
+});
diff --git a/app/api/v1/channels/discord/[id]/route.ts b/app/api/v1/channels/discord/[id]/route.ts
new file mode 100644
index 00000000..aefa5562
--- /dev/null
+++ b/app/api/v1/channels/discord/[id]/route.ts
@@ -0,0 +1,26 @@
+import { NextRequest, NextResponse } from "next/server";
+import { ChannelError, dispatchChannelInbound, receiveDiscord } from "@/lib/channels";
+import { rateLimitedUntrusted } from "@/lib/host/rate-limit";
+import { channelWorkflowRuntime } from "../../workflow-runtime";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export async function POST(req: NextRequest, context: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await context.params;
+ if (rateLimitedUntrusted(`channel-discord:${id}`, 120, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });
+ const length = Number(req.headers.get("content-length"));
+ if (Number.isFinite(length) && length > 1024 * 1024) throw new ChannelError("request_too_large", 413);
+ const body = await req.text();
+ if (Buffer.byteLength(body) > 1024 * 1024) throw new ChannelError("request_too_large", 413);
+ const result = await receiveDiscord(id, body, req.headers.get("x-signature-timestamp"), req.headers.get("x-signature-ed25519"));
+ if (result.ping) return NextResponse.json({ type: 1 });
+ if (!result.event) throw new ChannelError("invalid_discord_interaction");
+ const dispatched = await dispatchChannelInbound(id, result.event, channelWorkflowRuntime());
+ return NextResponse.json({ type: 4, data: { content: dispatched.workflow ? "Workflow started." : "Received by MSO Channels.", flags: 64 } });
+ } catch (error) {
+ const value = error instanceof ChannelError ? error : new ChannelError("invalid_channel_interaction");
+ return NextResponse.json({ error: value.code }, { status: value.status });
+ }
+}
diff --git a/app/api/v1/channels/route.test.ts b/app/api/v1/channels/route.test.ts
new file mode 100644
index 00000000..bd52f68f
--- /dev/null
+++ b/app/api/v1/channels/route.test.ts
@@ -0,0 +1,36 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const session = vi.hoisted(() => ({ role: null as null | string }));
+vi.mock("@/lib/auth/require-session", () => ({
+ getSessionContext: vi.fn(async () => session.role ? { role: session.role, session: { device_id: "test-device" } } : null),
+}));
+vi.mock("@/lib/channels", () => ({
+ ChannelError: class ChannelError extends Error {
+ constructor(public readonly code: string, public readonly status = 400) { super(code); }
+ },
+ channelsSnapshot: vi.fn(async () => ({ version: 1, revision: 0, channels: [], credentials: [], providers: [] })),
+ createChannelConfig: vi.fn(),
+ updateChannelConfig: vi.fn(),
+ deleteChannelConfig: vi.fn(),
+ sendChannelText: vi.fn(),
+ testChannel: vi.fn(),
+}));
+
+import { GET } from "./route";
+
+describe("/api/v1/channels", () => {
+ beforeEach(() => { session.role = null; });
+
+ it("requires owner session before exposing channel metadata", async () => {
+ const response = await GET();
+ expect(response.status).toBe(403);
+ expect(await response.json()).toEqual({ error: "owner_required" });
+ });
+
+ it("returns the bounded metadata snapshot for owner", async () => {
+ session.role = "owner";
+ const response = await GET();
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ version: 1, revision: 0, channels: [] });
+ });
+});
diff --git a/app/api/v1/channels/route.ts b/app/api/v1/channels/route.ts
new file mode 100644
index 00000000..77299571
--- /dev/null
+++ b/app/api/v1/channels/route.ts
@@ -0,0 +1,70 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { readSetupJson } from "@/lib/infra/setup-http";
+import { rateLimited } from "@/lib/host/rate-limit";
+import {
+ ChannelError,
+ channelsSnapshot,
+ createChannelConfig,
+ deleteChannelConfig,
+ sendChannelText,
+ testChannel,
+ updateChannelConfig,
+} from "@/lib/channels";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer" };
+
+const failure = (error: unknown) => {
+ const value = error instanceof ChannelError ? error : new ChannelError("channel_operation_failed", 400);
+ return NextResponse.json({ error: value.code }, { status: value.status, headers });
+};
+
+async function owner() {
+ const context = await getSessionContext();
+ return context?.role === "owner" ? context : null;
+}
+
+export async function GET() {
+ if (!(await owner())) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ try { return NextResponse.json(await channelsSnapshot(), { headers }); }
+ catch (error) { return failure(error); }
+}
+
+export async function POST(req: NextRequest) {
+ const context = await owner();
+ if (!context) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ try {
+ const body = await readSetupJson(req, 64 * 1024);
+ const action = typeof body.action === "string" ? body.action : "";
+ if (rateLimited(`channels:${action}:${context.session.device_id}`, action === "send" ? 60 : 30, 60_000)) {
+ throw new ChannelError("rate_limited", 429);
+ }
+ if (action === "create") {
+ if (!body.data || typeof body.data !== "object" || Array.isArray(body.data)) throw new ChannelError("invalid_channel_data");
+ return NextResponse.json(await createChannelConfig(body.data as Record<string, unknown>), { headers });
+ }
+ if (action === "update") {
+ if (typeof body.id !== "string" || !Number.isSafeInteger(body.expectedRevision) || !body.data || typeof body.data !== "object" || Array.isArray(body.data)) {
+ throw new ChannelError("invalid_channel_update");
+ }
+ return NextResponse.json(await updateChannelConfig(body.id, Number(body.expectedRevision), body.data as Record<string, unknown>), { headers });
+ }
+ if (action === "delete") {
+ if (typeof body.id !== "string" || !Number.isSafeInteger(body.expectedRevision)) throw new ChannelError("invalid_channel_delete");
+ return NextResponse.json(await deleteChannelConfig(body.id, Number(body.expectedRevision)), { headers });
+ }
+ if (action === "test") {
+ if (typeof body.id !== "string") throw new ChannelError("invalid_channel_id");
+ return NextResponse.json(await testChannel(body.id), { headers });
+ }
+ if (action === "send") {
+ if (typeof body.id !== "string" || typeof body.text !== "string") throw new ChannelError("invalid_channel_send");
+ return NextResponse.json(await sendChannelText(body.id, { text: body.text, ...(typeof body.target === "string" ? { target: body.target } : {}) }), { headers });
+ }
+ throw new ChannelError("unknown_channel_action");
+ } catch (error) {
+ return failure(error);
+ }
+}
diff --git a/app/api/v1/channels/telegram/[id]/route.test.ts b/app/api/v1/channels/telegram/[id]/route.test.ts
new file mode 100644
index 00000000..c86cdc44
--- /dev/null
+++ b/app/api/v1/channels/telegram/[id]/route.test.ts
@@ -0,0 +1,44 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const mocks = vi.hoisted(() => ({ receive: vi.fn(), dispatch: vi.fn(), rate: vi.fn() }));
+vi.mock("@/lib/host/rate-limit", () => ({ rateLimitedUntrusted: mocks.rate }));
+vi.mock("../../workflow-runtime", () => ({ channelWorkflowRuntime: () => ({ scope: "exec", resolveTool: () => undefined }) }));
+vi.mock("@/lib/channels", () => {
+ class ChannelError extends Error {
+ constructor(public readonly code: string, public readonly status = 400) { super(code); }
+ }
+ return { ChannelError, receiveTelegram: mocks.receive, dispatchChannelInbound: mocks.dispatch };
+});
+
+const { POST } = await import("./route");
+const request = () => new NextRequest("https://mso.example.test/api/v1/channels/telegram/channel-1", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-telegram-bot-api-secret-token": "secret_123" },
+ body: JSON.stringify({ update_id: 7 }),
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.rate.mockReturnValue(false);
+ mocks.receive.mockResolvedValue({ provider: "telegram", eventId: "7", kind: "message", receivedAt: new Date().toISOString(), raw: {} });
+ mocks.dispatch.mockResolvedValue({ workflow: { runId: "run-1", state: "running", graphId: "flow-1" } });
+});
+
+describe("Telegram channel webhook route", () => {
+ it("dispatches only after provider verification returns an event", async () => {
+ const response = await POST(request(), { params: Promise.resolve({ id: "channel-1" }) });
+ expect(response.status).toBe(200);
+ expect(mocks.receive).toHaveBeenCalledWith("channel-1", { update_id: 7 }, "secret_123");
+ expect(mocks.dispatch).toHaveBeenCalledTimes(1);
+ await expect(response.json()).resolves.toMatchObject({ ok: true, eventId: "7", workflow: { runId: "run-1" } });
+ });
+
+ it("preserves provider-native verification failures", async () => {
+ const { ChannelError } = await import("@/lib/channels");
+ mocks.receive.mockRejectedValue(new ChannelError("invalid_webhook_signature", 401));
+ const response = await POST(request(), { params: Promise.resolve({ id: "channel-1" }) });
+ expect(response.status).toBe(401);
+ expect(mocks.dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/api/v1/channels/telegram/[id]/route.ts b/app/api/v1/channels/telegram/[id]/route.ts
new file mode 100644
index 00000000..00132d5e
--- /dev/null
+++ b/app/api/v1/channels/telegram/[id]/route.ts
@@ -0,0 +1,22 @@
+import { NextRequest, NextResponse } from "next/server";
+import { ChannelError, dispatchChannelInbound, receiveTelegram } from "@/lib/channels";
+import { rateLimitedUntrusted } from "@/lib/host/rate-limit";
+import { channelWorkflowRuntime } from "../../workflow-runtime";
+import { readSetupJson } from "@/lib/infra/setup-http";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+export async function POST(req: NextRequest, context: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await context.params;
+ if (rateLimitedUntrusted(`channel-telegram:${id}`, 120, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });
+ const body = await readSetupJson(req, 1024 * 1024);
+ const event = await receiveTelegram(id, body, req.headers.get("x-telegram-bot-api-secret-token"));
+ const dispatched = await dispatchChannelInbound(id, event, channelWorkflowRuntime());
+ return NextResponse.json({ ok: true, eventId: event.eventId, ...dispatched });
+ } catch (error) {
+ const value = error instanceof ChannelError ? error : new ChannelError("invalid_channel_webhook");
+ return NextResponse.json({ error: value.code }, { status: value.status });
+ }
+}
diff --git a/app/api/v1/channels/workflow-runtime.ts b/app/api/v1/channels/workflow-runtime.ts
new file mode 100644
index 00000000..e00f6e67
--- /dev/null
+++ b/app/api/v1/channels/workflow-runtime.ts
@@ -0,0 +1,12 @@
+import type { ChannelWorkflowRuntime } from "@/lib/channels/workflow";
+import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";
+import { maxScope } from "@/lib/mcp/scope";
+import { TOOLS_BY_NAME } from "@/lib/mcp/tools";
+
+export function channelWorkflowRuntime(): ChannelWorkflowRuntime {
+ return {
+ scope: maxScope(),
+ capabilities: msoCapabilityRuntime,
+ resolveTool: (name) => TOOLS_BY_NAME.get(name),
+ };
+}
diff --git a/bin/mso b/bin/mso
index 29598193..3eba1e5d 100755
--- a/bin/mso
+++ b/bin/mso
@@ -51,6 +51,7 @@
# flow list|inspect|run|status|save|delete Project API/MCP automation (flow --help)
# workflow * Visual/private Workflow Graph v2 CRUD + run/status (workflow --help)
# integrations Named credential users, connections, sources, setup and execution
+# channels * Telegram/Discord channels: list, create/save/delete, test, send
# provider * Infrastructure credentials: list | set | rm | doctor
# providers * Alias for provider
# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index d65f3a00..5a323b3e 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -14,6 +14,7 @@ const commandOwnerFiles = [
"scripts/cli/commands-runtime.sh",
"scripts/cli/flows.sh",
"scripts/cli/workflows.sh",
+ "scripts/cli/channels.sh",
"scripts/cli/commands-state.sh",
"scripts/cli/organization.sh",
"scripts/cli/config-command.sh",
@@ -115,6 +116,8 @@ describe("bin/mso", () => {
// named CLI setup verb opens that form without placing keys in shell/tool JSON.
"POST /api/integrations/setup",
"GET /api/sw",
+ "POST /api/v1/channels/telegram/[id]", // Provider callback: requires Telegram webhook signature, not a user CLI action.
+ "POST /api/v1/channels/discord/[id]", // Provider callback: requires Discord Ed25519 signature, not a user CLI action.
"/api/v1/managed-apps/[id]/proxy/[[...path]]",
"/api/auth/devices",
// Internal transport between scripts/mso-agent.mjs and the authenticated
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 93645dcd..9720f30a 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -339,3 +339,11 @@ Each MSO connector/server scope owns its own Page app catalog. Core MSO Page cod
MSO Organization is a first-class owner-private domain beside Workflow Graph, Local Agents, A2A, Project Agents, and Integrations. It stores stable units/seats/reporting lines and execution-target references; it does not store credentials, transcripts, or workflow topology. An active seat may be `unbound`, and a seat may reference an existing `project-agent`, `local-agent`, or `a2a` executor. Workflow Agent nodes can hold `orgSeatId` and resolve that pointer at run time, so organizational identity remains stable when the underlying executor changes. All existing capability/audit/approval boundaries still apply. See [`ORGANIZATION.md`](./ORGANIZATION.md).
MSO has a Workflow Graph v2 layer above the existing automation/lifecycle/RASMIC primitives. It is the automation-topology SSOT and provides server-side schedule/webhook triggers, bounded branching/loops/subflows, retry/error paths, versioned definitions, private variables and persisted execution history. Canonical project paths resolve dynamically and credentials remain in integration authorities rather than portable graph definitions. Graph definitions/versions/runs/variables are isolated by authenticated principal, while tools/scripts/subflows retain normal capability scope, audit, connection and project guards. See [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md).
+
+## Channels
+
+`frontend/slices/channels/` is the first-class messaging application. The provider-neutral runtime lives in `lib/channels/`; provider-specific behavior is limited to adapters. Channel records store only non-secret routing/configuration and exact references to native Integrations connections.
+
+Telegram and Discord credentials remain under `lib/infra/*`. Telegram inbound requests require the configured Bot API webhook secret; Discord inbound requests require Ed25519-signed Interactions. Discord Gateway message ingestion is not part of the current capability.
+
+Inbound channel events may dispatch into the existing Workflow Graph engine through the `channel_trigger` node. Outbound automation uses `channel_send`, which calls the same Channels send service as the UI/API. This keeps Channels, Integrations, and Workflows as separate authorities without copying credentials or building a second automation engine. See [CHANNELS.md](./CHANNELS.md).
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index ecde28be..8f6feb56 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -28,6 +28,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `channels` add Telegram and Discord channels
- `federation` bridge Batonly to MSO and SI-Coder
- `workflows` split n8n and improve org automation ux
diff --git a/docs/CHANNELS.md b/docs/CHANNELS.md
new file mode 100644
index 00000000..9cda2a34
--- /dev/null
+++ b/docs/CHANNELS.md
@@ -0,0 +1,112 @@
+# Channels
+
+MSO Channels is the provider-neutral messaging boundary between external conversation systems and native MSO Workflows.
+
+The first adapters are **Telegram** and **Discord**. The domain is intentionally split from Integrations:
+
+- **Integrations** owns credential users, named provider connections, bot tokens, webhook secrets, Discord application IDs and public keys.
+- **Channels** owns non-secret routing configuration: display name, provider, exact Integration reference, enabled state, default target and optional workflow binding.
+- **Workflows** owns automation topology and execution. Channels does not create a second automation engine.
+
+## Architecture
+
+```text
+Telegram / Discord
+ |
+ | verified provider-native inbound request
+ v
+/api/v1/channels/<provider>/<channel-id>
+ |
+ v
+lib/channels
+ ├─ provider registry
+ ├─ metadata-only channel store
+ ├─ Telegram adapter
+ ├─ Discord adapter
+ └─ workflow dispatcher
+ |
+ v
+native Workflow Graph
+ Channel Trigger -> ... -> Channel Send
+```
+
+The private channel store lives under `~/.mso/private/channels.json` by default. It contains no credential values.
+
+## Telegram
+
+A Telegram Integration connection stores:
+
+- `botToken` — secret, required.
+- `webhookSecret` — secret, optional for outbound-only usage and required by MSO before accepting inbound webhook events.
+
+Credential verification calls Bot API `getMe`. Outbound text uses `sendMessage`.
+
+Inbound URL:
+
+```text
+https://<mso-host>/api/v1/channels/telegram/<channel-id>
+```
+
+Configure Telegram to send the exact configured webhook secret through `X-Telegram-Bot-Api-Secret-Token`. MSO refuses inbound Telegram delivery when no webhook secret is configured.
+
+## Discord
+
+A Discord Integration connection stores:
+
+- `botToken` — secret, required for REST sends.
+- `applicationId` — non-secret, optional for outbound-only usage and recommended for inbound binding.
+- `publicKey` — non-secret Ed25519 Interactions public key, required for inbound Interactions.
+
+Credential verification calls Discord REST `/api/v10/users/@me` with Bot authorization. Outbound text posts to `/api/v10/channels/<channel-id>/messages`.
+
+Inbound Interactions URL:
+
+```text
+https://<mso-host>/api/v1/channels/discord/<channel-id>
+```
+
+MSO verifies `X-Signature-Ed25519` over `X-Signature-Timestamp + rawBody`, supports Discord PING/PONG, and normalizes supported interaction payloads into the shared inbound event contract.
+
+**Discord Gateway message ingestion is not implemented or claimed.** Channels currently supports Discord REST sending plus signed HTTP Interactions.
+
+## Workflow integration
+
+Native Workflow Graph exposes two provider-neutral node types:
+
+- **Channel Trigger** — root trigger for a channel-bound workflow.
+- **Channel Send** — sends text through an existing Channel record.
+
+A Channel may reference one active workflow. The workflow must contain a Channel Trigger that either names that Channel ID or leaves `channelId` empty as the workflow's fallback Channel Trigger.
+
+Inbound events enter Workflow input as:
+
+```json
+{
+ "channel": {
+ "id": "<channel-id>",
+ "name": "<display-name>",
+ "provider": "telegram | discord"
+ },
+ "event": {
+ "provider": "telegram | discord",
+ "eventId": "<provider-event-id>",
+ "kind": "<normalized-kind>",
+ "target": "<optional-target>",
+ "sender": "<optional-sender>",
+ "text": "<optional-text>",
+ "receivedAt": "<iso-time>"
+ }
+}
+```
+
+Raw provider payloads are not copied into the workflow input receipt.
+
+## Security boundaries
+
+- No bot token or webhook secret is accepted by the Channels CRUD API or stored in channel state.
+- Channel creation/update resolves the exact existing direct Integration connection before saving.
+- Owner session is required for Channels list/create/update/delete/test/send.
+- Public inbound endpoints are provider-authenticated instead of owner-session authenticated.
+- Inbound routes apply untrusted rate limits before expensive payload verification.
+- Channel activity and health checks do not advance configuration revision, so inbound traffic cannot invalidate an owner's pending edit.
+- Provider response bodies and credentials are not returned by doctor/test responses.
diff --git a/docs/CLI.md b/docs/CLI.md
index bc0c4ef5..5bc1abe0 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -91,6 +91,7 @@ Commands:
flow list|inspect|run|status|save|delete Project API/MCP automation (flow --help)
workflow * Visual/private Workflow Graph v2 CRUD + run/status (workflow --help)
integrations Named credential users, connections, sources, setup and execution
+ channels * Telegram/Discord channels: list, create/save/delete, test, send
provider * Infrastructure credentials: list | set | rm | doctor
providers * Alias for provider
gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 553cc682..07d9ae55 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -312,3 +312,13 @@ Hostinger is one provider with two direct connection methods:
The native connection executor supports read-only mail-order/plan/resource/log operations plus reviewed non-secret mailbox management for aliases, forwarders, autoreplies, catch-alls and mailbox deletion. Mailbox creation/password rotation, webhook creation/regeneration, and Mail API-token creation are deliberately not accepted through model/tool JSON because those operations create or consume secret values. Use a private Hostinger/browser flow for those secrets.
Official reference: <https://developers.hostinger.com/> → **Mail**. The API documents Mail Orders, Mailboxes, Aliases, Autoreplies, Forwarders, Catchalls, Webhooks, API Tokens and Logs under `/api/mail/v1`.
+
+## Telegram and Discord for Channels
+
+Telegram and Discord are native direct Integration providers used by MSO Channels. Channel configuration never stores bot credentials.
+
+Telegram direct connections store the Bot API token plus an optional webhook secret. Verification uses Bot API `getMe`; the webhook secret becomes mandatory only when the connection is used for inbound Channels delivery.
+
+Discord direct connections store the bot token and may also store the non-secret application ID and Interactions Ed25519 public key. Verification uses Discord REST bot identity. The public key is required before signed Discord Interactions can be accepted. Gateway event ingestion is intentionally not implied by a verified Discord connection.
+
+The Channels application resolves an exact credential user + named connection. If no compatible connection exists, setup remains in Integrations rather than exposing a token field inside Channels. See [CHANNELS.md](./CHANNELS.md).
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index c92d66f6..ed83a889 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,13 @@
+## 2026-09-23 — Add native Channels for Telegram and Discord
+
+MSO now has a first-class **Channels** application and provider-neutral messaging runtime. Telegram and Discord are adapters over one shared channel contract rather than separate feature implementations. Channel records contain only routing metadata and exact native Integrations references; bot tokens and webhook secrets remain in Integrations.
+
+Telegram supports Bot API credential verification, outbound text, normalized webhook events and webhook-secret validation. Discord supports REST bot verification, outbound channel messages, signed Ed25519 Interactions including PING/PONG, and normalized command/component/modal events. Discord Gateway message ingestion is explicitly not claimed.
+
+Native Workflows gains `Channel Trigger` and `Channel Send` nodes. Verified inbound events use the existing Workflow Graph engine and durable session/run machinery instead of a parallel automation runtime. The Channels UI exposes connection health, enabled state, default target, workflow binding, provider inbound URL, test, edit/delete and test-message controls, with direct navigation back to Integrations when setup is missing.
+
+Focused provider/schema/store/API tests and TypeScript verification cover the new boundary. `docs/CHANNELS.md` records runtime, security and capability truth.
+
## 2026-09-23 — Isolate Termux installations inside Ubuntu PRoot
The Termux adapter now starts installation and the generated CLI launcher with a fresh guest environment, explicit Linux-only PATH and non-root owner. It rejects an Android Node/Bun runtime accidentally visible inside the guest, retains the legacy native launcher target while replacing its symlink, and supports bounded build workers, Node heap, resumable installs and a private persistent install log for low-memory tablets. Shell tests exercise the exact guest argv boundary, hostile inherited environment, argument forwarding and failed guest-runtime probes without installing packages. The launcher test reads its generated file directly instead of first checking filesystem metadata, avoiding a check/read race flagged by CodeQL.
diff --git a/docs/README.md b/docs/README.md
index f1f67e70..e5c65596 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -36,6 +36,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`CLI.md`](./CLI.md) | Generated `mso` CLI contract |
| [`INTEGRATION-PORTABILITY.md`](./INTEGRATION-PORTABILITY.md) | Reviewed JSON identity transfers, encrypted credentials, SC interoperability and receiver limits |
| [`INTEGRATIONS.md`](./INTEGRATIONS.md) | Native temporary credential forms, direct HTTPS secret submission, CLI and ChatGPT Page |
+| [`CHANNELS.md`](./CHANNELS.md) | Provider-neutral Telegram/Discord messaging, inbound verification, outbound send and Workflow bridge |
| [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs |
| [`BATONLY-FEDERATION.md`](./BATONLY-FEDERATION.md) | Pull-based Batonly capability federation worker, MSO/SI-Coder execution boundary, polling, security and acceptance contract |
| [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits |
diff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.md
index 90470b6e..1c785105 100644
--- a/docs/SLICE-CATALOG.md
+++ b/docs/SLICE-CATALOG.md
@@ -3,12 +3,12 @@
> **Current reference.** Counts are checked against the directory tree by
> `scripts/check-docs.mjs`; the directory remains the final authority.
-<!-- slice-catalog: slices=27 appshell-features=10 -->
+<!-- slice-catalog: slices=28 appshell-features=10 -->
Every application is a vertical slice under `frontend/slices/`. Host-facing slices use the
shared API/host seam rather than reaching arbitrary Node host APIs from client code.
-## Slices (27)
+## Slices (28)
| Slug | Purpose |
|---|---|
@@ -17,6 +17,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c
| `assistant` | Alfa assistant, agents/playbooks and tool activity |
| `auth` | Authentication UI/helpers |
| `camoufox-browser` | Remote Camoufox/noVNC Browser app |
+| `channels` | Provider-neutral Telegram/Discord channel configuration, status, send/test, inbound URLs and workflow binding |
| `code-editor` | Code/text editor with integrated terminal |
| `create-app` | Create App manifest authoring surface |
| `docs` | In-app documentation browser |
@@ -38,7 +39,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c
| `reel-editor` | Video/reel timeline editor |
| `shell-settings` | Shared shell settings UI primitives |
| `system-monitor` | Live metrics/processes plus service inventory/logs/allowlisted lifecycle and cache-only package updates |
-| `workflows` | Server-native automation editor with schedule/webhook triggers, flow control, private history/versions/variables and node-level logs |
+| `workflows` | Server-native automation editor with schedule/webhook/channel triggers, channel send, flow control, private history/versions/variables and node-level logs |
## AppShell feature directories (10)
diff --git a/frontend/slices/app-store/lib/system-catalog.ts b/frontend/slices/app-store/lib/system-catalog.ts
index 5acfe306..ddec7daa 100644
--- a/frontend/slices/app-store/lib/system-catalog.ts
+++ b/frontend/slices/app-store/lib/system-catalog.ts
@@ -19,6 +19,7 @@ import {
Cloud,
ServerCog,
Plug,
+ MessageSquareMore,
type LucideIcon,
} from "lucide-react";
@@ -44,6 +45,7 @@ export type SystemEntry = {
export const SYSTEM_CATALOG: SystemEntry[] = [
// ── Built-in apps ─────────────────────────────────────────────────────────
{ id: "integrations", title: "Integrations", kind: "app", icon: Plug, gradient: "var(--primary)", desc: "Manage native service accounts, connections, and private setup." },
+ { id: "channels", title: "Channels", kind: "app", icon: MessageSquareMore, gradient: "var(--primary)", desc: "Connect Telegram and Discord to MSO Workflows and outbound messaging." },
{ id: "files-manager", title: "Files", kind: "app", icon: Folder, gradient: "linear-gradient(160deg,#3aa0ff,#1f6dff)", desc: "Browse, upload, and manage host files." },
{ id: "browser", title: "Browser", kind: "app", icon: Globe, gradient: "linear-gradient(160deg,#22b1ff,#1666e0)", desc: "Tabbed web viewer — pages render in a sandboxed embedded frame." },
{ id: "code-editor", title: "Code", kind: "app", icon: Code, gradient: "linear-gradient(160deg,#7a5cff,#4f2fd6)", desc: "Edit host files in a tabbed code editor." },
diff --git a/frontend/slices/channels/app.test.ts b/frontend/slices/channels/app.test.ts
new file mode 100644
index 00000000..29a1dbf2
--- /dev/null
+++ b/frontend/slices/channels/app.test.ts
@@ -0,0 +1,24 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import { channelsApp } from "./index";
+
+describe("Channels shell feature", () => {
+ it("is a first-class dockable app registered in the shell and App Store", () => {
+ expect(channelsApp.id).toBe("channels");
+ expect(channelsApp.noDock).not.toBe(true);
+ expect(readFileSync("frontend/slices/os-shell/shell.manifest.ts", "utf8")).toContain('pin(withSlug(channelsApp, "channels"))');
+ expect(readFileSync("frontend/slices/app-store/lib/system-catalog.ts", "utf8")).toContain('id: "channels", title: "Channels", kind: "app"');
+ });
+
+ it("keeps bot secrets in Integrations and exposes test/send/workflow controls", () => {
+ const app = readFileSync("frontend/slices/channels/app.tsx", "utf8");
+ const editor = readFileSync("frontend/slices/channels/components/channel-editor.tsx", "utf8");
+ const card = readFileSync("frontend/slices/channels/components/channel-card.tsx", "utf8");
+ expect(app).toContain('data-slot="channels-feature"');
+ expect(editor).toContain('openWindow("integrations", "Integrations")');
+ expect(editor).not.toContain("botToken");
+ expect(card).toContain('action: "test"');
+ expect(card).toContain('action: "send"');
+ expect(editor).toContain("Inbound workflow");
+ });
+});
diff --git a/frontend/slices/channels/app.tsx b/frontend/slices/channels/app.tsx
new file mode 100644
index 00000000..154ddc93
--- /dev/null
+++ b/frontend/slices/channels/app.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { MessageSquareMore, Plus, Plug, RefreshCw, Workflow } from "lucide-react";
+import type { AppProps } from "@/features/appshell";
+import { AppFrame, openWindow } from "@/features/appshell";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { ChannelCard } from "./components/channel-card";
+import { ChannelEditor } from "./components/channel-editor";
+import { loadChannels, loadChannelWorkflows } from "./lib/api";
+import type { ChannelsSnapshot, ChannelView, WorkflowOption } from "./types";
+
+const empty: ChannelsSnapshot = { version: 1, revision: 0, channels: [], credentials: [], providers: [] };
+
+export default function ChannelsApp(_: AppProps) {
+ const [snapshot, setSnapshot] = useState<ChannelsSnapshot>(empty);
+ const [workflows, setWorkflows] = useState<WorkflowOption[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState("");
+ const [editor, setEditor] = useState<ChannelView | "new" | null>(null);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const [channels, graphs] = await Promise.all([loadChannels(), loadChannelWorkflows()]);
+ setSnapshot(channels);
+ setWorkflows(graphs);
+ setError("");
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "Could not load Channels.");
+ } finally { setLoading(false); }
+ }, []);
+
+ useEffect(() => {
+ const frame = requestAnimationFrame(() => void load());
+ window.addEventListener("focus", load);
+ return () => { cancelAnimationFrame(frame); window.removeEventListener("focus", load); };
+ }, [load]);
+
+ const workflowNames = useMemo(() => new Map(workflows.map((row) => [row.id, row.name])), [workflows]);
+ const toolbar = <div className="flex h-11 min-w-0 items-center gap-2 px-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2"><span className="text-sm font-semibold">Channels</span><Badge variant="outline">{snapshot.channels.length}</Badge></div>
+ </div>
+ <Button size="icon" variant="ghost" aria-label="Refresh channels" onClick={() => void load()}><RefreshCw className="size-4"/></Button>
+ <Button size="sm" variant="outline" onClick={() => openWindow("integrations", "Integrations")}><Plug className="mr-2 size-3"/>Integrations</Button>
+ <Button size="sm" onClick={() => setEditor("new")}><Plus className="mr-2 size-3"/>Add</Button>
+ </div>;
+
+ return <div data-slot="channels-feature" className="@container h-full min-h-0 min-w-0">
+ <AppFrame safeArea={false} className="h-full min-w-0 bg-background" toolbar={toolbar} bodyClassName="overflow-hidden">
+ <div className="h-full overflow-y-auto p-3 @min-[720px]:p-4">
+ {error ? <div role="alert" className="mb-3 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{error}</div> : null}
+ {snapshot.channels.length ? <div className="grid gap-3 @min-[840px]:grid-cols-2">
+ {snapshot.channels.map((row) => <ChannelCard
+ key={row.id}
+ row={row}
+ revision={snapshot.revision}
+ workflowName={row.workflowId ? workflowNames.get(row.workflowId) : undefined}
+ onEdit={() => setEditor(row)}
+ onReload={load}
+ />)}
+ </div> : <Empty loading={loading} hasCredentials={snapshot.credentials.length > 0} onAdd={() => setEditor("new")}/>}
+ </div>
+ </AppFrame>
+ <ChannelEditor
+ key={editor === "new" ? `new:${snapshot.revision}` : editor?.id ?? "closed"}
+ open={editor !== null}
+ onOpenChange={(open) => { if (!open) setEditor(null); }}
+ row={editor && editor !== "new" ? editor : null}
+ snapshot={snapshot}
+ workflows={workflows}
+ onSaved={load}
+ />
+ </div>;
+}
+
+function Empty({ loading, hasCredentials, onAdd }: { loading: boolean; hasCredentials: boolean; onAdd: () => void }) {
+ return <div className="grid min-h-[55vh] place-items-center">
+ <div className="w-full max-w-xl rounded-xl border bg-card p-5">
+ <div className="flex items-start gap-3"><div className="grid size-10 place-items-center rounded-lg border bg-muted/40"><MessageSquareMore className="size-5"/></div><div>
+ <h2 className="text-base font-semibold">{loading ? "Loading channels…" : "Connect MSO to a conversation channel"}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">Telegram and Discord share one channel contract. Credentials stay in Integrations; verified inbound events can start native Workflows.</p>
+ </div></div>
+ {!loading ? <div className="mt-4 flex flex-wrap gap-2">
+ {hasCredentials ? <Button onClick={onAdd}><Plus className="mr-2 size-3"/>Add channel</Button> : <Button onClick={() => openWindow("integrations", "Integrations")}><Plug className="mr-2 size-3"/>Set up bot connection</Button>}
+ <Button variant="outline" onClick={() => openWindow("workflows", "Workflows")}><Workflow className="mr-2 size-3"/>Open Workflows</Button>
+ </div> : null}
+ </div>
+ </div>;
+}
diff --git a/frontend/slices/channels/components/channel-card.tsx b/frontend/slices/channels/components/channel-card.tsx
new file mode 100644
index 00000000..827d511a
--- /dev/null
+++ b/frontend/slices/channels/components/channel-card.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { useState } from "react";
+import { Copy, Pencil, Send, TestTube2, Trash2, Workflow } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import { channelAction } from "../lib/api";
+import type { ChannelView } from "../types";
+
+function status(row: ChannelView) {
+ if (!row.enabled) return { label: "Disabled", variant: "outline" as const };
+ if (row.lastCheck && !row.lastCheck.ok) return { label: "Error", variant: "outline" as const, className: "text-destructive" };
+ if (!row.connection || row.connection.state === "missing" || row.connection.state === "incomplete") {
+ return { label: "Needs setup", variant: "outline" as const };
+ }
+ if (row.lastCheck?.ok || row.connection.state === "verified") return { label: "Connected", variant: "secondary" as const };
+ return { label: "Configured", variant: "outline" as const };
+}
+
+export function ChannelCard({
+ row,
+ revision,
+ workflowName,
+ onEdit,
+ onReload,
+}: {
+ row: ChannelView;
+ revision: number;
+ workflowName?: string;
+ onEdit: () => void;
+ onReload: () => Promise<void>;
+}) {
+ const [target, setTarget] = useState(row.defaultTarget ?? "");
+ const [text, setText] = useState("Hello from MSO");
+ const [busy, setBusy] = useState("");
+ const [message, setMessage] = useState("");
+ const state = status(row);
+ const inboundPath = `/api/v1/channels/${row.provider}/${row.id}`;
+
+ const run = async (name: string, body: Record<string, unknown>, reload = true) => {
+ setBusy(name); setMessage("");
+ try {
+ await channelAction(body);
+ setMessage(name === "send" ? "Message sent." : name === "test" ? "Connection verified." : "");
+ if (reload) await onReload();
+ } catch (cause) {
+ setMessage(cause instanceof Error ? cause.message : "Action failed.");
+ } finally { setBusy(""); }
+ };
+
+ return <article className="flex min-w-0 flex-col rounded-xl border bg-card">
+ <header className="flex items-start gap-3 border-b p-4">
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="truncate text-sm font-semibold">{row.name}</h3>
+ <Badge variant="outline" className="capitalize">{row.provider}</Badge>
+ <Badge variant={state.variant} className={state.className}>{state.label}</Badge>
+ </div>
+ <p className="mt-1 truncate text-xs text-muted-foreground">
+ {row.connection?.label ?? `${row.credential.user} / ${row.credential.connection}`}
+ </p>
+ </div>
+ <Switch
+ checked={row.enabled}
+ disabled={Boolean(busy)}
+ aria-label={`${row.name} enabled`}
+ onCheckedChange={(enabled) => void run("toggle", { action: "update", id: row.id, expectedRevision: revision, data: { enabled } })}
+ />
+ </header>
+
+ <div className="space-y-3 p-4">
+ <div className="grid gap-2 text-xs sm:grid-cols-2">
+ <Info label="Inbound" value={row.capabilities.inbound === "webhook" ? "Telegram webhook" : "Discord interactions"}/>
+ <Info label="Workflow" value={workflowName ?? (row.workflowId ? "Missing / inactive" : "Not linked")}/>
+ <Info label="Default target" value={row.defaultTarget || "Not set"}/>
+ <Info label="Last activity" value={row.lastActivityAt ? new Date(row.lastActivityAt).toLocaleString() : "No activity yet"}/>
+ </div>
+
+ <div className="rounded-lg border bg-muted/20 p-2.5">
+ <div className="flex items-center gap-2">
+ <code className="min-w-0 flex-1 truncate text-[10px]">{inboundPath}</code>
+ <Button size="icon" variant="ghost" className="size-7" aria-label="Copy inbound URL" onClick={() => void navigator.clipboard?.writeText(window.location.origin + inboundPath)}>
+ <Copy className="size-3"/>
+ </Button>
+ </div>
+ <p className="mt-1 text-[10px] text-muted-foreground">{row.capabilities.notes}</p>
+ </div>
+
+ <div className="grid gap-2 sm:grid-cols-[minmax(0,0.85fr)_minmax(0,1.6fr)_auto]">
+ <Input value={target} placeholder={row.provider === "telegram" ? "Chat ID" : "Channel ID"} onChange={(event) => setTarget(event.target.value)}/>
+ <Input value={text} maxLength={row.provider === "telegram" ? 4096 : 2000} placeholder="Test message" onChange={(event) => setText(event.target.value)}/>
+ <Button disabled={Boolean(busy) || !text.trim()} onClick={() => void run("send", { action: "send", id: row.id, target, text })}>
+ <Send className="mr-2 size-3"/>Send
+ </Button>
+ </div>
+
+ {row.lastCheck ? <p className={`text-xs ${row.lastCheck.ok ? "text-muted-foreground" : "text-destructive"}`}>{row.lastCheck.detail}</p> : null}
+ {message ? <p className="text-xs text-muted-foreground">{message}</p> : null}
+ </div>
+
+ <footer className="flex flex-wrap items-center gap-2 border-t px-4 py-3">
+ <Button size="sm" variant="outline" disabled={Boolean(busy)} onClick={() => void run("test", { action: "test", id: row.id })}>
+ <TestTube2 className="mr-2 size-3"/>Test
+ </Button>
+ {row.workflowId ? <Button size="sm" variant="ghost" disabled><Workflow className="mr-2 size-3"/>Linked</Button> : null}
+ <div className="flex-1"/>
+ <Button size="icon" variant="ghost" aria-label="Edit channel" onClick={onEdit}><Pencil className="size-3"/></Button>
+ <Button size="icon" variant="ghost" aria-label="Delete channel" disabled={Boolean(busy)} onClick={() => {
+ if (window.confirm(`Delete ${row.name}?`)) void run("delete", { action: "delete", id: row.id, expectedRevision: revision });
+ }}><Trash2 className="size-3"/></Button>
+ </footer>
+ </article>;
+}
+
+function Info({ label, value }: { label: string; value: string }) {
+ return <div className="min-w-0"><div className="text-[10px] uppercase tracking-wide text-muted-foreground">{label}</div><div className="mt-0.5 truncate font-medium">{value}</div></div>;
+}
diff --git a/frontend/slices/channels/components/channel-editor.tsx b/frontend/slices/channels/components/channel-editor.tsx
new file mode 100644
index 00000000..a14a3f67
--- /dev/null
+++ b/frontend/slices/channels/components/channel-editor.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { Plug } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import { FormDrawer, openWindow } from "@/features/appshell";
+import { channelAction } from "../lib/api";
+import type { ChannelsSnapshot, ChannelProviderId, ChannelView, WorkflowOption } from "../types";
+
+const selectClass = "h-9 w-full rounded-md border bg-background px-2 text-sm";
+const credentialValue = (user: string, connection: string) => `${user}::${connection}`;
+
+export function ChannelEditor({
+ open,
+ onOpenChange,
+ row,
+ snapshot,
+ workflows,
+ onSaved,
+}: {
+ open: boolean;
+ onOpenChange: (value: boolean) => void;
+ row: ChannelView | null;
+ snapshot: ChannelsSnapshot;
+ workflows: WorkflowOption[];
+ onSaved: () => Promise<void>;
+}) {
+ const initialProvider = row?.provider ?? "telegram";
+ const initialCredential = row
+ ? credentialValue(row.credential.user, row.credential.connection)
+ : (() => {
+ const first = snapshot.credentials.find((item) => item.provider === initialProvider);
+ return first ? credentialValue(first.user, first.id) : "";
+ })();
+
+ const [name, setName] = useState(row?.name ?? "");
+ const [provider, setProvider] = useState<ChannelProviderId>(initialProvider);
+ const [credential, setCredential] = useState(initialCredential);
+ const [target, setTarget] = useState(row?.defaultTarget ?? "");
+ const [workflowId, setWorkflowId] = useState(row?.workflowId ?? "");
+ const [enabled, setEnabled] = useState(row?.enabled ?? true);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+
+ const credentials = useMemo(
+ () => snapshot.credentials.filter((item) => item.provider === provider),
+ [provider, snapshot.credentials],
+ );
+
+ const changeProvider = (next: ChannelProviderId) => {
+ setProvider(next);
+ const first = snapshot.credentials.find((item) => item.provider === next);
+ setCredential(first ? credentialValue(first.user, first.id) : "");
+ };
+
+ const save = async () => {
+ const [user, connection] = credential.split("::");
+ if (!user || !connection) { setError("Choose an Integration connection first."); return; }
+ setBusy(true); setError("");
+ try {
+ const data = {
+ name,
+ provider,
+ credential: { user, connection },
+ enabled,
+ defaultTarget: target,
+ workflowId,
+ };
+ await channelAction(row
+ ? { action: "update", id: row.id, expectedRevision: snapshot.revision, data }
+ : { action: "create", data });
+ await onSaved();
+ onOpenChange(false);
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "Could not save channel.");
+ } finally { setBusy(false); }
+ };
+
+ return <FormDrawer open={open} onOpenChange={onOpenChange} size="md">
+ <FormDrawer.Header>
+ <FormDrawer.Title>{row ? "Edit channel" : "Add channel"}</FormDrawer.Title>
+ <FormDrawer.Description>
+ Channel configuration stores only connection references. Bot tokens remain in Integrations.
+ </FormDrawer.Description>
+ </FormDrawer.Header>
+ <FormDrawer.Body className="space-y-4">
+ <Field label="Name"><Input value={name} maxLength={120} placeholder="Support bot" onChange={(event) => setName(event.target.value)}/></Field>
+ <Field label="Provider">
+ <select className={selectClass} value={provider} onChange={(event) => changeProvider(event.target.value as ChannelProviderId)}>
+ <option value="telegram">Telegram</option><option value="discord">Discord</option>
+ </select>
+ </Field>
+ <Field label="Integration connection">
+ {credentials.length ? <select className={selectClass} value={credential} onChange={(event) => setCredential(event.target.value)}>
+ {credentials.map((item) => <option key={`${item.user}:${item.id}`} value={credentialValue(item.user, item.id)}>
+ {item.userLabel} / {item.label} · {item.state}
+ </option>)}
+ </select> : <div className="rounded-lg border border-dashed p-3">
+ <p className="text-xs text-muted-foreground">No {provider} bot connection exists yet.</p>
+ <Button className="mt-2" size="sm" variant="outline" onClick={() => openWindow("integrations", "Integrations")}><Plug className="mr-2 size-3"/>Open Integrations</Button>
+ </div>}
+ </Field>
+ <Field label={provider === "telegram" ? "Default chat ID / @channel" : "Default channel ID"}>
+ <Input value={target} placeholder={provider === "telegram" ? "-1001234567890" : "123456789012345678"} onChange={(event) => setTarget(event.target.value)}/>
+ </Field>
+ <Field label="Inbound workflow">
+ <select className={selectClass} value={workflowId} onChange={(event) => setWorkflowId(event.target.value)}>
+ <option value="">Receive only — no workflow</option>
+ {workflows.map((workflow) => <option key={workflow.id} value={workflow.id}>{workflow.name}</option>)}
+ </select>
+ </Field>
+ <label className="flex items-center justify-between rounded-lg border p-3">
+ <span><span className="block text-sm font-medium">Enabled</span><span className="text-xs text-muted-foreground">Allow send and verified inbound events.</span></span>
+ <Switch checked={enabled} onCheckedChange={setEnabled}/>
+ </label>
+ <div className="rounded-lg bg-muted/40 p-3 text-xs text-muted-foreground">
+ {provider === "telegram"
+ ? "Inbound Telegram requires a webhook secret on the selected Integration connection."
+ : "Inbound Discord uses the application public key to verify signed Interactions. Gateway message ingestion is intentionally not enabled."}
+ </div>
+ {error ? <p className="text-xs text-destructive">{error}</p> : null}
+ </FormDrawer.Body>
+ <FormDrawer.Footer>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>
+ <Button disabled={busy || !name.trim() || !credential} onClick={() => void save()}>{busy ? "Saving…" : "Save channel"}</Button>
+ </FormDrawer.Footer>
+ </FormDrawer>;
+}
+
+function Field({ label, children }: { label: string; children: React.ReactNode }) {
+ return <label className="block space-y-1.5"><span className="text-xs font-medium">{label}</span>{children}</label>;
+}
diff --git a/frontend/slices/channels/index.ts b/frontend/slices/channels/index.ts
new file mode 100644
index 00000000..62742edc
--- /dev/null
+++ b/frontend/slices/channels/index.ts
@@ -0,0 +1,11 @@
+import { MessageSquareMore } from "lucide-react";
+import type { AppDescriptor } from "@/features/appshell";
+
+export const channelsApp: AppDescriptor = {
+ id: "channels",
+ title: "Channels",
+ icon: MessageSquareMore,
+ gradient: "var(--primary)",
+ load: () => import("./app"),
+ defaultSize: { w: 1120, h: 760 },
+};
diff --git a/frontend/slices/channels/lib/api.ts b/frontend/slices/channels/lib/api.ts
new file mode 100644
index 00000000..2db220f1
--- /dev/null
+++ b/frontend/slices/channels/lib/api.ts
@@ -0,0 +1,23 @@
+import type { ChannelsSnapshot, WorkflowOption } from "../types";
+
+async function json<T>(input: RequestInfo, init?: RequestInit): Promise<T> {
+ const response = await fetch(input, {
+ ...init,
+ cache: "no-store",
+ headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
+ });
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(typeof body.error === "string" ? body.error : `request failed (${response.status})`);
+ return body as T;
+}
+
+export const loadChannels = () => json<ChannelsSnapshot>("/api/v1/channels");
+export const channelAction = (body: Record<string, unknown>) =>
+ json<unknown>("/api/v1/channels", { method: "POST", body: JSON.stringify(body) });
+
+export async function loadChannelWorkflows() {
+ const graphs = (await json<{ graphs: WorkflowOption[] }>("/api/v1/workflows")).graphs;
+ return graphs.filter((graph) =>
+ graph.status === "active" && graph.nodes.some((node) => node.type === "channel_trigger")
+ );
+}
diff --git a/frontend/slices/channels/types.ts b/frontend/slices/channels/types.ts
new file mode 100644
index 00000000..6bb33557
--- /dev/null
+++ b/frontend/slices/channels/types.ts
@@ -0,0 +1,39 @@
+export type ChannelProviderId = "telegram" | "discord";
+export type ChannelCredential = {
+ user: string;
+ userLabel: string;
+ id: string;
+ label: string;
+ provider: ChannelProviderId;
+ state: string;
+ missing: string[];
+ verifiedAt?: number | null;
+};
+export type ChannelView = {
+ id: string;
+ name: string;
+ provider: ChannelProviderId;
+ credential: { user: string; connection: string };
+ enabled: boolean;
+ defaultTarget?: string;
+ workflowId?: string;
+ createdAt: string;
+ updatedAt: string;
+ lastCheck?: { at: string; ok: boolean; detail: string };
+ lastActivityAt?: string;
+ connection?: { state?: string; error?: string; label?: string };
+ capabilities: { inbound: "webhook" | "interactions"; notes: string };
+};
+export type ChannelsSnapshot = {
+ version: 1;
+ revision: number;
+ channels: ChannelView[];
+ credentials: ChannelCredential[];
+ providers: Array<{ id: ChannelProviderId; title: string; notes: string }>;
+};
+export type WorkflowOption = {
+ id: string;
+ name: string;
+ status: string;
+ nodes: Array<{ type: string; config: Record<string, unknown> }>;
+};
diff --git a/frontend/slices/os-shell/channels-home-order.test.ts b/frontend/slices/os-shell/channels-home-order.test.ts
new file mode 100644
index 00000000..ab1b05d2
--- /dev/null
+++ b/frontend/slices/os-shell/channels-home-order.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from "vitest";
+import { BUILTIN_APPS } from "./shell.manifest";
+
+describe("Channels mobile-home registration", () => {
+ it("keeps Channels, Docs and Settings on the first 24-icon page", () => {
+ const index = (slug: string) => BUILTIN_APPS.findIndex((app) => app.slug === slug);
+ expect(index("channels")).toBeGreaterThanOrEqual(0);
+ expect(index("channels")).toBeLessThan(24);
+ expect(index("docs")).toBeGreaterThanOrEqual(0);
+ expect(index("docs")).toBeLessThan(24);
+ expect(index("settings")).toBeGreaterThanOrEqual(0);
+ expect(index("settings")).toBeLessThan(24);
+ expect(index("links")).toBeGreaterThanOrEqual(24);
+ });
+});
diff --git a/frontend/slices/os-shell/shell.manifest.ts b/frontend/slices/os-shell/shell.manifest.ts
index 91786b6a..a7bcec8d 100644
--- a/frontend/slices/os-shell/shell.manifest.ts
+++ b/frontend/slices/os-shell/shell.manifest.ts
@@ -21,6 +21,7 @@ import { osSettingsApp } from "@/features/os-settings";
import { quicklinksApp } from "@/features/quicklinks";
import { docsApp } from "@/features/docs";
import { integrationsApp } from "@/features/integrations";
+import { channelsApp } from "@/features/channels";
import { workflowsApp } from "@/features/workflows";
import { n8nApp } from "@/features/n8n";
import { organizationApp } from "@/features/organization";
@@ -70,16 +71,19 @@ export const BUILTIN_APPS: AppDescriptor[] = [
withSlug(withArtwork(openclawApp), "openclaw"),
withSlug(withArtwork(nineRouterApp), "9router"),
pin(withSlug(integrationsApp, "connections")),
+ pin(withSlug(channelsApp, "channels")),
pin(withSlug(withArtwork(workflowsApp), "workflows")),
pin(withSlug(withArtwork(n8nApp), "n8n")),
withSlug(withArtwork(organizationApp), "organization"),
withSlug(withArtwork(dokployApp), "dokploy"),
withSlug(withArtwork(cloudflareApp), "cloudflare"),
- withSlug(withArtwork(quicklinksApp), "links"),
+ // Keep Docs + Settings on the first 24-icon mobile home page. Quicklinks is
+ // non-pinned and may begin page 2 as the built-in catalog grows.
// Docs is deliberately dockable, not noDock: for a signed-out visitor it is the
// only app that explains what they are looking at and how to get their own.
withSlug(withArtwork(docsApp), "docs"),
pin(withSlug(withArtwork(osSettingsApp), "settings")),
+ withSlug(withArtwork(quicklinksApp), "links"),
];
// Shell features — the generic brand-free set now lives INSIDE the appshell
diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsx
index bfa945bb..03ce88b9 100644
--- a/frontend/slices/workflows/components/workflow-inspector.tsx
+++ b/frontend/slices/workflows/components/workflow-inspector.tsx
@@ -21,7 +21,7 @@ function JsonField({label,value,onChange}:{label:string;value:unknown;onChange:(
export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph}:{graph:WorkflowGraph;graphs:WorkflowGraph[];node:WorkflowGraphNode|null;onNode:(node:WorkflowGraphNode)=>void;onDeleteNode:(id:string)=>void;onGraph:(graph:WorkflowGraph)=>void;}){
const[advancedError,setAdvancedError]=useState("");
const outgoing=useMemo(()=>node?graph.edges.filter((edge)=>edge.source===node.id):[],[graph.edges,node]);
- if(!node){const tags=graph.metadata.tags?.join(", ")??"";return <div className="space-y-4 p-3 text-xs"><div className="font-semibold">Workflow settings</div><Field label="Description"><Textarea value={graph.description} onChange={(e)=>onGraph({...graph,description:e.target.value})}/></Field><Field label="Folder"><Input value={graph.metadata.folder??""} placeholder="Automation / Operations" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,folder:e.target.value||undefined}})}/></Field><Field label="Tags"><Input value={tags} placeholder="deploy, qa, daily" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,tags:e.target.value.split(",").map((v)=>v.trim()).filter(Boolean).slice(0,32)}})}/></Field><Field label="Timezone"><Input value={graph.metadata.timezone??"UTC"} placeholder="UTC" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,timezone:e.target.value||undefined}})}/></Field><Field label="Error workflow"><select className={selectClass} value={graph.metadata.errorWorkflowId??""} onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,errorWorkflowId:e.target.value||undefined}})}><option value="">None</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><p className="text-[10px] text-muted-foreground">Active schedule/webhook triggers execute server-side. Workflow data, versions, runs and variables stay private to the authenticated principal.</p></div>;}
+ if(!node){const tags=graph.metadata.tags?.join(", ")??"";return <div className="space-y-4 p-3 text-xs"><div className="font-semibold">Workflow settings</div><Field label="Description"><Textarea value={graph.description} onChange={(e)=>onGraph({...graph,description:e.target.value})}/></Field><Field label="Folder"><Input value={graph.metadata.folder??""} placeholder="Automation / Operations" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,folder:e.target.value||undefined}})}/></Field><Field label="Tags"><Input value={tags} placeholder="deploy, qa, daily" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,tags:e.target.value.split(",").map((v)=>v.trim()).filter(Boolean).slice(0,32)}})}/></Field><Field label="Timezone"><Input value={graph.metadata.timezone??"UTC"} placeholder="UTC" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,timezone:e.target.value||undefined}})}/></Field><Field label="Error workflow"><select className={selectClass} value={graph.metadata.errorWorkflowId??""} onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,errorWorkflowId:e.target.value||undefined}})}><option value="">None</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><p className="text-[10px] text-muted-foreground">Active schedule, webhook and Channel triggers execute server-side. Workflow data, versions, runs and variables stay private to the authenticated principal.</p></div>;}
const projectValue=String(node.config.project??graph.metadata.project??"");
const patch=(next:Partial<WorkflowGraphNode>)=>onNode({...node,...next}),setConfig=(key:string,value:unknown)=>patch({config:{...node.config,[key]:value}}),removeConfig=(key:string)=>{const next={...node.config};delete next[key];patch({config:next});};
const patchEdge=(id:string,patch:Partial<WorkflowGraph["edges"][number]>)=>onGraph({...graph,edges:graph.edges.map((edge)=>edge.id===id?{...edge,...patch}:edge)});
@@ -29,18 +29,18 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph
const applyAdvanced=(text:string)=>{try{const value=JSON.parse(text);if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Config must be an object");patch({config:value as Record<string,unknown>});setAdvancedError("");}catch(e){setAdvancedError(e instanceof Error?e.message:"Invalid JSON");}};
const openTarget=async()=>{const resolved=await resolveNode(graph.id,node.id);openWindow("files-manager",resolved.name,undefined,{path:resolved.path},{multi:true});};
const copyWebhook=()=>void navigator.clipboard?.writeText(`${window.location.origin}/api/v1/workflows/webhook/${graph.id}/${node.id}`);
- const actionNode=["tool","project_function","project_mcp","integration","script","agent","subflow","loop","repeat","data_table"].includes(node.type);
+ const actionNode=["tool","project_function","project_mcp","integration","channel_send","script","agent","subflow","loop","repeat","data_table"].includes(node.type);
return <div className="space-y-4 p-3 text-xs">
<Field label="Name"><Input value={node.name} onChange={(e)=>patch({name:e.target.value})}/></Field>
<Field label="Type"><select className={selectClass} value={node.type} onChange={(e)=>patch({type:e.target.value as WorkflowGraphNodeType})}>{WORKFLOW_GRAPH_NODE_TYPES.map((type)=><option key={type} value={type}>{type}</option>)}</select></Field>
{node.type==="schedule"&&<><Field label="Schedule mode"><select className={selectClass} value={String(node.config.mode??"interval")} onChange={(e)=>setConfig("mode",e.target.value)}><option value="interval">Interval</option><option value="cron">Cron</option></select></Field>{node.config.mode==="cron"?<Field label="Cron (5 fields)"><Input value={String(node.config.cron??"0 * * * *")} onChange={(e)=>setConfig("cron",e.target.value)}/></Field>:<Field label="Every minutes"><Input type="number" min={1} max={10080} value={number(node.config.everyMinutes,60)} onChange={(e)=>setConfig("everyMinutes",Number(e.target.value))}/></Field>}<Field label="Timezone override"><Input value={String(node.config.timezone??"")} placeholder={graph.metadata.timezone??"UTC"} onChange={(e)=>setConfig("timezone",e.target.value)}/></Field></>}
{node.type==="webhook"&&<><Field label="Methods"><Input value={Array.isArray(node.config.methods)?node.config.methods.join(", "):"POST"} onChange={(e)=>setConfig("methods",e.target.value.split(",").map((v)=>v.trim().toUpperCase()).filter(Boolean))}/></Field><Field label="Response"><select className={selectClass} value={String(node.config.responseMode??"onReceived")} onChange={(e)=>setConfig("responseMode",e.target.value)}><option value="onReceived">202 immediately</option><option value="lastNode">Wait for output</option></select></Field><Field label="Auth variable"><Input value={String(node.config.authVariable??"")} placeholder="WEBHOOK_TOKEN (optional)" onChange={(e)=>e.target.value?setConfig("authVariable",e.target.value.toUpperCase()):removeConfig("authVariable")}/></Field><div className="rounded border p-2"><div className="break-all font-mono text-[10px]">/api/v1/workflows/webhook/{graph.id}/{node.id}</div><Button className="mt-2" size="sm" variant="outline" onClick={copyWebhook}><Copy className="mr-1 size-3"/>Copy URL</Button></div></>}
- {node.type==="agent"&&<WorkflowAgentSeatField value={String(node.config.orgSeatId??"")} onChange={(value)=>value?setConfig("orgSeatId",value):removeConfig("orgSeatId")}/>}
+ {node.type==="channel_trigger"&&<><Field label="Channel ID"><Input value={String(node.config.channelId??"")} placeholder="Leave blank for any channel bound to this workflow" onChange={(e)=>e.target.value?setConfig("channelId",e.target.value):removeConfig("channelId")}/></Field><Button size="sm" variant="outline" className="w-full" onClick={()=>openWindow("channels","Channels")}>Open Channels</Button></>}\n {node.type==="agent"&&<WorkflowAgentSeatField value={String(node.config.orgSeatId??"")} onChange={(value)=>value?setConfig("orgSeatId",value):removeConfig("orgSeatId")}/>}
{(node.type==="project"||node.type==="folder"||node.type==="knowledge"||(node.type==="agent"&&!node.config.orgSeatId)||node.type==="script"||node.type==="project_function"||node.type==="project_mcp"||node.type==="subflow"||(node.type==="memory"&&node.config.scope==="project"))&&<Field label="Project"><Input value={String(node.config.project??graph.metadata.project??"")} placeholder="Canonical project id/name" onChange={(e)=>setConfig("project",e.target.value)}/></Field>}
{node.type==="folder"&&<Field label="Relative path"><Input value={String(node.config.path??".")} onChange={(e)=>setConfig("path",e.target.value)}/></Field>}
{node.type==="script"&&<WorkflowScriptField project={projectValue} value={String(node.config.script_id??"")} onChange={(value)=>value?setConfig("script_id",value):removeConfig("script_id")}/>}
{node.type==="tool"&&<><WorkflowToolDirectoryField value={String(node.config.tool??"")} onChange={(value)=>setConfig("tool",value)}/><JsonField label="Arguments JSON" value={node.config.arguments??{}} onChange={(value)=>setConfig("arguments",value)}/></>}
- {node.type==="integration"&&<>{["user","provider","connection","operation"].map((key)=><Field key={key} label={key[0]!.toUpperCase()+key.slice(1)}><Input value={String(node.config[key]??"")} onChange={(e)=>setConfig(key,e.target.value)}/></Field>)}</>}
+ {node.type==="channel_send"&&<><Field label="Channel ID"><Input value={String(node.config.channelId??"")} placeholder="Channel UUID from Channels" onChange={(e)=>setConfig("channelId",e.target.value)}/></Field><Field label="Target override"><Input value={String(node.config.target??"")} placeholder="Use channel default when empty" onChange={(e)=>e.target.value?setConfig("target",e.target.value):removeConfig("target")}/></Field><JsonField label="Text / binding JSON" value={node.config.text??{"$ref":"input.event.text"}} onChange={(value)=>setConfig("text",value)}/><Button size="sm" variant="outline" className="w-full" onClick={()=>openWindow("channels","Channels")}>Open Channels</Button></>}\n {node.type==="integration"&&<>{["user","provider","connection","operation"].map((key)=><Field key={key} label={key[0]!.toUpperCase()+key.slice(1)}><Input value={String(node.config[key]??"")} onChange={(e)=>setConfig(key,e.target.value)}/></Field>)}</>}
{node.type==="agent"&&<Field label="Agent objective"><Textarea value={String(node.config.message??"")} onChange={(e)=>setConfig("message",e.target.value)}/></Field>}
{node.type==="subflow"&&<><Field label="Workflow graph"><select className={selectClass} value={String(node.config.workflowId??"")} onChange={(e)=>e.target.value?setConfig("workflowId",e.target.value):removeConfig("workflowId")}><option value="">Legacy project flow</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field>{!node.config.workflowId&&<Field label="Legacy flow id"><Input value={String(node.config.flow??"")} onChange={(e)=>setConfig("flow",e.target.value)}/></Field>}</>}
{node.type==="repeat"&&<><Field label="Workflow to repeat"><select className={selectClass} value={String(node.config.workflowId??"")} onChange={(e)=>e.target.value?setConfig("workflowId",e.target.value):removeConfig("workflowId")}><option value="">Select saved workflow</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><JsonField label="Input JSON / bindings" value={node.config.input??{}} onChange={(value)=>setConfig("input",value)}/><Field label="Condition path"><Input value={String(node.config.path??"result.output")} placeholder="result.output.ok" onChange={(e)=>setConfig("path",e.target.value)}/></Field><label className="flex items-center justify-between"><span>Compare exact value</span><Switch checked={Object.hasOwn(node.config,"equals")} onCheckedChange={(checked)=>checked?setConfig("equals",true):removeConfig("equals")}/></label>{Object.hasOwn(node.config,"equals")&&<JsonField label="Expected JSON" value={node.config.equals} onChange={(value)=>setConfig("equals",value)}/>}<Field label="Max iterations"><Input type="number" min={1} max={50} value={number(node.config.maxIterations,5)} onChange={(e)=>setConfig("maxIterations",Number(e.target.value))}/></Field><Field label="Delay between iterations ms"><Input type="number" min={0} max={600000} value={number(node.config.delayMs,1000)} onChange={(e)=>setConfig("delayMs",Number(e.target.value))}/></Field><Field label="Max repeat duration ms"><Input type="number" min={1000} max={840000} value={number(node.config.maxDurationMs,600000)} onChange={(e)=>setConfig("maxDurationMs",Number(e.target.value))}/></Field><p className="text-[10px] text-muted-foreground">Each child run receives <code>input.repeat.iteration</code> and the previous iteration output. Route <code>done</code> when the condition matches or <code>exhausted</code> when limits are reached.</p></>}
@@ -57,7 +57,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph
{(node.type==="project"||node.type==="folder")&&<Button variant="secondary" size="sm" className="w-full" onClick={()=>void openTarget()}><FolderOpen className="mr-2 size-3"/>Open real folder</Button>}
<details><summary className="cursor-pointer font-medium">Advanced config JSON</summary><div className="mt-2 space-y-2"><AdvancedConfig key={JSON.stringify(node.config)} value={node.config} onApply={applyAdvanced}/>{advancedError&&<p className="text-destructive">{advancedError}</p>}</div></details>
<div className="space-y-2"><div className="font-medium">Connections</div>{outgoing.map((edge)=>{
- const target=graph.nodes.find((item)=>item.id===edge.target),reverseBlocked=["manual","schedule","webhook"].includes(node.type)||target?.type==="output";
+ const target=graph.nodes.find((item)=>item.id===edge.target),reverseBlocked=["manual","schedule","webhook","channel_trigger"].includes(node.type)||target?.type==="output";
return <div key={edge.id} className="space-y-2 rounded border p-2"><div className="flex items-center gap-2"><span className="min-w-0 flex-1 truncate">{edge.sourceHandle?`${edge.sourceHandle} → `:"→ "}{target?.name??edge.target}</span><Button size="icon" variant="ghost" title="Reverse direction" aria-label={`Reverse ${node.name} to ${target?.name??edge.target}`} disabled={reverseBlocked} onClick={()=>reverseEdge(edge.id)}><ArrowLeftRight className="size-3"/></Button><Button size="icon" variant="ghost" aria-label={`Delete connection to ${target?.name??edge.target}`} onClick={()=>onGraph({...graph,edges:graph.edges.filter((item)=>item.id!==edge.id)})}><Trash2 className="size-3"/></Button></div><div className="grid grid-cols-[minmax(0,1fr)_auto] items-end gap-2"><Field label="Line style"><select className={selectClass} value={edge.style??"auto"} onChange={(e)=>patchEdge(edge.id,{style:e.target.value==="auto"?undefined:e.target.value as "solid"|"dashed"})}><option value="auto">Auto</option><option value="solid">Solid</option><option value="dashed">Dashed</option></select></Field><label className="flex h-9 items-center gap-2"><Switch checked={!edge.disabled} onCheckedChange={(checked)=>patchEdge(edge.id,{disabled:checked?undefined:true})}/><span>Active</span></label></div>{reverseBlocked?<p className="text-[9px] text-muted-foreground">Reverse is blocked when it would target a trigger or make Output a source.</p>:null}</div>;
})}<p className="text-[10px] text-muted-foreground">Click an edge to focus its source node. Style is visual; Active controls execution/topology. Reverse swaps execution direction and is validated on save.</p></div>
<Button variant="destructive" size="sm" className="w-full" onClick={()=>onDeleteNode(node.id)}><Trash2 className="mr-2 size-3"/>Delete node</Button>
diff --git a/lib/channels/errors.ts b/lib/channels/errors.ts
new file mode 100644
index 00000000..3fb8a6bd
--- /dev/null
+++ b/lib/channels/errors.ts
@@ -0,0 +1,9 @@
+export class ChannelError extends Error {
+ constructor(public readonly code: string, public readonly status = 400) {
+ super(code);
+ }
+}
+
+export function channelError(error: unknown): ChannelError {
+ return error instanceof ChannelError ? error : new ChannelError("channel_operation_failed", 400);
+}
diff --git a/lib/channels/index.ts b/lib/channels/index.ts
new file mode 100644
index 00000000..57026be9
--- /dev/null
+++ b/lib/channels/index.ts
@@ -0,0 +1,5 @@
+export * from "./types";
+export * from "./errors";
+export * from "./registry";
+export * from "./service";
+export * from "./workflow";
diff --git a/lib/channels/integration-contract.test.ts b/lib/channels/integration-contract.test.ts
new file mode 100644
index 00000000..812a9b1c
--- /dev/null
+++ b/lib/channels/integration-contract.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import { connectionCatalog } from "@/lib/infra/connection-registry";
+import { normalizeInfraValues } from "@/lib/infra/catalog";
+
+describe("channel integration providers", () => {
+ it("publishes Telegram and Discord direct credentials with secret metadata", () => {
+ const catalog = connectionCatalog();
+ const telegram = catalog.find((row) => row.id === "telegram")!;
+ const discord = catalog.find((row) => row.id === "discord")!;
+ expect(telegram.sources[0]?.methods[0]?.fields.find((field) => field.key === "botToken")?.secret).toBe(true);
+ expect(telegram.sources[0]?.methods[0]?.fields.find((field) => field.key === "webhookSecret")?.secret).toBe(true);
+ expect(discord.sources[0]?.methods[0]?.fields.find((field) => field.key === "botToken")?.secret).toBe(true);
+ expect(discord.sources[0]?.methods[0]?.fields.find((field) => field.key === "publicKey")?.secret).toBe(false);
+ });
+
+ it("rejects malformed provider identity fields before persistence", () => {
+ expect(() => normalizeInfraValues("telegram", { botToken: "bad token" })).toThrow("Telegram bot token format");
+ expect(() => normalizeInfraValues("discord", { botToken: "A".repeat(32), publicKey: "nope" })).toThrow("Discord publicKey");
+ });
+});
diff --git a/lib/channels/providers.test.ts b/lib/channels/providers.test.ts
new file mode 100644
index 00000000..41f1a7ce
--- /dev/null
+++ b/lib/channels/providers.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { generateKeyPairSync, sign } from "node:crypto";
+import { normalizeTelegramUpdate, verifyTelegramSecret } from "./providers/telegram";
+import { normalizeDiscordInteraction, verifyDiscordSignature } from "./providers/discord";
+
+describe("channel provider verification", () => {
+ it("validates Telegram webhook secrets and normalizes messages", () => {
+ const values = { webhookSecret: "secret_123" };
+ expect(verifyTelegramSecret(values, "secret_123")).toBe(true);
+ expect(verifyTelegramSecret(values, "wrong")).toBe(false);
+ expect(normalizeTelegramUpdate({
+ update_id: 42,
+ message: { text: "hello", chat: { id: -1001 }, from: { id: 7 } },
+ })).toMatchObject({ provider: "telegram", eventId: "42", kind: "message", target: "-1001", sender: "7", text: "hello" });
+ });
+
+ it("verifies Discord Ed25519 signatures and normalizes commands", () => {
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
+ const der = publicKey.export({ format: "der", type: "spki" });
+ const publicKeyHex = Buffer.from(der).subarray(-32).toString("hex");
+ const timestamp = "1727000000";
+ const body = JSON.stringify({ id: "123456789012345678", type: 2, application_id: "222222222222222222", channel_id: "333333333333333333", data: { name: "ask" }, member: { user: { id: "444444444444444444" } } });
+ const signature = sign(null, Buffer.from(timestamp + body), privateKey).toString("hex");
+
+ expect(verifyDiscordSignature({ publicKey: publicKeyHex }, timestamp, signature, body)).toBe(true);
+ expect(verifyDiscordSignature({ publicKey: publicKeyHex }, timestamp, "00".repeat(64), body)).toBe(false);
+ expect(normalizeDiscordInteraction(JSON.parse(body))).toMatchObject({
+ provider: "discord", kind: "command", text: "ask", target: "333333333333333333", sender: "444444444444444444",
+ });
+ });
+});
diff --git a/lib/channels/providers/discord.test.ts b/lib/channels/providers/discord.test.ts
new file mode 100644
index 00000000..b035defb
--- /dev/null
+++ b/lib/channels/providers/discord.test.ts
@@ -0,0 +1,34 @@
+import { generateKeyPairSync, sign } from "node:crypto";
+import { describe, expect, it } from "vitest";
+import { normalizeDiscordInteraction, verifyDiscordSignature } from "./discord";
+
+describe("discord channel adapter", () => {
+ it("verifies Discord Ed25519 interaction signatures", () => {
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
+ const spki = publicKey.export({ format: "der", type: "spki" });
+ const publicKeyHex = Buffer.from(spki).subarray(-32).toString("hex");
+ const timestamp = "1700000000";
+ const body = JSON.stringify({ id: "123456789012345678", application_id: "111111111111111111", type: 1 });
+ const signature = sign(null, Buffer.from(timestamp + body), privateKey).toString("hex");
+ expect(verifyDiscordSignature({ publicKey: publicKeyHex }, timestamp, signature, body)).toBe(true);
+ expect(verifyDiscordSignature({ publicKey: publicKeyHex }, timestamp, signature, body + "x")).toBe(false);
+ });
+
+ it("normalizes commands to the shared inbound event contract", () => {
+ const event = normalizeDiscordInteraction({
+ id: "123456789012345678",
+ type: 2,
+ channel_id: "222222222222222222",
+ member: { user: { id: "333333333333333333" } },
+ data: { name: "deploy" },
+ });
+ expect(event).toMatchObject({
+ provider: "discord",
+ eventId: "123456789012345678",
+ kind: "command",
+ target: "222222222222222222",
+ sender: "333333333333333333",
+ text: "deploy",
+ });
+ });
+});
diff --git a/lib/channels/providers/discord.ts b/lib/channels/providers/discord.ts
new file mode 100644
index 00000000..28520ce2
--- /dev/null
+++ b/lib/channels/providers/discord.ts
@@ -0,0 +1,82 @@
+import { createPublicKey, verify } from "node:crypto";
+import { request } from "@/lib/infra/http";
+import { ChannelError } from "../errors";
+import type { ChannelInboundEvent } from "../types";
+import { validateTarget } from "../schema";
+
+const BOT_TOKEN = /^[^\s\x00-\x1f\x7f]{24,256}$/;
+const PUBLIC_KEY = /^[0-9a-f]{64}$/i;
+const SPKI_ED25519_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
+
+function token(values: Record<string, string>) {
+ const value = values.botToken;
+ if (!value || !BOT_TOKEN.test(value)) throw new ChannelError("discord_not_configured", 409);
+ return value;
+}
+
+const headers = (values: Record<string, string>) => ({
+ authorization: `Bot ${token(values)}`,
+ accept: "application/json",
+ "user-agent": "MSO-Channels/1.0",
+});
+
+export async function verifyDiscord(values: Record<string, string>) {
+ const response = await request("https://discord.com/api/v10/users/@me", { headers: headers(values) });
+ const body = response.body as { id?: string; username?: string } | null;
+ if (!response.ok || !body?.id) throw new ChannelError(`discord_http_${response.status || 502}`, 502);
+ return { detail: `Discord bot verified as ${body.username ?? body.id}`, identity: body.id };
+}
+
+export async function sendDiscordText(values: Record<string, string>, target: string, text: string) {
+ validateTarget("discord", target);
+ if (!text || text.length > 2000) throw new ChannelError("invalid_message_text");
+ const response = await request(`https://discord.com/api/v10/channels/${target}/messages`, {
+ method: "POST",
+ headers: { ...headers(values), "content-type": "application/json" },
+ body: JSON.stringify({ content: text }),
+ });
+ const body = response.body as { id?: string } | null;
+ if (!response.ok || !body?.id) throw new ChannelError(`discord_http_${response.status || 502}`, 502);
+ return { messageId: body.id };
+}
+
+export function verifyDiscordSignature(values: Record<string, string>, timestamp: string | null, signature: string | null, body: string) {
+ const keyHex = values.publicKey;
+ if (!keyHex || !PUBLIC_KEY.test(keyHex) || !timestamp || !signature || !/^[0-9a-f]{128}$/i.test(signature)) return false;
+ try {
+ const key = createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, Buffer.from(keyHex, "hex")]), format: "der", type: "spki" });
+ return verify(null, Buffer.from(timestamp + body), key, Buffer.from(signature, "hex"));
+ } catch {
+ return false;
+ }
+}
+
+export function normalizeDiscordInteraction(raw: unknown): ChannelInboundEvent {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new ChannelError("invalid_discord_interaction");
+ const row = raw as Record<string, unknown>;
+ const id = row.id;
+ if (typeof id !== "string") throw new ChannelError("invalid_discord_interaction");
+ const data = row.data as Record<string, unknown> | undefined;
+ const member = row.member as Record<string, unknown> | undefined;
+ const memberUser = member?.user as Record<string, unknown> | undefined;
+ const user = (row.user as Record<string, unknown> | undefined) ?? memberUser;
+ const type = Number(row.type);
+ const kind = type === 2 ? "command" : type === 3 ? "component" : type === 5 ? "modal" : "interaction";
+ const text = typeof data?.name === "string" ? data.name : typeof data?.custom_id === "string" ? data.custom_id : undefined;
+ return {
+ provider: "discord",
+ eventId: id,
+ kind,
+ ...(typeof row.channel_id === "string" ? { target: row.channel_id } : {}),
+ ...(typeof user?.id === "string" ? { sender: user.id } : {}),
+ ...(text ? { text } : {}),
+ receivedAt: new Date().toISOString(),
+ raw,
+ };
+}
+
+export function discordApplicationMatches(values: Record<string, string>, raw: unknown) {
+ if (!values.applicationId) return true;
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
+ return (raw as Record<string, unknown>).application_id === values.applicationId;
+}
diff --git a/lib/channels/providers/telegram.test.ts b/lib/channels/providers/telegram.test.ts
new file mode 100644
index 00000000..c1fa602a
--- /dev/null
+++ b/lib/channels/providers/telegram.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { normalizeTelegramUpdate, verifyTelegramSecret } from "./telegram";
+
+describe("telegram channel adapter", () => {
+ it("validates the configured webhook secret with constant-time semantics", () => {
+ const values = { webhookSecret: "secret_123" };
+ expect(verifyTelegramSecret(values, "secret_123")).toBe(true);
+ expect(verifyTelegramSecret(values, "secret_124")).toBe(false);
+ expect(verifyTelegramSecret({}, "secret_123")).toBe(false);
+ });
+
+ it("normalizes message updates without changing provider payload semantics", () => {
+ const event = normalizeTelegramUpdate({
+ update_id: 42,
+ message: { text: "hello", chat: { id: -100123 }, from: { id: 7 } },
+ });
+ expect(event).toMatchObject({
+ provider: "telegram",
+ eventId: "42",
+ kind: "message",
+ target: "-100123",
+ sender: "7",
+ text: "hello",
+ });
+ });
+});
diff --git a/lib/channels/providers/telegram.ts b/lib/channels/providers/telegram.ts
new file mode 100644
index 00000000..894d373a
--- /dev/null
+++ b/lib/channels/providers/telegram.ts
@@ -0,0 +1,71 @@
+import { timingSafeEqual } from "node:crypto";
+import { request } from "@/lib/infra/http";
+import { ChannelError } from "../errors";
+import type { ChannelInboundEvent } from "../types";
+import { validateTarget } from "../schema";
+
+const TOKEN = /^\d{5,16}:[A-Za-z0-9_-]{20,}$/;
+const SECRET = /^[A-Za-z0-9_-]{1,256}$/;
+
+function token(values: Record<string, string>) {
+ const value = values.botToken;
+ if (!value || !TOKEN.test(value)) throw new ChannelError("telegram_not_configured", 409);
+ return value;
+}
+
+function api(values: Record<string, string>, method: string) {
+ return `https://api.telegram.org/bot${token(values)}/${method}`;
+}
+
+export async function verifyTelegram(values: Record<string, string>) {
+ const response = await request(api(values, "getMe"), { headers: { accept: "application/json" } });
+ const body = response.body as { ok?: boolean; result?: { id?: number; username?: string } } | null;
+ if (!response.ok || !body?.ok || !body.result?.id) throw new ChannelError(`telegram_http_${response.status || 502}`, 502);
+ return { detail: `Telegram bot verified as @${body.result.username ?? body.result.id}`, identity: String(body.result.id) };
+}
+
+export async function sendTelegramText(values: Record<string, string>, target: string, text: string) {
+ validateTarget("telegram", target);
+ if (!text || text.length > 4096) throw new ChannelError("invalid_message_text");
+ const response = await request(api(values, "sendMessage"), {
+ method: "POST",
+ headers: { "content-type": "application/json", accept: "application/json" },
+ body: JSON.stringify({ chat_id: target, text }),
+ });
+ const body = response.body as { ok?: boolean; result?: { message_id?: number } } | null;
+ if (!response.ok || !body?.ok) throw new ChannelError(`telegram_http_${response.status || 502}`, 502);
+ return { messageId: body.result?.message_id ? String(body.result.message_id) : null };
+}
+
+export function verifyTelegramSecret(values: Record<string, string>, supplied: string | null) {
+ const expected = values.webhookSecret;
+ if (!expected || !SECRET.test(expected) || !supplied || !SECRET.test(supplied)) return false;
+ const a = Buffer.from(expected), b = Buffer.from(supplied);
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
+export function normalizeTelegramUpdate(raw: unknown): ChannelInboundEvent {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new ChannelError("invalid_telegram_update");
+ const update = raw as Record<string, unknown>;
+ const updateId = update.update_id;
+ if (typeof updateId !== "number" && typeof updateId !== "string") throw new ChannelError("invalid_telegram_update");
+
+ const message = (update.message ?? update.channel_post ?? update.edited_message) as Record<string, unknown> | undefined;
+ const callback = update.callback_query as Record<string, unknown> | undefined;
+ const callbackMessage = callback?.message as Record<string, unknown> | undefined;
+ const source = message ?? callbackMessage;
+ const chat = source?.chat as Record<string, unknown> | undefined;
+ const from = (message?.from ?? callback?.from) as Record<string, unknown> | undefined;
+ const text = typeof message?.text === "string" ? message.text : typeof callback?.data === "string" ? callback.data : undefined;
+
+ return {
+ provider: "telegram",
+ eventId: String(updateId),
+ kind: callback ? "callback" : message ? "message" : "update",
+ ...(chat?.id !== undefined ? { target: String(chat.id) } : {}),
+ ...(from?.id !== undefined ? { sender: String(from.id) } : {}),
+ ...(text ? { text } : {}),
+ receivedAt: new Date().toISOString(),
+ raw,
+ };
+}
diff --git a/lib/channels/registry.ts b/lib/channels/registry.ts
new file mode 100644
index 00000000..7d5f53bb
--- /dev/null
+++ b/lib/channels/registry.ts
@@ -0,0 +1,28 @@
+import type { ChannelProviderCapability, ChannelProviderId } from "./types";
+import { ChannelError } from "./errors";
+
+const providers: Record<ChannelProviderId, ChannelProviderCapability> = {
+ telegram: {
+ id: "telegram",
+ title: "Telegram",
+ inbound: "webhook",
+ sendText: true,
+ inboundEvents: true,
+ notes: "Bot API send + verified webhook updates.",
+ },
+ discord: {
+ id: "discord",
+ title: "Discord",
+ inbound: "interactions",
+ sendText: true,
+ inboundEvents: true,
+ notes: "REST send + signed Interactions endpoint. Gateway message ingestion is not enabled.",
+ },
+};
+
+export const listChannelProviders = () => Object.values(providers).map((value) => ({ ...value }));
+export function channelProvider(id: ChannelProviderId) {
+ const provider = providers[id];
+ if (!provider) throw new ChannelError("unknown_channel_provider", 404);
+ return provider;
+}
diff --git a/lib/channels/schema.test.ts b/lib/channels/schema.test.ts
new file mode 100644
index 00000000..a70656ae
--- /dev/null
+++ b/lib/channels/schema.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { parseChannelPatch, validateTarget } from "./schema";
+
+describe("channel schema", () => {
+ const base = {
+ name: "Support",
+ provider: "telegram",
+ credential: { user: "owner", connection: "bot" },
+ enabled: true,
+ };
+
+ it("keeps channel records metadata-only", () => {
+ expect(() => parseChannelPatch({ ...base, botToken: "123456:abcdefghijklmnopqrstuvwxyz" })).toThrow("secret_input_forbidden");
+ });
+
+ it("validates provider-specific targets", () => {
+ expect(validateTarget("telegram", "-100123456789")).toBe("-100123456789");
+ expect(validateTarget("discord", "123456789012345678")).toBe("123456789012345678");
+ expect(() => validateTarget("discord", "#general")).toThrow("invalid_discord_target");
+ });
+});
diff --git a/lib/channels/schema.ts b/lib/channels/schema.ts
new file mode 100644
index 00000000..15dca4d3
--- /dev/null
+++ b/lib/channels/schema.ts
@@ -0,0 +1,76 @@
+import { identity, metadataOnly, IntegrationError } from "@/lib/infra/identity";
+import { ChannelError } from "./errors";
+import { CHANNEL_PROVIDER_IDS, type ChannelProviderId, type ChannelRecord } from "./types";
+
+const SECRETISH = /(token|secret|password|passphrase|authorization|cookie)/i;
+function assertNoSecrets(value: unknown, depth = 0): void {
+ if (depth > 12) throw new ChannelError("channel_config_too_deep");
+ if (Array.isArray(value)) { value.forEach((item) => assertNoSecrets(item, depth + 1)); return; }
+ if (!value || typeof value !== "object") return;
+ for (const [key, child] of Object.entries(value)) {
+ if (SECRETISH.test(key)) throw new ChannelError("secret_input_forbidden");
+ assertNoSecrets(child, depth + 1);
+ }
+}
+
+const clean = (value: unknown, label: string, max = 120) => {
+ if (typeof value !== "string" || !value.trim() || value.length > max || /[\x00-\x1f\x7f]/.test(value)) {
+ throw new ChannelError(`invalid_${label}`);
+ }
+ return value.trim();
+};
+
+export function isChannelProvider(value: unknown): value is ChannelProviderId {
+ return typeof value === "string" && (CHANNEL_PROVIDER_IDS as readonly string[]).includes(value);
+}
+
+export function validateTarget(provider: ChannelProviderId, target: string) {
+ if (provider === "telegram") {
+ if (!/^(?:-?\d{1,20}|@[A-Za-z][A-Za-z0-9_]{4,31})$/.test(target)) throw new ChannelError("invalid_telegram_target");
+ return target;
+ }
+ if (!/^\d{15,22}$/.test(target)) throw new ChannelError("invalid_discord_target");
+ return target;
+}
+
+export function parseChannelPatch(
+ raw: Record<string, unknown>,
+ previous?: ChannelRecord,
+): Omit<ChannelRecord, "id" | "createdAt" | "updatedAt" | "lastCheck" | "lastActivityAt"> {
+ assertNoSecrets(raw);
+ try { metadataOnly(raw); } catch (error) { if (error instanceof IntegrationError) throw new ChannelError("secret_input_forbidden"); throw error; }
+ const providerRaw = raw.provider ?? previous?.provider;
+ if (!isChannelProvider(providerRaw)) throw new ChannelError("invalid_provider");
+
+ const credentialRaw = raw.credential ?? previous?.credential;
+ if (!credentialRaw || typeof credentialRaw !== "object" || Array.isArray(credentialRaw)) throw new ChannelError("credential_required");
+ const credential = credentialRaw as Record<string, unknown>;
+ const user = identity(credential.user, "user");
+ const connection = identity(credential.connection, "connection");
+
+ const name = raw.name === undefined && previous ? previous.name : clean(raw.name, "name");
+ const enabled = raw.enabled === undefined ? previous?.enabled ?? true : raw.enabled;
+ if (typeof enabled !== "boolean") throw new ChannelError("invalid_enabled");
+
+ const targetRaw = raw.defaultTarget === undefined ? previous?.defaultTarget : raw.defaultTarget;
+ let defaultTarget: string | undefined;
+ if (targetRaw !== undefined && targetRaw !== null && targetRaw !== "") {
+ defaultTarget = validateTarget(providerRaw, clean(targetRaw, "target", 128));
+ }
+
+ const workflowRaw = raw.workflowId === undefined ? previous?.workflowId : raw.workflowId;
+ let workflowId: string | undefined;
+ if (workflowRaw !== undefined && workflowRaw !== null && workflowRaw !== "") {
+ workflowId = clean(workflowRaw, "workflow", 96);
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(workflowId)) throw new ChannelError("invalid_workflow");
+ }
+
+ return {
+ name,
+ provider: providerRaw,
+ credential: { user, connection },
+ enabled,
+ ...(defaultTarget ? { defaultTarget } : {}),
+ ...(workflowId ? { workflowId } : {}),
+ };
+}
diff --git a/lib/channels/service.ts b/lib/channels/service.ts
new file mode 100644
index 00000000..1a823e5b
--- /dev/null
+++ b/lib/channels/service.ts
@@ -0,0 +1,146 @@
+import { directConnectionValues, integrationSnapshot, resolveIntegration } from "@/lib/infra/connection-service";
+import { IntegrationError } from "@/lib/infra/identity";
+import { ChannelError } from "./errors";
+import { channelProvider, listChannelProviders } from "./registry";
+import { parseChannelPatch } from "./schema";
+import {
+ channelById,
+ createChannel,
+ deleteChannel,
+ readChannelState,
+ recordChannelActivity,
+ recordChannelCheck,
+ updateChannel,
+} from "./store";
+import type { ChannelInboundEvent, ChannelRecord } from "./types";
+import { verifyTelegram, sendTelegramText, verifyTelegramSecret, normalizeTelegramUpdate } from "./providers/telegram";
+import {
+ discordApplicationMatches,
+ normalizeDiscordInteraction,
+ sendDiscordText,
+ verifyDiscord,
+ verifyDiscordSignature,
+} from "./providers/discord";
+
+async function values(channel: ChannelRecord) {
+ try {
+ return await directConnectionValues(channel.provider, {
+ user: channel.credential.user,
+ connection: channel.credential.connection,
+ });
+ } catch (error) {
+ if (error instanceof IntegrationError) throw new ChannelError(error.code, error.status);
+ throw error;
+ }
+}
+
+function assertEnabled(channel: ChannelRecord) {
+ if (!channel.enabled) throw new ChannelError("channel_disabled", 409);
+}
+
+export async function channelsSnapshot() {
+ const state = await readChannelState();
+ const root = await integrationSnapshot();
+ const credentials = (await Promise.all(root.users.map(async (profile) => {
+ const snapshot = await integrationSnapshot({ user: profile.id });
+ return snapshot.connections
+ .filter((row) => row.source === "direct" && (row.provider === "telegram" || row.provider === "discord"))
+ .map((row) => ({ userLabel: profile.label, ...row }));
+ }))).flat();
+ const channels = await Promise.all(state.channels.map(async (row) => {
+ try {
+ const connection = await resolveIntegration(row.provider, row.credential);
+ return { ...row, capabilities: channelProvider(row.provider), connection };
+ } catch (error) {
+ const code = error instanceof IntegrationError ? error.code : "connection_unavailable";
+ return { ...row, capabilities: channelProvider(row.provider), connection: { state: "missing", error: code } };
+ }
+ }));
+ return { ...state, providers: listChannelProviders(), credentials, channels };
+}
+
+async function assertCredentialRef(input: ReturnType<typeof parseChannelPatch>) {
+ try {
+ await directConnectionValues(input.provider, { user: input.credential.user, connection: input.credential.connection });
+ } catch (error) {
+ if (error instanceof IntegrationError) throw new ChannelError(error.code, error.status);
+ throw error;
+ }
+}
+
+export async function createChannelConfig(raw: Record<string, unknown>) {
+ const parsed = parseChannelPatch(raw);
+ await assertCredentialRef(parsed);
+ return createChannel(raw);
+}
+
+export async function updateChannelConfig(id: string, expectedRevision: number, raw: Record<string, unknown>) {
+ const previous = await channelById(id);
+ const parsed = parseChannelPatch(raw, previous);
+ await assertCredentialRef(parsed);
+ return updateChannel(id, expectedRevision, raw);
+}
+
+export const deleteChannelConfig = deleteChannel;
+
+export async function testChannel(id: string) {
+ const channel = await channelById(id);
+ let ok = false;
+ let detail = "Verification failed";
+ try {
+ const credential = await values(channel);
+ const result = channel.provider === "telegram" ? await verifyTelegram(credential) : await verifyDiscord(credential);
+ ok = true;
+ detail = result.detail;
+ } catch (error) {
+ detail = error instanceof Error ? error.message : "verification_failed";
+ }
+ const stored = await recordChannelCheck(id, ok, detail);
+ return { ok, detail, channel: stored };
+}
+
+export async function sendChannelText(id: string, input: { target?: string; text: string }) {
+ const channel = await channelById(id);
+ assertEnabled(channel);
+ const target = input.target?.trim() || channel.defaultTarget;
+ if (!target) throw new ChannelError("channel_target_required");
+ const credential = await values(channel);
+ const result = channel.provider === "telegram"
+ ? await sendTelegramText(credential, target, input.text)
+ : await sendDiscordText(credential, target, input.text);
+ await recordChannelActivity(id);
+ return { provider: channel.provider, target, ...result };
+}
+
+export async function receiveTelegram(id: string, raw: unknown, suppliedSecret: string | null): Promise<ChannelInboundEvent> {
+ const channel = await channelById(id);
+ if (channel.provider !== "telegram") throw new ChannelError("channel_provider_mismatch", 404);
+ assertEnabled(channel);
+ const credential = await values(channel);
+ if (!credential.webhookSecret) throw new ChannelError("telegram_webhook_secret_required", 503);
+ if (!verifyTelegramSecret(credential, suppliedSecret)) throw new ChannelError("invalid_webhook_signature", 401);
+ return normalizeTelegramUpdate(raw);
+}
+
+export async function receiveDiscord(
+ id: string,
+ bodyText: string,
+ timestamp: string | null,
+ signature: string | null,
+): Promise<{ event: ChannelInboundEvent | null; ping: boolean }> {
+ const channel = await channelById(id);
+ if (channel.provider !== "discord") throw new ChannelError("channel_provider_mismatch", 404);
+ assertEnabled(channel);
+ const credential = await values(channel);
+ if (!credential.publicKey) throw new ChannelError("discord_public_key_required", 503);
+ if (!verifyDiscordSignature(credential, timestamp, signature, bodyText)) throw new ChannelError("invalid_webhook_signature", 401);
+ let raw: unknown;
+ try { raw = JSON.parse(bodyText); } catch { throw new ChannelError("invalid_discord_interaction"); }
+ if (!discordApplicationMatches(credential, raw)) throw new ChannelError("discord_application_mismatch", 401);
+ if ((raw as Record<string, unknown>).type === 1) {
+ await recordChannelActivity(id);
+ return { event: null, ping: true };
+ }
+ const event = normalizeDiscordInteraction(raw);
+ return { event, ping: false };
+}
diff --git a/lib/channels/store.test.ts b/lib/channels/store.test.ts
new file mode 100644
index 00000000..20845237
--- /dev/null
+++ b/lib/channels/store.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { createChannel, readChannelState, recordChannelActivity, recordChannelCheck, updateChannel } from "./store";
+
+let dir = "";
+beforeEach(async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), "mso-channels-"));
+ process.env.OS_CHANNEL_STORE = path.join(dir, "channels.json");
+});
+afterEach(async () => {
+ delete process.env.OS_CHANNEL_STORE;
+ await rm(dir, { recursive: true, force: true });
+});
+
+describe("channel store", () => {
+ it("persists non-secret config and keeps activity/check telemetry outside config revision", async () => {
+ const created = await createChannel({
+ name: "Bot",
+ provider: "telegram",
+ credential: { user: "owner", connection: "telegram" },
+ enabled: true,
+ defaultTarget: "-100123",
+ });
+ expect(created.state.revision).toBe(1);
+ const id = created.result.id;
+
+ await recordChannelActivity(id);
+ await recordChannelCheck(id, true, "verified");
+ const observed = await readChannelState();
+ expect(observed.revision).toBe(1);
+ expect(observed.channels[0]?.lastCheck?.ok).toBe(true);
+ expect(observed.channels[0]?.lastActivityAt).toBeTruthy();
+
+ const updated = await updateChannel(id, observed.revision, { enabled: false });
+ expect(updated.state.revision).toBe(2);
+ expect(updated.result.enabled).toBe(false);
+ });
+});
diff --git a/lib/channels/store.ts b/lib/channels/store.ts
new file mode 100644
index 00000000..2df02207
--- /dev/null
+++ b/lib/channels/store.ts
@@ -0,0 +1,147 @@
+import { randomUUID } from "node:crypto";
+import { constants, promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { ChannelError } from "./errors";
+import { parseChannelPatch } from "./schema";
+import type { ChannelRecord, ChannelState } from "./types";
+
+const MAX_BYTES = 1024 * 1024;
+const storePath = () => expandOwnerStorePath(process.env.OS_CHANNEL_STORE ?? path.join(os.homedir(), ".mso", "private", "channels.json"));
+const empty = (): ChannelState => ({ version: 1, revision: 0, channels: [] });
+
+function validateState(value: unknown): ChannelState {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ChannelError("invalid_channel_store");
+ const state = value as Partial<ChannelState>;
+ if (state.version !== 1 || !Number.isSafeInteger(state.revision) || (state.revision ?? -1) < 0 || !Array.isArray(state.channels)) {
+ throw new ChannelError("invalid_channel_store");
+ }
+ const ids = new Set<string>();
+ const channels = state.channels.map((raw) => {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new ChannelError("invalid_channel_store");
+ const row = raw as ChannelRecord;
+ if (typeof row.id !== "string" || !/^[0-9a-f-]{36}$/i.test(row.id) || ids.has(row.id)) throw new ChannelError("invalid_channel_store");
+ ids.add(row.id);
+ const parsed = parseChannelPatch(row as unknown as Record<string, unknown>);
+ if (typeof row.createdAt !== "string" || typeof row.updatedAt !== "string") throw new ChannelError("invalid_channel_store");
+ return {
+ id: row.id,
+ ...parsed,
+ createdAt: row.createdAt,
+ updatedAt: row.updatedAt,
+ ...(row.lastCheck ? { lastCheck: row.lastCheck } : {}),
+ ...(row.lastActivityAt ? { lastActivityAt: row.lastActivityAt } : {}),
+ } satisfies ChannelRecord;
+ });
+ return { version: 1, revision: state.revision!, channels };
+}
+
+async function readUnlocked(): Promise<ChannelState> {
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
+ try {
+ handle = await fs.open(storePath(), constants.O_RDONLY | constants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_BYTES || (stat.mode & 0o077)) throw new ChannelError("unsafe_channel_store");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new ChannelError("unsafe_channel_store");
+ return validateState(JSON.parse(await handle.readFile("utf8")));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return empty();
+ throw error;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+}
+
+async function writeUnlocked(state: ChannelState) {
+ const file = storePath();
+ const dir = path.dirname(file);
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ await fs.chmod(dir, 0o700);
+ const body = JSON.stringify(state, null, 2) + "\n";
+ if (Buffer.byteLength(body) > MAX_BYTES) throw new ChannelError("channel_store_capacity", 409);
+ const temp = `${file}.${randomUUID()}.tmp`;
+ try {
+ await fs.writeFile(temp, body, { flag: "wx", mode: 0o600 });
+ await fs.rename(temp, file);
+ await fs.chmod(file, 0o600);
+ } finally {
+ await fs.unlink(temp).catch(() => undefined);
+ }
+}
+
+export async function readChannelState() {
+ return structuredClone(await readUnlocked());
+}
+
+async function mutate<T>(fn: (state: ChannelState) => T | Promise<T>, bumpRevision = true) {
+ return withSecurityStoreLock(storePath(), async () => {
+ const state = await readUnlocked();
+ const result = await fn(state);
+ if (bumpRevision) state.revision += 1;
+ await writeUnlocked(state);
+ return { result, state: structuredClone(state) };
+ });
+}
+
+export async function createChannel(raw: Record<string, unknown>) {
+ return mutate((state) => {
+ const now = new Date().toISOString();
+ const row: ChannelRecord = { id: randomUUID(), ...parseChannelPatch(raw), createdAt: now, updatedAt: now };
+ state.channels.push(row);
+ return structuredClone(row);
+ });
+}
+
+export async function updateChannel(id: string, expectedRevision: number, raw: Record<string, unknown>) {
+ return mutate((state) => {
+ if (state.revision !== expectedRevision) throw new ChannelError("channel_revision_changed", 409);
+ const index = state.channels.findIndex((row) => row.id === id);
+ if (index < 0) throw new ChannelError("channel_not_found", 404);
+ const previous = state.channels[index]!;
+ const row: ChannelRecord = {
+ ...previous,
+ ...parseChannelPatch(raw, previous),
+ id: previous.id,
+ createdAt: previous.createdAt,
+ updatedAt: new Date().toISOString(),
+ };
+ state.channels[index] = row;
+ return structuredClone(row);
+ });
+}
+
+export async function deleteChannel(id: string, expectedRevision: number) {
+ return mutate((state) => {
+ if (state.revision !== expectedRevision) throw new ChannelError("channel_revision_changed", 409);
+ const index = state.channels.findIndex((row) => row.id === id);
+ if (index < 0) throw new ChannelError("channel_not_found", 404);
+ return state.channels.splice(index, 1)[0]!;
+ });
+}
+
+export async function channelById(id: string) {
+ const row = (await readUnlocked()).channels.find((item) => item.id === id);
+ if (!row) throw new ChannelError("channel_not_found", 404);
+ return structuredClone(row);
+}
+
+export async function recordChannelCheck(id: string, ok: boolean, detail: string) {
+ return mutate((state) => {
+ const row = state.channels.find((item) => item.id === id);
+ if (!row) throw new ChannelError("channel_not_found", 404);
+ row.lastCheck = { at: new Date().toISOString(), ok, detail: detail.slice(0, 300) };
+ row.updatedAt = new Date().toISOString();
+ return structuredClone(row);
+ }, false);
+}
+
+export async function recordChannelActivity(id: string) {
+ return mutate((state) => {
+ const row = state.channels.find((item) => item.id === id);
+ if (!row) throw new ChannelError("channel_not_found", 404);
+ row.lastActivityAt = new Date().toISOString();
+ return structuredClone(row);
+ }, false);
+}
diff --git a/lib/channels/types.ts b/lib/channels/types.ts
new file mode 100644
index 00000000..98867416
--- /dev/null
+++ b/lib/channels/types.ts
@@ -0,0 +1,53 @@
+export const CHANNEL_PROVIDER_IDS = ["telegram", "discord"] as const;
+export type ChannelProviderId = (typeof CHANNEL_PROVIDER_IDS)[number];
+
+export type ChannelCredentialRef = {
+ user: string;
+ connection: string;
+};
+
+export type ChannelCheck = {
+ at: string;
+ ok: boolean;
+ detail: string;
+};
+
+export type ChannelRecord = {
+ id: string;
+ name: string;
+ provider: ChannelProviderId;
+ credential: ChannelCredentialRef;
+ enabled: boolean;
+ defaultTarget?: string;
+ workflowId?: string;
+ createdAt: string;
+ updatedAt: string;
+ lastCheck?: ChannelCheck;
+ lastActivityAt?: string;
+};
+
+export type ChannelState = {
+ version: 1;
+ revision: number;
+ channels: ChannelRecord[];
+};
+
+export type ChannelInboundEvent = {
+ provider: ChannelProviderId;
+ eventId: string;
+ kind: string;
+ target?: string;
+ sender?: string;
+ text?: string;
+ receivedAt: string;
+ raw: unknown;
+};
+
+export type ChannelProviderCapability = {
+ id: ChannelProviderId;
+ title: string;
+ inbound: "webhook" | "interactions";
+ sendText: boolean;
+ inboundEvents: boolean;
+ notes: string;
+};
diff --git a/lib/channels/workflow-contract.test.ts b/lib/channels/workflow-contract.test.ts
new file mode 100644
index 00000000..6edc5f70
--- /dev/null
+++ b/lib/channels/workflow-contract.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { parseWorkflowGraphDefinition } from "@/lib/workflow/graph-schema";
+import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";
+
+const trigger = { id: "channel", name: "Channel", type: "channel_trigger", position: { x: 0, y: 0 }, config: { channelId: "" } };
+const output = { id: "output", name: "Output", type: "output", position: { x: 200, y: 0 }, config: {} };
+
+describe("channel workflow contract", () => {
+ it("exposes native Channel Trigger and Channel Send nodes", () => {
+ const types = workflowNodeCatalog("channel").map((row) => row.type);
+ expect(types).toContain("channel_trigger");
+ expect(types).toContain("channel_send");
+ });
+
+ it("accepts channel triggers as workflow roots and rejects incoming edges into them", () => {
+ expect(parseWorkflowGraphDefinition({
+ name: "Channel flow", description: "", status: "active", inputs: {},
+ nodes: [trigger, output], edges: [{ id: "e1", source: "channel", target: "output" }], metadata: {},
+ }).nodes[0]?.type).toBe("channel_trigger");
+ expect(() => parseWorkflowGraphDefinition({
+ name: "Bad", description: "", status: "active", inputs: {},
+ nodes: [trigger, output], edges: [{ id: "e1", source: "output", target: "channel" }], metadata: {},
+ })).toThrow("trigger nodes must be workflow roots");
+ });
+});
diff --git a/lib/channels/workflow.ts b/lib/channels/workflow.ts
new file mode 100644
index 00000000..a1f03c37
--- /dev/null
+++ b/lib/channels/workflow.ts
@@ -0,0 +1,59 @@
+import { createAgentSession } from "@/lib/agent/session-store";
+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
+import type { Scope } from "@/lib/capabilities/scope";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+import { findActiveChannelSource } from "@/lib/workflow/graph-triggers";
+import { startWorkflowGraph } from "@/lib/workflow/graph-engine";
+import { ChannelError } from "./errors";
+import { channelById, recordChannelActivity } from "./store";
+import type { ChannelInboundEvent } from "./types";
+
+export type ChannelWorkflowRuntime = {
+ scope: Scope;
+ capabilities?: CapabilityRuntime;
+ resolveTool: (name: string) => CapabilityTool | undefined;
+};
+
+function workflowInput(channel: Awaited<ReturnType<typeof channelById>>, event: ChannelInboundEvent) {
+ const { raw: _raw, ...safeEvent } = event;
+ return {
+ channel: { id: channel.id, name: channel.name, provider: channel.provider },
+ event: safeEvent,
+ };
+}
+
+export async function dispatchChannelInbound(
+ channelId: string,
+ event: ChannelInboundEvent,
+ runtime: ChannelWorkflowRuntime,
+) {
+ const channel = await channelById(channelId);
+ await recordChannelActivity(channelId);
+ if (!channel.workflowId) return { workflow: null };
+
+ const source = await findActiveChannelSource(channel.workflowId, channel.id);
+ if (!source) throw new ChannelError("channel_workflow_trigger_not_found", 409);
+
+ const session = await createAgentSession(source.principal, "cli", {
+ title: "Channel: " + channel.name,
+ titleSource: "auto",
+ });
+ const context = {
+ principal: source.principal,
+ actor: source.principal,
+ sessionId: session.id,
+ scope: runtime.scope,
+ ...(runtime.capabilities ? { capabilities: runtime.capabilities } : {}),
+ } as const;
+ const idempotency = ["channel", channel.id, event.eventId].join(":").slice(0, 128);
+ const run = await startWorkflowGraph(
+ source.graph,
+ workflowInput(channel, event),
+ idempotency,
+ context,
+ runtime.resolveTool,
+ source.principal,
+ { type: "channel", nodeId: source.node.id, receivedAt: event.receivedAt },
+ );
+ return { workflow: { runId: run.id, state: run.state, graphId: source.graph.id } };
+}
diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.ts
index 9cd875ff..2f216188 100644
--- a/lib/contracts/workflow-graph.ts
+++ b/lib/contracts/workflow-graph.ts
@@ -1,6 +1,6 @@
import type { GraphCustomNode } from "./graph-custom-nodes";
export const WORKFLOW_GRAPH_NODE_TYPES = [
- "manual", "schedule", "webhook", "tool", "project_function", "project_mcp", "integration", "script", "agent", "subflow",
+ "manual", "schedule", "webhook", "channel_trigger", "tool", "project_function", "project_mcp", "integration", "channel_send", "script", "agent", "subflow",
"condition", "switch", "merge", "batch", "loop", "repeat", "wait", "cache", "data_table", "memory", "session", "directory", "project", "folder", "skill", "knowledge", "output",
] as const;
export type WorkflowGraphNodeType = (typeof WORKFLOW_GRAPH_NODE_TYPES)[number];
@@ -99,7 +99,7 @@ export type WorkflowGraphRun = {
instance: string;
nodes: WorkflowGraphRunNode[];
edges?: WorkflowGraphRunEdge[];
- trigger?: { type: "manual" | "schedule" | "webhook" | "system"; nodeId?: string; receivedAt: string };
+ trigger?: { type: "manual" | "schedule" | "webhook" | "channel" | "system"; nodeId?: string; receivedAt: string };
ancestry?: string[];
/** Owner-private runtime input retained only so an execution can be retried safely. Public receipts strip this field. */
runtimeInput?: Record<string, unknown>;
diff --git a/lib/infra/additional-doctor.ts b/lib/infra/additional-doctor.ts
index 13f1461d..c43cab5a 100644
--- a/lib/infra/additional-doctor.ts
+++ b/lib/infra/additional-doctor.ts
@@ -133,6 +133,28 @@ export async function doctorAdditionalProvider(id: string, values: Record<string
const response = await checked("Supabase", "https://api.supabase.com/v1/projects", { authorization: `Bearer ${values.managementToken}`, accept: "application/json" });
return `authenticated; ${countRows(response.body)} accessible project(s)`;
}
+ case "telegram": {
+ if (!present(values.botToken)) return null;
+ if (!/^\\d{5,16}:[A-Za-z0-9_-]{20,}$/.test(values.botToken)) throw new Error("Telegram bot token format is invalid");
+ const response = await checked("Telegram", "https://api.telegram.org/bot" + values.botToken + "/getMe", { accept: "application/json" });
+ const root = obj(response.body);
+ const result = obj(root.result);
+ if (root.ok !== true || (typeof result.id !== "number" && typeof result.id !== "string")) throw new Error("Telegram bot identity unavailable");
+ const username = typeof result.username === "string" && /^[A-Za-z0-9_]{3,64}$/.test(result.username) ? " @" + result.username : "";
+ return "authenticated; bot identity verified" + username;
+ }
+ case "discord": {
+ if (!present(values.botToken)) return null;
+ const response = await checked("Discord", "https://discord.com/api/v10/users/@me", {
+ authorization: "Bot " + values.botToken,
+ accept: "application/json",
+ "user-agent": "MSO-integration-doctor",
+ });
+ const body = obj(response.body);
+ if (typeof body.id !== "string") throw new Error("Discord bot identity unavailable");
+ const username = typeof body.username === "string" && body.username.length <= 80 ? " as " + body.username : "";
+ return "authenticated; bot identity verified" + username;
+ }
case "doku":
return doctorDoku(values);
case "convex-cloud": {
diff --git a/lib/infra/additional-providers.ts b/lib/infra/additional-providers.ts
index 2244981f..9191a476 100644
--- a/lib/infra/additional-providers.ts
+++ b/lib/infra/additional-providers.ts
@@ -91,6 +91,27 @@ export const ADDITIONAL_PROVIDERS = {
feature: false,
fields: [{ key: "organizationId", label: "Organization ID", secret: false, required: false, description: "Optional connection-specific configuration; retained during JSON transfer." }, { key: "managementToken", label: "Management access token", secret: true, required: true, description: "A Supabase personal access token for the Management API; it is distinct from project API keys." }],
},
+ telegram: {
+ id: "telegram",
+ title: "Telegram",
+ description: "Connect a Telegram bot for MSO Channels without storing bot credentials in channel configuration.",
+ feature: false,
+ fields: [
+ { key: "botToken", label: "Bot token", secret: true, required: true, description: "Telegram Bot API token created by BotFather. Kept only in MSO Integrations." },
+ { key: "webhookSecret", label: "Webhook secret", secret: true, required: false, description: "Optional 1–256 character secret used to validate X-Telegram-Bot-Api-Secret-Token on inbound webhooks." },
+ ],
+ },
+ discord: {
+ id: "discord",
+ title: "Discord",
+ description: "Connect a Discord bot/application for MSO Channels with REST sending and signed Interactions.",
+ feature: false,
+ fields: [
+ { key: "botToken", label: "Bot token", secret: true, required: true, description: "Discord bot token. Kept only in MSO Integrations." },
+ { key: "applicationId", label: "Application ID", secret: false, required: false, description: "Discord application snowflake used to bind signed interaction payloads to this application." },
+ { key: "publicKey", label: "Interactions public key", secret: false, required: false, description: "64-character Ed25519 public key from the Discord Developer Portal for interaction signature verification." },
+ ],
+ },
doku: { id:"doku", title:"DOKU", description:"Verify DOKU Payment REST or DOKU MCP merchant credentials without copying secrets into project configuration.", feature:false, fields:[
{key:"paymentClientId",label:"Payment Client ID",secret:true,required:false,description:"DOKU Back Office Client ID used by the signed Non-SNAP payment API."},
{key:"paymentSecretKey",label:"Payment Secret Key",secret:true,required:false,description:"DOKU Back Office HMAC Secret Key for signed payment API requests. This is not the MCP API Key."},
@@ -122,6 +143,8 @@ export const ADDITIONAL_GUIDANCE = {
stripe: { url: "https://dashboard.stripe.com/apikeys", reference: "https://docs.stripe.com/keys", steps: ["Open Developers → API keys in the intended Stripe account.", "Use a restricted key when its available permissions cover the integration.", "Confirm whether you are using test or live mode before copying the secret key.", "Copy the key once and rotate it promptly if it is exposed."] },
clerk: { url: "https://dashboard.clerk.com", reference: "https://clerk.com/docs/guides/development/api-keys", steps: ["Open the intended Clerk instance in the Clerk dashboard.", "Find its secret key in the API Keys or Developers settings.", "Keep the key server-side and limit access to the intended instance.", "Copy it into this form; this check only confirms Backend API authentication."] },
supabase: { url: "https://supabase.com/dashboard/account/tokens", reference: "https://supabase.com/docs/reference/api/introduction", steps: ["Open Account → Access Tokens in the Supabase dashboard.", "Generate a personal access token for the account that owns the intended projects.", "Give it a clear name and an appropriate expiry.", "Copy it once into this form; project API keys cannot be used as Management API tokens."] },
+ telegram: { url: "https://t.me/BotFather", reference: "https://core.telegram.org/bots/api", steps: ["Create or select the intended bot in BotFather.", "Copy its Bot API token into this private Integrations form; never paste it into a Channel record.", "Create a webhook secret with letters, digits, underscore or hyphen before enabling inbound webhooks.", "MSO verifies the token with Bot API getMe before marking the connection verified."] },
+ discord: { url: "https://discord.com/developers/applications", reference: "https://discord.com/developers/docs/quick-start/getting-started", steps: ["Open the intended application in the Discord Developer Portal.", "Create/reset the bot token only if needed and enter it in this private Integrations form.", "For inbound interactions also copy the Application ID and Interactions Endpoint public key.", "MSO verifies the bot token through the Discord REST API; signed interactions are verified separately at the public channel endpoint."] },
doku: { url: "https://developers.doku.com/accept-payments/doku-mcp-server", reference: "https://developers.doku.com/accept-payments/doku-mcp-server", steps: ["Open DOKU's official MCP Server guide and choose Sandbox first unless this project is explicitly approved for production payments.", "Obtain the DOKU Client ID and MCP API Key for that environment.", "Enter them only in this private setup form; do not paste them into chat, Baton notes, RR, Git, or project MCP JSON.", "MSO calls the fixed official DOKU MCP endpoint with a read-only MCP initialize request before saving the connection."] },
"openai-app": { url: "https://chatgpt.com/", reference: "https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt", steps: ["Enable ChatGPT developer mode, then create/register the remote MCP app for this MSO installation and complete Scan Tools + OAuth.", "Open the registered app details. Copy the App ID shown there, or copy the technical plugin_asdk_app_… id from the browser URL; do not use the Version ID as the app binding.", "Enter the App ID only in this private Integrations form. MSO normalizes plugin_asdk_app_… to canonical asdk_app_… and never returns the stored value through tool/model responses.", "Use the private plugin staging/link command when packaging. Keep the repository .app.json empty so a maintainer-specific App ID is never committed or distributed to other users."] },
} as const satisfies Record<AdditionalProviderId, { url: string; reference: string; steps: readonly string[] }>;
diff --git a/lib/infra/catalog.ts b/lib/infra/catalog.ts
index 8de8b65a..616aa93d 100644
--- a/lib/infra/catalog.ts
+++ b/lib/infra/catalog.ts
@@ -103,6 +103,15 @@ export function normalizeInfraValues(id: InfraProviderId, raw: Record<string, un
if (out.accessToken && (out.accessToken.length < 16 || /\s/.test(out.accessToken))) throw new Error("MCP token must be an opaque single-line value");
parseMcpToolAllowlist(out.allowedTools);
}
+ if (id === "telegram") {
+ if (out.botToken && !/^\d{5,16}:[A-Za-z0-9_-]{20,}$/.test(out.botToken)) throw new Error("Telegram bot token format is invalid");
+ if (out.webhookSecret && !/^[A-Za-z0-9_-]{1,256}$/.test(out.webhookSecret)) throw new Error("Telegram webhook secret must use only letters, digits, underscore or hyphen");
+ }
+ if (id === "discord") {
+ if (out.botToken && (out.botToken.length < 24 || out.botToken.length > 256 || /[\s\x00-\x1f\x7f]/.test(out.botToken))) throw new Error("Discord bot token format is invalid");
+ if (out.applicationId && !/^\d{15,22}$/.test(out.applicationId)) throw new Error("Discord applicationId must be a snowflake");
+ if (out.publicKey && !/^[0-9a-f]{64}$/i.test(out.publicKey)) throw new Error("Discord publicKey must be 64 hexadecimal characters");
+ }
if (id === "doku") {
for(const key of ["environment","paymentEnvironment"])if(out[key]&&!["sandbox","production"].includes(out[key]))throw new Error("DOKU environment must be sandbox or production");
for(const key of ["paymentClientId","mcpClientId"])if(out[key]&&(out[key].length<3||out[key].length>256||/[\s\x00-\x1f\x7f]/.test(out[key])))throw new Error("DOKU Client ID must be an opaque single-line value");
diff --git a/lib/infra/channels-integration.test.ts b/lib/infra/channels-integration.test.ts
new file mode 100644
index 00000000..5ca410fd
--- /dev/null
+++ b/lib/infra/channels-integration.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { getInfraProviderDefinition, normalizeInfraValues } from "./catalog";
+import { connectionCatalog } from "./connection-registry";
+
+describe("Channels integration providers", () => {
+ it("registers Telegram and Discord as direct secret-bearing Integrations", () => {
+ const catalog = connectionCatalog();
+ for (const id of ["telegram", "discord"] as const) {
+ const row = catalog.find((item) => item.id === id);
+ expect(row?.sources.map((source) => source.id)).toEqual(["direct"]);
+ expect(getInfraProviderDefinition(id).fields.find((field) => field.key === "botToken")?.secret).toBe(true);
+ }
+ });
+
+ it("validates public interaction metadata without treating it as secret", () => {
+ expect(normalizeInfraValues("discord", {
+ botToken: "abcdefghijklmnopqrstuvwxyz123456",
+ applicationId: "123456789012345678",
+ publicKey: "a".repeat(64),
+ }).applicationId).toBe("123456789012345678");
+ expect(() => normalizeInfraValues("telegram", { botToken: "not-a-token" })).toThrow("Telegram bot token format");
+ });
+});
diff --git a/lib/infra/types.ts b/lib/infra/types.ts
index dfc43f9c..67adc0b2 100644
--- a/lib/infra/types.ts
+++ b/lib/infra/types.ts
@@ -1,4 +1,4 @@
-export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "composio", "github", "vercel", "convex-cloud", "convex", "resend", "stripe", "clerk", "supabase", "doku", "mcp", "openai-app"] as const;
+export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "composio", "github", "vercel", "convex-cloud", "convex", "resend", "stripe", "clerk", "supabase", "telegram", "discord", "doku", "mcp", "openai-app"] as const;
export type InfraProviderId = (typeof INFRA_PROVIDER_IDS)[number];
export type InfraProviderValues = Record<string, string>;
diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.ts
index d1d3915e..7fe10632 100644
--- a/lib/workflow/graph-engine.ts
+++ b/lib/workflow/graph-engine.ts
@@ -53,7 +53,7 @@ async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Recor
for(const node of graph.nodes){
if(cancelled.has(run.id)){run.state="interrupted";run.error="Stopped by user.";for(const pendingId of remaining){const queued=rows.get(pendingId);if(queued?.state==="queued"){queued.state="skipped";queued.logs.push("Skipped because the execution was stopped.");}}throw new Error(run.error);}
if(!remaining.has(node.id))continue; const deps=incoming.get(node.id)??[]; if(deps.some((edge)=>edgeState.get(edge.id)==="pending"))continue; const row=rows.get(node.id)!;
- const triggerNode=["manual","schedule","webhook"].includes(node.type),triggerMismatch=Boolean(triggerNode&&run.trigger?.nodeId&&run.trigger.nodeId!==node.id);if(node.disabled||triggerMismatch||(deps.length>0&&deps.every((edge)=>edgeState.get(edge.id)==="disabled"))){row.state="skipped";row.finishedAt=new Date().toISOString();row.logs.push(node.disabled?"Node disabled by workflow definition.":triggerMismatch?"Skipped because another trigger started this run.":"Skipped because no incoming branch was selected.");disableOutgoing(node.id);remaining.delete(node.id);progressed=true;run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);continue;}
+ const triggerNode=["manual","schedule","webhook","channel_trigger"].includes(node.type),triggerMismatch=Boolean(triggerNode&&run.trigger?.nodeId&&run.trigger.nodeId!==node.id);if(node.disabled||triggerMismatch||(deps.length>0&&deps.every((edge)=>edgeState.get(edge.id)==="disabled"))){row.state="skipped";row.finishedAt=new Date().toISOString();row.logs.push(node.disabled?"Node disabled by workflow definition.":triggerMismatch?"Skipped because another trigger started this run.":"Skipped because no incoming branch was selected.");disableOutgoing(node.id);remaining.delete(node.id);progressed=true;run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);continue;}
row.state="running";row.startedAt=new Date().toISOString();row.logs.push("Node started.");run.updatedAt=row.startedAt;await writeWorkflowGraphRun(run);await sessionEvent("running",`${node.name} · ${node.type}`); const started=Date.now(),policy=retryPolicy(node); let failure:unknown;
for(let attempt=1;attempt<=policy.maxAttempts;attempt+=1){row.attempts=attempt;try{const result=await executeNode(node,run,graph,input,outputs,context,resolve);row.output=compact(secretValue(result.output,secrets));outputs[node.id]=result.output;row.state="completed";if(result.log)row.logs.push(result.log);resolveOutgoing(node.id,result.handles);failure=undefined;break;}catch(error){failure=error;row.logs.push(`Attempt ${attempt}/${policy.maxAttempts} failed: ${secretText(redactText(error instanceof Error?error.message:"node failed",500),secrets)}`);if(attempt<policy.maxAttempts)await sleep(Math.min(30_000,policy.backoffMs*Math.max(1,2**(attempt-1))));}}
if(failure){row.state="failed";row.error=secretText(redactText(failure instanceof Error?failure.message:"node failed",800),secrets);outputs[node.id]={error:row.error};const errorEdges=(outgoing.get(node.id)??[]).filter((edge)=>edge.sourceHandle==="error"),continueOnError=node.config.onError==="continue";if(errorEdges.length||continueOnError){handledErrors=true;resolveOutgoing(node.id,errorEdges.length?["error"]:undefined);row.logs.push(errorEdges.length?"Failure routed through error output.":"Failure continued by node policy.");}else{run.failedNodeId=node.id;run.failedNodeName=node.name;run.error=row.error;run.state="failed";for(const pendingId of remaining){if(pendingId===node.id)continue;const blocked=rows.get(pendingId)!;if(blocked.state==="queued"){blocked.state="blocked";blocked.logs.push(`Blocked by failed node ${node.name}.`);}}row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);throw failure;}}
@@ -75,7 +75,7 @@ export function workflowGraphRunId(owner:string,key:string){return hash(`${owner
export async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknown, idempotencyKey: string, context: CapabilityRunContext, resolve: Resolver, storagePrincipal?: string, trigger?: WorkflowRunTrigger, ancestry: string[] = []) {
const principal=storagePrincipal??context.principal;if(!principal||!context.sessionId)throw new Error("workflow graph requires an authenticated principal/session");if(ancestry.includes(graph.id)||ancestry.length>=16)throw new Error("recursive workflow subflow detected");if(graph.status==="archived")throw new Error("archived workflow graph cannot run");if(!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))throw new Error("idempotency_key must be 1-128 simple characters");
const owner=workflowGraphOwner(principal),input=inputObject(rawInput),fingerprint=hash(canonical({graphId:graph.id,revision:graph.revision,input})),id=workflowGraphRunId(owner,idempotencyKey);
- return lockWorkflowGraphRun(owner,id,async()=>{const existing=await readWorkflowGraphRun(owner,id);if(existing){if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),edges:graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,...(edge.sourceHandle?{sourceHandle:edge.sourceHandle}:{}),state:edge.disabled?"disabled":"pending"})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id],runtimeInput:structuredClone(input)};await writeWorkflowGraphRun(run);await appendAgentSessionEvent(principal,run.sessionId,{kind:"workflow",tool:"workflow_graph",state:"started",workflowId:graph.id,detail:graph.name}).catch(()=>undefined);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>{pending.delete(id);cancelled.delete(id);});pending.set(id,work);return publicWorkflowGraphRun(run);});
+ return lockWorkflowGraphRun(owner,id,async()=>{const existing=await readWorkflowGraphRun(owner,id);if(existing){if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),edges:graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,...(edge.sourceHandle?{sourceHandle:edge.sourceHandle}:{}),state:edge.disabled?"disabled":"pending"})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook","channel_trigger"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id],runtimeInput:structuredClone(input)};await writeWorkflowGraphRun(run);await appendAgentSessionEvent(principal,run.sessionId,{kind:"workflow",tool:"workflow_graph",state:"started",workflowId:graph.id,detail:graph.name}).catch(()=>undefined);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>{pending.delete(id);cancelled.delete(id);});pending.set(id,work);return publicWorkflowGraphRun(run);});
}
export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0){if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");if(run.state==="running"&&pending.has(id)&&waitMs>0){let timer:ReturnType<typeof setTimeout>|undefined;await Promise.race([pending.get(id),new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);clearTimeout(timer);run=await readWorkflowGraphRun(owner,id)??run;}if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}return publicWorkflowGraphRun(run);}
diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.ts
index 51691620..ed081e1f 100644
--- a/lib/workflow/graph-runtime.ts
+++ b/lib/workflow/graph-runtime.ts
@@ -59,7 +59,7 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph
const principal = context.principal ?? context.actor; if (!principal) throw new Error("workflow node requires principal");
const config = bindWorkflowValue(node.config, runtime, await workflowVariableValues(principal)) as Record<string, unknown>;
const project = typeof config.project === "string" ? config.project : graph.metadata.project;
- if (["manual", "schedule", "webhook"].includes(node.type)) return { output: graphInput, log: `${node.type} trigger accepted.` };
+ if (["manual", "schedule", "webhook", "channel_trigger"].includes(node.type)) return { output: graphInput, log: `${node.type} trigger accepted.` };
if (node.type === "project") return { output: await resolvedProject(config.project ?? project), log: "Canonical project resolved at runtime." };
if (node.type === "folder") {
const resolved = await resolvedProject(config.project ?? project), relative = typeof config.path === "string" ? config.path : ".", target = path.resolve(resolved.path, relative), root = resolved.path.endsWith(path.sep) ? resolved.path : resolved.path + path.sep;
@@ -146,6 +146,12 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph
const args = graphObject(config.arguments) ? structuredClone(config.arguments) : {}; if (context.workflowId) args.workflow_id = context.workflowId;
return { output: await callTool(tool, args, context, resolve), log: `Tool ${tool} completed.` };
}
+ if (node.type === "channel_send") {
+ if (typeof config.channelId !== "string" || !config.channelId) throw new Error("channel_send node requires channelId");
+ if (typeof config.text !== "string" || !config.text) throw new Error("channel_send node requires text");
+ const { sendChannelText } = await import("@/lib/channels");
+ return { output: await sendChannelText(config.channelId, { text: config.text, ...(typeof config.target === "string" && config.target ? { target: config.target } : {}) }), log: "Channel message sent." };
+ }
if (node.type === "integration") {
for (const key of ["user", "provider", "connection", "operation"]) if (typeof config[key] !== "string" || !config[key]) throw new Error(`integration node requires ${key}`);
const args = { user: config.user, provider: config.provider, connection: config.connection, operation: config.operation, ...(typeof config.tool === "string" ? { tool: config.tool } : {}), ...(graphObject(config.arguments) ? { arguments: config.arguments } : {}), ...(config.confirm === true ? { confirm: true } : {}), ...(context.workflowId ? { workflow_id: context.workflowId } : {}) };
diff --git a/lib/workflow/graph-schema.ts b/lib/workflow/graph-schema.ts
index e23fffb5..9cbc7f3a 100644
--- a/lib/workflow/graph-schema.ts
+++ b/lib/workflow/graph-schema.ts
@@ -108,7 +108,7 @@ export function parseWorkflowGraphDefinition(raw: unknown): WorkflowGraphDefinit
const edges = raw.edges.map((edge) => parseEdge(edge, nodeIds));
if (new Set(edges.map((edge) => edge.id)).size !== edges.length) throw new Error("duplicate workflow edge id");
const activeEdges = edges.filter((edge) => !edge.disabled);
- const triggerIds = new Set(nodes.filter((node) => ["manual", "schedule", "webhook"].includes(node.type)).map((node) => node.id));
+ const triggerIds = new Set(nodes.filter((node) => ["manual", "schedule", "webhook", "channel_trigger"].includes(node.type)).map((node) => node.id));
if (activeEdges.some((edge) => triggerIds.has(edge.target))) throw new Error("trigger nodes must be workflow roots");
assertAcyclic(nodes, activeEdges);
return { ...(typeof raw.id === "string" ? { id: raw.id } : {}), name: raw.name.trim(), description: raw.description, status: raw.status as WorkflowGraphStatus, inputs: structuredClone(raw.inputs), nodes, edges, metadata: parseMetadata(raw.metadata, nodeIds) };
diff --git a/lib/workflow/graph-store.ts b/lib/workflow/graph-store.ts
index 66f6f4f2..990df908 100644
--- a/lib/workflow/graph-store.ts
+++ b/lib/workflow/graph-store.ts
@@ -175,7 +175,7 @@ export async function listWorkflowGraphTriggerSources(): Promise<Array<{ owner:
const out: Array<{ owner: string; principal: string; graph: WorkflowGraph }> = [];
for (const owner of owners.filter((value) => /^[a-f0-9]{64}$/.test(value)).slice(0, 4096)) {
const store = await readStore(owner).catch(() => null); if (!store?.principal) continue;
- for (const graph of store.graphs) if (graph.status === "active" && graph.nodes.some((node) => node.type === "schedule" || node.type === "webhook")) out.push({ owner, principal: store.principal, graph });
+ for (const graph of store.graphs) if (graph.status === "active" && graph.nodes.some((node) => node.type === "schedule" || node.type === "webhook" || node.type === "channel_trigger")) out.push({ owner, principal: store.principal, graph });
}
return out;
}
diff --git a/lib/workflow/graph-triggers.ts b/lib/workflow/graph-triggers.ts
index c57efb9a..4a6f61f1 100644
--- a/lib/workflow/graph-triggers.ts
+++ b/lib/workflow/graph-triggers.ts
@@ -20,3 +20,5 @@ async function runScheduled(principal:string,owner:string,graph:Awaited<ReturnTy
export async function tickWorkflowScheduler(resolve:Resolver,now=new Date(),capabilities?:CapabilityRuntime){if(g.__msoWorkflowSchedulerBusy)return;g.__msoWorkflowSchedulerBusy=true;try{const sources=await listWorkflowGraphTriggerSources();let started=0;for(const source of sources){for(const node of source.graph.nodes.filter((row)=>row.type==="schedule"&&!row.disabled)){if(started>=50)return;let bucket:string|null=null;try{bucket=scheduleBucket(node,now,source.graph.metadata.timezone||"UTC");}catch{continue;}if(!bucket)continue;await runScheduled(source.principal,source.owner,source.graph,node,bucket,resolve,capabilities).catch(()=>undefined);started+=1;}}}finally{g.__msoWorkflowSchedulerBusy=false;}}
export function startWorkflowScheduler(resolve:Resolver,capabilities?:CapabilityRuntime){if(process.env.NODE_ENV==="test"||g.__msoWorkflowScheduler)return;void tickWorkflowScheduler(resolve,new Date(),capabilities);g.__msoWorkflowScheduler=setInterval(()=>void tickWorkflowScheduler(resolve,new Date(),capabilities),15_000);g.__msoWorkflowScheduler.unref();}
export async function findActiveWebhookSource(graphId:string,nodeId:string){for(const source of await listWorkflowGraphTriggerSources()){if(source.graph.id!==graphId)continue;const node=source.graph.nodes.find((row)=>row.id===nodeId&&row.type==="webhook"&&!row.disabled);if(node)return{...source,node};}return null;}
+
+export async function findActiveChannelSource(graphId:string,channelId:string){for(const source of await listWorkflowGraphTriggerSources()){if(source.graph.id!==graphId)continue;const nodes=source.graph.nodes.filter((row)=>row.type==="channel_trigger"&&!row.disabled),node=nodes.find((row)=>row.config.channelId===channelId)??nodes.find((row)=>!row.config.channelId);if(node)return{...source,node};}return null;}
diff --git a/lib/workflow/node-catalog.ts b/lib/workflow/node-catalog.ts
index d58bfde3..550a4350 100644
--- a/lib/workflow/node-catalog.ts
+++ b/lib/workflow/node-catalog.ts
@@ -4,6 +4,7 @@ export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[
{type:"manual",title:"Manual Trigger",category:"Triggers",description:"Start from UI, CLI or MCP.",defaults:{}},
{type:"schedule",title:"Schedule Trigger",category:"Triggers",description:"Run by cron or minute interval on the MSO server.",defaults:{mode:"interval",everyMinutes:60}},
{type:"webhook",title:"Webhook Trigger",category:"Triggers",description:"Public HTTP trigger with optional private-variable bearer auth.",defaults:{methods:["POST"],responseMode:"onReceived"}},
+ {type:"channel_trigger",title:"Channel Trigger",category:"Triggers",description:"Start from a verified MSO Channel inbound event. Bind a Channel ID from the Channels app.",defaults:{channelId:""}},
{type:"condition",title:"If",category:"Flow",description:"Route to true/false handles.",handles:["true","false"],defaults:{path:"input"}},
{type:"switch",title:"Switch",category:"Flow",description:"Route by multiple case handles plus default.",defaults:{path:"input",cases:[]}},
{type:"merge",title:"Merge",category:"Flow",description:"Merge enabled incoming node outputs.",defaults:{mode:"combine"}},
@@ -20,6 +21,7 @@ export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[
{type:"project_function",title:"Project Function",category:"Actions",description:"Call a project-owned function.",defaults:{}},
{type:"project_mcp",title:"Project MCP",category:"Actions",description:"Call a project-owned MCP tool.",defaults:{}},
{type:"integration",title:"Integration",category:"Actions",description:"Execute through an existing MSO integration connection; credentials stay outside the graph.",defaults:{}},
+ {type:"channel_send",title:"Channel Send",category:"Actions",description:"Send text through an existing MSO Channel. Channel credentials remain in Integrations.",defaults:{channelId:"",text:{"$ref":"input.event.text"}}},
{type:"script",title:"Script",category:"Actions",description:"Run a saved validated RASMIC script by project and script id.",defaults:{}},
{type:"agent",title:"Agent",category:"AI",description:"Run an organization seat or focused project agent action.",defaults:{wait:true,max_scope:"write"}},
{type:"subflow",title:"Subflow",category:"Flow",description:"Run an existing project flow.",defaults:{}},
diff --git a/scripts/cli/channels.sh b/scripts/cli/channels.sh
new file mode 100755
index 00000000..ccc1e591
--- /dev/null
+++ b/scripts/cli/channels.sh
@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+# Channels CLI. Channel configuration is metadata-only; credentials stay in Integrations.
+run_channels() {
+ local sub="${1:-list}" id="" input='{}' revision="" target="" message="" body
+ shift || true
+ case "$sub" in
+ save|delete|test|send) id="${1:?channel id required}"; shift ;;
+ esac
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --input) input="${2:?JSON or @file required}"; shift 2 ;;
+ --revision) revision="${2:?revision required}"; shift 2 ;;
+ --target) target="${2:?target required}"; shift 2 ;;
+ --text) message="${2:?message text required}"; shift 2 ;;
+ *) die "unknown channels option: $1" ;;
+ esac
+ done
+ if [ "${input:0:1}" = "@" ]; then input=$(cat -- "${input:1}"); fi
+ case "$sub" in
+ list) jget "/api/v1/channels" ;;
+ create)
+ body=$(jq -n --argjson data "$input" '{action:"create",data:$data}')
+ jpost "/api/v1/channels" "$body" ;;
+ save)
+ [ -n "$revision" ] || die "channels save requires --revision"
+ body=$(jq -n --arg id "$id" --argjson revision "$revision" --argjson data "$input" '{action:"update",id:$id,expectedRevision:$revision,data:$data}')
+ jpost "/api/v1/channels" "$body" ;;
+ delete)
+ [ -n "$revision" ] || die "channels delete requires --revision"
+ body=$(jq -n --arg id "$id" --argjson revision "$revision" '{action:"delete",id:$id,expectedRevision:$revision}')
+ jpost "/api/v1/channels" "$body" ;;
+ test)
+ body=$(jq -n --arg id "$id" '{action:"test",id:$id}')
+ jpost "/api/v1/channels" "$body" ;;
+ send)
+ [ -n "$message" ] || die "channels send requires --text"
+ body=$(jq -n --arg id "$id" --arg text "$message" --arg target "$target" '{action:"send",id:$id,text:$text}+if $target!="" then {target:$target} else {} end')
+ jpost "/api/v1/channels" "$body" ;;
+ *) die "usage: mso ${U_channels:-channels}" ;;
+ esac
+}
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
index e022ab18..67870f88 100755
--- a/scripts/cli/commands-runtime.sh
+++ b/scripts/cli/commands-runtime.sh
@@ -10,6 +10,7 @@ case "$cmd" in
setup) run_onboard "${1-}" ;;
onboard) run_onboard "${1-}" ;;
integrations) run_integrations "$@" ;;
+ channels) source "$ROOT/scripts/cli/channels.sh"; run_channels "$@" ;;
flow) source "$ROOT/scripts/cli/flows.sh"; run_flow "$@" ;;
workflow) source "$ROOT/scripts/cli/workflows.sh"; run_workflow "$@" ;;
provider|providers) run_provider "$@" ;;
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 97df9097..33de4c08 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -27,6 +27,7 @@ U_doctor="doctor [--fix]"
U_flow="flow list|inspect <id> [--project <project>]|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|save|delete <id> --revision <revision> [--input <JSON|@file>]"
U_workflow="workflow list|embeds|embed-save --input <JSON|@file>|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|runs <id>|versions <id>|restore <id> --revision <current> --version <saved>|catalog [--query q]|templates|template <id>|variables|variable-set <KEY> --input <JSON> [--secret]|variable-delete <KEY>|ai --prompt <text>"
U_integrations="integrations [interactive]|transfer|status|users|catalog|connections [user] [provider]|which [folder]|request|resolve <user> <provider> [connection]|create-user <id> [label]|create-connection <user> <provider> <id> <source> <auth>|manage <JSON>|setup|verify <user> <provider> <connection>|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute <JSON>"
+U_channels="channels list|create --input <JSON|@file>|save <id> --revision <n> --input <JSON|@file>|delete <id> --revision <n>|test <id>|send <id> --text <message> [--target <id>]"
U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"
U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"
@@ -93,7 +94,7 @@ mso_cli_main() {
case "$cmd" in
version|--version|-V|-v|ls|cat|raw|share|usage|search|project-candidates|write|mkdir|rm|mv|cp|zip|upload|exec|stats|ps|units|unit|packages|cleanup|status|health|doctor)
mso_cmd_host "$cmd" "$@" ;;
- agent|chat|model|setup|onboard|provider|providers|integrations|flow|workflow|gateway|web|camoufox|apps|mapp|term)
+ agent|chat|model|setup|onboard|provider|providers|integrations|channels|flow|workflow|gateway|web|camoufox|apps|mapp|term)
mso_cmd_runtime "$cmd" "$@" ;;
ai|cockpit|threads|agent-sessions|agents|org|a2a|memory|config|prefs|federation|models|skills|changelog|stock)
mso_cmd_state "$cmd" "$@" ;;