Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(channels): set up and manage Telegram, Discord, Slack and Signal from clients

Salman Qureshi049d9580b3a1
diff --git a/src/channels/credential-check.test.ts b/src/channels/credential-check.test.ts
new file mode 100644
index 00000000..95d7a997
--- /dev/null
+++ b/src/channels/credential-check.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it, vi } from 'vitest';
+import { checkDiscord, checkSignal, checkSlack, checkTelegram } from './credential-check.js';
+
+const reply = (...rs: Array<[number, unknown]>) => {
+ const f = vi.fn();
+ for (const [status, body] of rs) f.mockResolvedValueOnce({ status, json: async () => body });
+ return f as unknown as typeof fetch;
+};
+const TG = '123456789:AAEabcdefghijklmnopqrstuvwxyz0123456';
+const DC = 'MTIz' + 'NDU2Nzg5MDEyMzQ1Njc4.GabcDe.abcdefghijklmnopqrstuvwxyz0123';
+
+describe('channel credential checks', () => {
+ it('Telegram: shape first, then getMe names the bot', async () => {
+ expect((await checkTelegram('nope')).field).toBe('botToken');
+ expect(await checkTelegram(TG, reply([200, { ok: true, result: { username: 'mercury_bot' } }]))).toMatchObject({ ok: true, identity: '@mercury_bot' });
+ expect(await checkTelegram(TG, reply([401, { ok: false }]))).toMatchObject({ ok: false, field: 'botToken' });
+ });
+
+ it('Discord: a valid bot that is not in the server points at the server ID', async () => {
+ const r = await checkDiscord(DC, '111', undefined, reply([200, { username: 'Mercury' }], [404, {}]));
+ expect(r).toMatchObject({ ok: false, field: 'guildId' });
+ expect(await checkDiscord(DC, '111', '222', reply([200, { username: 'Mercury' }], [200, { name: 'Cosmic' }], [200, {}]))).toMatchObject({ ok: true, message: 'Connected as Mercury in Cosmic.' });
+ expect(await checkDiscord(DC, undefined, undefined, reply([401, {}]))).toMatchObject({ field: 'botToken' });
+ });
+
+ it('Slack: checks the bot token and the app-level token separately', async () => {
+ const bot = 'xoxb' + '-1234567890-abcdefghijklmnopqrst';
+ const app = 'xapp' + '-1-A123-4567890-abcdefghijklmnop';
+ expect((await checkSlack('xoxp' + '-wrong-kind', app)).field).toBe('botToken');
+ expect(await checkSlack(bot, app, reply([200, { ok: true, user: 'mercury', team: 'Cosmic Stack' }], [200, { ok: false, error: 'missing_scope' }]))).toMatchObject({ ok: false, field: 'appToken', message: expect.stringMatching(/connections:write/) });
+ expect(await checkSlack(bot, app, reply([200, { ok: true, user: 'mercury', team: 'Cosmic Stack' }], [200, { ok: true, url: 'wss://x' }]))).toMatchObject({ ok: true, identity: '@mercury in Cosmic Stack' });
+ });
+
+ it('Signal: local checks, in the order a person can fix them', () => {
+ expect(checkSignal('0300', { binary: '/x', javaOk: true, accounts: [] }).field).toBe('phoneNumber');
+ expect(checkSignal('+923001234567', { binary: null, javaOk: false, accounts: [] }).message).toMatch(/isn't installed/);
+ expect(checkSignal('+923001234567', { binary: '/x', javaOk: false, accounts: [] }).message).toMatch(/Java 17/);
+ expect(checkSignal('+923001234567', { binary: '/x', javaOk: true, accounts: [] }).message).toMatch(/Link a device/);
+ expect(checkSignal('+923001234567', { binary: '/x', javaOk: true, accounts: ['+923001234567'] }).ok).toBe(true);
+ });
+});
diff --git a/src/channels/credential-check.ts b/src/channels/credential-check.ts
new file mode 100644
index 00000000..3f40a167
--- /dev/null
+++ b/src/channels/credential-check.ts
@@ -0,0 +1,111 @@
+/**
+ * Check a messaging channel's credentials before they're saved: one cheap,
+ * read-only call per service, with what was found (the bot's name, the
+ * workspace) or which field is wrong. Signal is checked locally only: its
+ * own tools stop a running Signal, so nothing here touches signal-cli.
+ */
+
+import { existsSync, readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+type Fetch = typeof fetch;
+
+export interface ChannelCheck {
+ ok: boolean;
+ /** What the credentials belong to, e.g. "@mercury_bot" or "Cosmic Stack (Slack)". */
+ identity?: string;
+ message: string;
+ field?: string;
+}
+
+async function getJson(f: Fetch, url: string, init: RequestInit = {}): Promise<{ status: number; body: any }> {
+ const res = await f(url, { ...init, signal: AbortSignal.timeout(10_000) });
+ let body: any = null;
+ try { body = await res.json(); } catch { /* not JSON */ }
+ return { status: res.status, body };
+}
+
+function offline(service: string, err: unknown): ChannelCheck {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { ok: false, message: /timeout|abort/i.test(msg) ? `${service} didn't answer in 10 seconds. Check your connection.` : `Couldn't reach ${service}: ${msg}` };
+}
+
+export const TOKEN_SHAPES = {
+ telegram: /^\d{5,}:[A-Za-z0-9_-]{30,}$/,
+ discord: /^[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{20,}$/,
+ slackBot: /^xoxb-[A-Za-z0-9-]{20,}$/,
+ slackApp: /^xapp-[A-Za-z0-9-]{20,}$/,
+ phone: /^\+[1-9]\d{6,14}$/,
+};
+
+export async function checkTelegram(token: string, f: Fetch = fetch): Promise<ChannelCheck> {
+ if (!TOKEN_SHAPES.telegram.test(token)) return { ok: false, field: 'botToken', message: 'That doesn\'t look like a Telegram bot token (it looks like 123456789:AAE…). Copy it again from @BotFather.' };
+ try {
+ const r = await getJson(f, `https://api.telegram.org/bot${token}/getMe`);
+ if (r.status === 401 || r.status === 404) return { ok: false, field: 'botToken', message: 'Telegram rejected this token. Get the current one from @BotFather (/token).' };
+ if (!r.body?.ok) return { ok: false, message: `Telegram answered ${r.status}${r.body?.description ? `: ${r.body.description}` : ''}.` };
+ const u = r.body.result as { username?: string; first_name?: string };
+ return { ok: true, identity: u.username ? `@${u.username}` : u.first_name, message: `Connected to ${u.username ? `@${u.username}` : 'your bot'}.` };
+ } catch (err) { return offline('Telegram', err); }
+}
+
+export async function checkDiscord(token: string, guildId: string | undefined, channelId: string | undefined, f: Fetch = fetch): Promise<ChannelCheck> {
+ if (!TOKEN_SHAPES.discord.test(token)) return { ok: false, field: 'botToken', message: 'That doesn\'t look like a Discord bot token. Copy it from the Developer Portal → your app → Bot → Reset Token.' };
+ const auth = { headers: { Authorization: `Bot ${token}` } };
+ try {
+ const me = await getJson(f, 'https://discord.com/api/v10/users/@me', auth);
+ if (me.status === 401) return { ok: false, field: 'botToken', message: 'Discord rejected this token. Reset it in the Developer Portal and paste the new one.' };
+ if (me.status !== 200) return { ok: false, message: `Discord answered ${me.status}.` };
+ const name = me.body?.username as string | undefined;
+ if (guildId) {
+ const g = await getJson(f, `https://discord.com/api/v10/guilds/${encodeURIComponent(guildId)}`, auth);
+ if (g.status === 403 || g.status === 404) return { ok: false, field: 'guildId', message: `${name ?? 'The bot'} isn't in that server. Invite it with the OAuth2 URL from the Developer Portal, or check the server ID.` };
+ if (channelId) {
+ const ch = await getJson(f, `https://discord.com/api/v10/channels/${encodeURIComponent(channelId)}`, auth);
+ if (ch.status === 403 || ch.status === 404) return { ok: false, field: 'channelId', message: 'The bot can\'t see that channel. Check the channel ID and the bot\'s permissions there.' };
+ }
+ return { ok: true, identity: name, message: `Connected as ${name ?? 'your bot'} in ${g.body?.name ?? 'the server'}.` };
+ }
+ return { ok: true, identity: name, message: `Connected as ${name ?? 'your bot'}.` };
+ } catch (err) { return offline('Discord', err); }
+}
+
+export async function checkSlack(botToken: string, appToken: string, f: Fetch = fetch): Promise<ChannelCheck> {
+ if (!TOKEN_SHAPES.slackBot.test(botToken)) return { ok: false, field: 'botToken', message: 'The bot token starts with xoxb-. Find it under OAuth & Permissions in your Slack app.' };
+ if (!TOKEN_SHAPES.slackApp.test(appToken)) return { ok: false, field: 'appToken', message: 'The app-level token starts with xapp-. Create one under Basic Information → App-Level Tokens with connections:write.' };
+ try {
+ const bot = await getJson(f, 'https://slack.com/api/auth.test', { method: 'POST', headers: { Authorization: `Bearer ${botToken}` } });
+ if (!bot.body?.ok) return { ok: false, field: 'botToken', message: bot.body?.error === 'invalid_auth' || bot.body?.error === 'not_authed' ? 'Slack rejected the bot token.' : `Slack: ${bot.body?.error ?? bot.status}.` };
+ const app = await getJson(f, 'https://slack.com/api/apps.connections.open', { method: 'POST', headers: { Authorization: `Bearer ${appToken}` } });
+ if (!app.body?.ok) {
+ const why = app.body?.error === 'invalid_auth' ? 'Slack rejected the app-level token.'
+ : app.body?.error === 'missing_scope' ? 'The app-level token needs the connections:write scope.'
+ : app.body?.error === 'not_allowed_token_type' ? 'That\'s not an app-level token (it should start with xapp-).'
+ : `Slack: ${app.body?.error ?? app.status}. Is Socket Mode on for the app?`;
+ return { ok: false, field: 'appToken', message: why };
+ }
+ const who = `${bot.body.user ? `@${bot.body.user}` : 'the bot'} in ${bot.body.team ?? 'your workspace'}`;
+ return { ok: true, identity: who, message: `Connected as ${who}.` };
+ } catch (err) { return offline('Slack', err); }
+}
+
+/** Numbers signal-cli has an account for (linked or registered on this computer). */
+export function signalAccounts(dataDir = process.env.SIGNAL_CLI_CONFIG_DIR || join(homedir(), '.local', 'share', 'signal-cli')): string[] {
+ const p = join(dataDir, 'data', 'accounts.json');
+ if (!existsSync(p)) return [];
+ try {
+ const parsed = JSON.parse(readFileSync(p, 'utf-8')) as { accounts?: Array<{ number?: string }> };
+ return (parsed.accounts ?? []).map((a) => a.number).filter((n): n is string => typeof n === 'string');
+ } catch {
+ return [];
+ }
+}
+
+export function checkSignal(phone: string, opts: { binary: string | null; javaOk: boolean; accounts: string[] }): ChannelCheck {
+ if (!TOKEN_SHAPES.phone.test(phone)) return { ok: false, field: 'phoneNumber', message: 'Use the full number with country code, like +923001234567.' };
+ if (!opts.binary) return { ok: false, message: 'Signal\'s helper program (signal-cli) isn\'t installed yet. Use "Link a device" to set it up.' };
+ if (!opts.javaOk) return { ok: false, message: 'signal-cli needs Java 17 or newer on this computer. Install it (e.g. `brew install openjdk@17`), then check again.' };
+ if (!opts.accounts.includes(phone)) return { ok: false, field: 'phoneNumber', message: 'This number isn\'t linked on this computer yet. Use "Link a device" and scan the code with Signal on your phone.' };
+ return { ok: true, identity: phone, message: `${phone} is linked on this computer.` };
+}
diff --git a/src/channels/registry.ts b/src/channels/registry.ts
index 63602201..13f39bd9 100644
--- a/src/channels/registry.ts
+++ b/src/channels/registry.ts
@@ -8,6 +8,9 @@ import { SlackChannel } from './slack.js';
import type { MercuryConfig } from '../utils/config.js';
import { logger } from '../utils/logger.js';
+/** The messaging channels Mercury runs itself (WhatsApp is a plugin). */
+export type ExternalChannel = 'telegram' | 'signal' | 'discord' | 'slack';
+
export class ChannelRegistry {
private channels: Map<ChannelType, Channel> = new Map();
@@ -53,6 +56,48 @@ export class ChannelRegistry {
}
}
+ /** Whether config has what a messaging channel needs to start. */
+ static configured(config: MercuryConfig, type: ExternalChannel): boolean {
+ const c = config.channels;
+ if (type === 'telegram') return c.telegram.enabled && !!c.telegram.botToken;
+ if (type === 'signal') return c.signal.enabled && !!c.signal.phoneNumber;
+ if (type === 'discord') return c.discord.enabled && !!c.discord.botToken;
+ return c.slack.enabled && !!c.slack.botToken && !!c.slack.appToken;
+ }
+
+ private static create(config: MercuryConfig, type: ExternalChannel): Channel {
+ if (type === 'telegram') return new TelegramChannel(config);
+ if (type === 'signal') return new SignalChannel(config);
+ if (type === 'discord') return new DiscordChannel(config);
+ return new SlackChannel(config);
+ }
+
+ /**
+ * Stop one messaging channel and, if config says it should run, start a
+ * fresh one from the same live config: new tokens, turned on or off, all
+ * without restarting Mercury. `wire` repeats the boot-time wiring on the
+ * new instance (chat commands). Resolves with whether it came up.
+ */
+ async restart(type: ExternalChannel, config: MercuryConfig, wire?: (channel: Channel) => void): Promise<{ running: boolean; error?: string }> {
+ const old = this.channels.get(type);
+ if (old) {
+ try { await old.stop(); } catch (err) { logger.warn({ channel: type, err }, 'Stopping the old channel failed'); }
+ this.unregister(type, old);
+ }
+ if (!ChannelRegistry.configured(config, type)) return { running: false };
+ const next = ChannelRegistry.create(config, type);
+ this.register(type, next);
+ try { wire?.(next); } catch (err) { logger.warn({ channel: type, err }, 'Wiring the restarted channel failed'); }
+ try {
+ await next.start();
+ } catch (err) {
+ return { running: false, error: err instanceof Error ? err.message : String(err) };
+ }
+ // Telegram and Discord log in in the background: give them a moment to come up.
+ for (let i = 0; i < 40 && !next.isReady(); i++) await new Promise((r) => setTimeout(r, 200));
+ return { running: next.isReady() };
+ }
+
getCliChannel(): CLIChannel | undefined {
return this.channels.get('cli') as CLIChannel | undefined;
}
diff --git a/src/index.ts b/src/index.ts
index d50b7af1..e8df5e9b 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -73,6 +73,7 @@ import { SpotifyClient } from './spotify/client.js';
import { ChannelRegistry } from './channels/registry.js';
import { CLIChannel } from './channels/cli.js';
import { TelegramChannel } from './channels/telegram.js';
+import type { Channel } from './channels/base.js';
import { SignalChannel } from './channels/signal.js';
import { DiscordChannel } from './channels/discord.js';
import { WebChannel } from './channels/web.js';
@@ -100,6 +101,7 @@ import { setFirstProviderHandler, setProvidersReload } from './web/api/providers
import { setCloudReload } from './web/api/cloud.js';
import { spawnDetachedRestart } from './cli/daemon.js';
import { recordVoiceCalls } from './plugins/voice-calls.js';
+import { setChannelRuntime } from './web/api/channels.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken, initWebAuth } from './web/auth.js';
import { startLoopLagMonitor } from './utils/loop-lag.js';
import { McpManager, probeMcpServer, validateMcpConfig, type McpServerStatus } from './capabilities/mcp/index.js';
@@ -3471,6 +3473,17 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
sigChannel.setChatCommandContext(capabilities.getChatCommandContext()!);
}
+ // Settings → Channels: changes apply to this live config, and a channel restarts on its own.
+ const wireChannel = (ch: Channel) => {
+ if (ch instanceof TelegramChannel || ch instanceof SignalChannel) ch.setChatCommandContext(capabilities.getChatCommandContext()!);
+ };
+ setChannelRuntime({
+ config: () => config,
+ restart: (type) => channels.restart(type, config, wireChannel),
+ running: (type) => channels.get(type)?.isReady() ?? false,
+ notify: (type, target, text) => channels.get(type)?.send(text, target) ?? Promise.resolve(),
+ });
+
setWebWebChannel(webChannel);
setWebSessionSyncEnabled(() => agent.isSessionSyncEnabled());
setWebProgrammingMode(agent.programmingMode);
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 4d8ec903..4e11d535 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -40,6 +40,7 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'chat.stop', // POST /api/chat/stop — interrupt the running turn (same as /stop)
'providers.manage', // GET /api/providers/settings, POST /api/providers/:id/check (live, unsaved), PUT /api/providers/roles; saves apply live; health.setupRequired
'voice.check',
+ 'channels', // GET /api/channels, POST :type/check, PUT :type, POST :type/access, POST/GET signal/link
'transcribe', // GET/POST /api/transcribe — dictation: raw audio in, text out
'cloud.signin', // GET /api/cloud/status, POST/GET/DELETE /api/cloud/signin (browser pairing from any client) // POST /api/voice/check { vendor, key?, endpoint? }
'brain.map', // GET /api/brain/map[?archive=1] — themes, sub-themes, notes, related links
diff --git a/src/web/api/channels-route.test.ts b/src/web/api/channels-route.test.ts
new file mode 100644
index 00000000..e4f689c7
--- /dev/null
+++ b/src/web/api/channels-route.test.ts
@@ -0,0 +1,88 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+
+const home = await vi.hoisted(async () => {
+ const fs = await import('node:fs');
+ const os = await import('node:os');
+ const path = await import('node:path');
+ for (const k of ['TELEGRAM_BOT_TOKEN', 'TELEGRAM_ENABLED', 'DISCORD_BOT_TOKEN', 'SLACK_BOT_TOKEN', 'SLACK_APP_TOKEN', 'SIGNAL_PHONE_NUMBER']) delete process.env[k];
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-channels-route-'));
+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), [
+ 'identity:', ' owner: Test',
+ 'channels:', ' telegram:', ' enabled: true', ' botToken: "123456789:AAEsavedsavedsavedsavedsavedsaved00"',
+ ' admins:', ' - userId: 1', ' chatId: 1', ' firstName: Salman', ' approvedAt: "2026-10-01T00:00:00.000Z"',
+ ' members: []',
+ ' pending:', ' - userId: 2', ' chatId: 22', ' firstName: Heer', ' requestedAt: "2026-10-27T00:00:00.000Z"',
+ '',
+ ].join('\n'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+import channels, { applyAccess, setChannelTestHooks } from './channels.js';
+import { loadConfig } from '../../utils/config.js';
+
+const call = (method: string, path: string, body?: unknown) => channels.request(`http://127.0.0.1${path}`, { method, headers: { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
+const yaml = () => readFileSync(join(home, 'mercury.yaml'), 'utf-8');
+
+describe('channels settings', () => {
+ it('lists every channel with keys hidden and people in one shape', async () => {
+ const body = (await (await call('GET', '/api/channels')).json()) as any;
+ expect(body.channels.map((c: any) => c.type)).toEqual(['telegram', 'discord', 'slack', 'signal']);
+ const tg = body.channels[0];
+ expect(tg.settings.botToken).toBe('1234••••ed00');
+ expect(JSON.stringify(body)).not.toContain('savedsaved');
+ expect(tg.access.admins).toEqual([expect.objectContaining({ id: '1', name: 'Salman', role: 'admin' })]);
+ expect(tg.access.pending).toEqual([expect.objectContaining({ id: '2', name: 'Heer' })]);
+ });
+
+ it('approves a request, and refuses to leave the channel without an admin', async () => {
+ const ok = await call('POST', '/api/channels/telegram/access', { action: 'approve', id: '2' });
+ expect(ok.status).toBe(200);
+ expect(((await ok.json()) as any).channel.access.members).toEqual([expect.objectContaining({ id: '2' })]);
+ expect((await call('POST', '/api/channels/telegram/access', { action: 'remove', id: '1' })).status).toBe(409);
+ expect((await call('POST', '/api/channels/telegram/access', { action: 'demote', id: '1' })).status).toBe(409);
+ expect((await call('POST', '/api/channels/telegram/access', { action: 'promote', id: '2' })).status).toBe(200);
+ expect((await call('POST', '/api/channels/telegram/access', { action: 'demote', id: '1' })).status).toBe(200);
+ expect(yaml()).toMatch(/admins:\n\s+- userId: 2/);
+ });
+
+ it('never saves a hidden key, and never turns on with credentials that fail', async () => {
+ expect((await call('PUT', '/api/channels/telegram', { botToken: '1234••••ed00' })).status).toBe(400);
+ setChannelTestHooks({ fetch: vi.fn().mockResolvedValue({ status: 401, json: async () => ({ ok: false }) }) as never });
+ const bad = await call('PUT', '/api/channels/discord', { enabled: true, botToken: 'MTIz' + 'NDU2Nzg5MDEyMzQ1Njc4.GabcDe.abcdefghijklmnopqrstuvwxyz0123' });
+ expect(bad.status).toBe(400);
+ expect(((await bad.json()) as any).field).toBe('botToken');
+ expect(loadConfig().channels.discord.enabled).toBe(false);
+ });
+
+ it('saves Slack once both tokens check out', async () => {
+ const f = vi.fn()
+ .mockResolvedValueOnce({ status: 200, json: async () => ({ ok: true, user: 'mercury', team: 'Cosmic' }) })
+ .mockResolvedValueOnce({ status: 200, json: async () => ({ ok: true }) });
+ setChannelTestHooks({ fetch: f as never });
+ const res = await call('PUT', '/api/channels/slack', { enabled: true, botToken: 'xoxb' + '-1234567890-abcdefghijklmnopqrst', appToken: 'xapp' + '-1-A123-4567890-abcdefghijklmnop', channelId: 'C123' });
+ const body = (await res.json()) as any;
+ expect(res.status).toBe(200);
+ expect(body.identity).toBe('@mercury in Cosmic');
+ expect(body.channel.settings).toMatchObject({ hasBotToken: true, hasAppToken: true, channelId: 'C123' });
+ expect(loadConfig().channels.slack.enabled).toBe(true);
+ });
+
+ it('Signal is checked locally and can be turned off without any check', async () => {
+ setChannelTestHooks({ signal: () => ({ binary: '/x', javaOk: true, accounts: ['+923001234567'] }) });
+ const r = await call('PUT', '/api/channels/signal', { enabled: true, phoneNumber: '+92 300 1234567', mode: 'private' });
+ expect(r.status).toBe(200);
+ expect(loadConfig().channels.signal).toMatchObject({ phoneNumber: '+923001234567', mode: 'private', enabled: true });
+ expect((await call('PUT', '/api/channels/signal', { enabled: false })).status).toBe(200);
+ });
+
+ it('Discord and Slack keep the role field in step when promoting', () => {
+ const cfg = loadConfig();
+ cfg.channels.discord.admins = [{ userId: 'a', role: 'admin', approvedAt: 'x' } as any];
+ cfg.channels.discord.members = [{ userId: 'b', role: 'member', approvedAt: 'x' } as any];
+ expect(applyAccess('discord', cfg, 'promote', 'b')).toEqual({ ok: true });
+ expect(cfg.channels.discord.admins.find((u) => u.userId === 'b')?.role).toBe('admin');
+ });
+});
diff --git a/src/web/api/channels.ts b/src/web/api/channels.ts
new file mode 100644
index 00000000..2f848947
--- /dev/null
+++ b/src/web/api/channels.ts
@@ -0,0 +1,336 @@
+import { Hono } from 'hono';
+import {
+ approveDiscordPendingRequest, approveSignalPendingRequest, approveSlackPendingRequest, approveTelegramPendingRequest,
+ clearDiscordAccess, clearSignalAccess, clearSlackAccess, clearTelegramAccess,
+ loadConfig, rejectDiscordPendingRequest, rejectSignalPendingRequest, rejectSlackPendingRequest, rejectTelegramPendingRequest,
+ saveConfig, type MercuryConfig,
+} from '../../utils/config.js';
+import { checkDiscord, checkSignal, checkSlack, checkTelegram, signalAccounts, TOKEN_SHAPES, type ChannelCheck } from '../../channels/credential-check.js';
+import type { ExternalChannel } from '../../channels/registry.js';
+import { logger } from '../../utils/logger.js';
+import { checkJavaAvailable, findSignalCli, isNativeBinary } from '../../signal/binary.js';
+
+/**
+ * Messaging channels (Telegram, Discord, Slack, Signal) from any client:
+ * set up and change credentials (checked live first), turn on and off, and
+ * manage who may talk to Mercury. WhatsApp is a plugin (/api/plugins).
+ *
+ * GET /api/channels every channel: settings (keys masked), running, people
+ * POST /api/channels/:type/check test what's typed, nothing saved
+ * PUT /api/channels/:type save settings / on-off; the channel restarts by itself
+ * POST /api/channels/:type/access { action: approve|reject|remove|promote|demote|reset, id?, role? }
+ * POST /api/channels/signal/link link this computer to a Signal account (QR), then poll GET
+ *
+ * Changes go to the live config the running channels read, then to disk, so
+ * a channel's own next save can never undo them; credentials and on/off
+ * restart just that channel.
+ */
+
+export interface ChannelRuntime {
+ /** The live config object the channels hold. */
+ config(): MercuryConfig;
+ restart(type: ExternalChannel): Promise<{ running: boolean; error?: string }>;
+ running(type: ExternalChannel): boolean;
+ /** Tell someone they were let in (best effort, through the running channel). */
+ notify(type: ExternalChannel, target: string, text: string): Promise<void>;
+}
+
+let runtime: ChannelRuntime | null = null;
+export function setChannelRuntime(r: ChannelRuntime | null): void { runtime = r; }
+
+type Fetch = typeof fetch;
+let doFetch: Fetch | undefined;
+let signalProbe: () => { binary: string | null; javaOk: boolean; accounts: string[] } = defaultSignalProbe;
+/** Test seams. */
+export function setChannelTestHooks(h: { fetch?: Fetch; signal?: typeof signalProbe }): void {
+ if (h.fetch !== undefined) doFetch = h.fetch;
+ if (h.signal) signalProbe = h.signal;
+}
+
+/** Local only: never downloads signal-cli and never starts it (that would stop a running Signal). */
+function defaultSignalProbe() {
+ const binary = findSignalCli();
+ // A native build runs on its own; the JAR (and its launcher) needs Java 17+.
+ const javaOk = !!binary && (isNativeBinary(binary) || checkJavaAvailable());
+ return { binary, javaOk, accounts: signalAccounts() };
+}
+
+const TYPES: ExternalChannel[] = ['telegram', 'discord', 'slack', 'signal'];
+const LABEL: Record<ExternalChannel, string> = { telegram: 'Telegram', discord: 'Discord', slack: 'Slack', signal: 'Signal' };
+
+function isType(t: string): t is ExternalChannel {
+ return (TYPES as string[]).includes(t);
+}
+
+function live(): MercuryConfig {
+ return runtime ? runtime.config() : loadConfig();
+}
+
+function persist(config: MercuryConfig): void {
+ saveConfig(config);
+}
+
+function mask(v: string | undefined): string {
+ if (!v) return '';
+ return v.length < 10 ? '••••••' : `${v.slice(0, 4)}••••${v.slice(-4)}`;
+}
+
+const masked = (v: unknown) => typeof v === 'string' && v.includes('•');
+
+// ── People, in one shape for every channel ──────────────────────────────────
+
+interface Person { id: string; name: string; detail?: string; role: 'admin' | 'member'; since?: string }
+interface Pending { id: string; name: string; detail?: string; code?: string; requestedAt?: string }
+
+function people(type: ExternalChannel, c: MercuryConfig['channels']) {
+ const ch = c[type] as unknown as { admins: any[]; members: any[]; pending: any[] };
+ const person = (u: any, role: 'admin' | 'member'): Person => {
+ if (type === 'telegram') return { id: String(u.userId), name: u.firstName || (u.username ? `@${u.username}` : String(u.userId)), detail: u.username ? `@${u.username}` : undefined, role, since: u.approvedAt };
+ if (type === 'signal') return { id: u.phoneNumber, name: u.name || u.phoneNumber, detail: u.name ? u.phoneNumber : undefined, role, since: u.pairedAt };
+ if (type === 'slack') return { id: u.userId, name: u.displayName || u.userName || u.userId, detail: u.userName ? `@${u.userName}` : undefined, role, since: u.approvedAt };
+ return { id: u.userId, name: u.displayName || u.username || u.userId, detail: u.username ? `@${u.username}` : undefined, role, since: u.approvedAt };
+ };
+ const pending = (u: any): Pending => {
+ const id = type === 'signal' ? u.phoneNumber : String(u.userId);
+ const name = type === 'telegram' ? (u.firstName || (u.username ? `@${u.username}` : id)) : type === 'signal' ? (u.name || u.phoneNumber) : (u.displayName || u.username || u.userName || id);
+ return { id, name, detail: u.username ? `@${u.username}` : u.userName ? `@${u.userName}` : undefined, code: u.pairingCode, requestedAt: u.requestedAt };
+ };
+ return {
+ admins: (ch.admins ?? []).map((u) => person(u, 'admin')),
+ members: (ch.members ?? []).map((u) => person(u, 'member')),
+ pending: (ch.pending ?? []).map(pending),
+ };
+}
+
+function describe(type: ExternalChannel, config: MercuryConfig) {
+ const c = config.channels;
+ const settings: Record<string, unknown> =
+ type === 'telegram' ? { botToken: mask(c.telegram.botToken), hasBotToken: !!c.telegram.botToken, streaming: c.telegram.streaming !== false }
+ : type === 'discord' ? { botToken: mask(c.discord.botToken), hasBotToken: !!c.discord.botToken, guildId: c.discord.guildId ?? '', channelId: c.discord.channelId ?? '', adminRoleName: c.discord.adminRoleName ?? '', streaming: c.discord.streaming !== false }
+ : type === 'slack' ? { botToken: mask(c.slack.botToken), hasBotToken: !!c.slack.botToken, appToken: mask(c.slack.appToken), hasAppToken: !!c.slack.appToken, channelId: c.slack.channelId ?? '', streaming: c.slack.streaming !== false }
+ : { phoneNumber: c.signal.phoneNumber ?? '', mode: c.signal.mode || 'group', groupName: c.signal.groupName ?? '', groupId: c.signal.groupId ?? '' };
+ const ch = c[type] as { enabled: boolean };
+ const configured = type === 'telegram' ? !!c.telegram.botToken : type === 'discord' ? !!c.discord.botToken : type === 'slack' ? !!c.slack.botToken && !!c.slack.appToken : !!c.signal.phoneNumber;
+ return {
+ type,
+ label: LABEL[type],
+ enabled: ch.enabled,
+ configured,
+ running: runtime?.running(type) ?? false,
+ settings,
+ access: people(type, c),
+ };
+}
+
+// ── Drafts and checks ───────────────────────────────────────────────────────
+
+type Draft = Record<string, unknown>;
+
+/** What the channel's credentials would be after this edit (an empty or omitted secret keeps the saved one). */
+function merged(type: ExternalChannel, config: MercuryConfig, body: Draft): Record<string, string> {
+ const c = config.channels;
+ const keep = (v: unknown, saved: string | undefined) => (typeof v === 'string' && v.trim() && !masked(v) ? v.trim() : saved ?? '');
+ const text = (v: unknown, saved: string | undefined) => (typeof v === 'string' ? v.trim() : saved ?? '');
+ if (type === 'telegram') return { botToken: keep(body.botToken, c.telegram.botToken) };
+ if (type === 'discord') return { botToken: keep(body.botToken, c.discord.botToken), guildId: text(body.guildId, c.discord.guildId), channelId: text(body.channelId, c.discord.channelId), adminRoleName: text(body.adminRoleName, c.discord.adminRoleName) };
+ if (type === 'slack') return { botToken: keep(body.botToken, c.slack.botToken), appToken: keep(body.appToken, c.slack.appToken), channelId: text(body.channelId, c.slack.channelId) };
+ return { phoneNumber: text(body.phoneNumber, c.signal.phoneNumber).replace(/[\s-]/g, ''), mode: text(body.mode, c.signal.mode || 'group'), groupName: text(body.groupName, c.signal.groupName) };
+}
+
+async function check(type: ExternalChannel, d: Record<string, string>): Promise<ChannelCheck> {
+ if (type === 'telegram') return checkTelegram(d.botToken, doFetch);
+ if (type === 'discord') return checkDiscord(d.botToken, d.guildId || undefined, d.channelId || undefined, doFetch);
+ if (type === 'slack') return checkSlack(d.botToken, d.appToken, doFetch);
+ return checkSignal(d.phoneNumber, signalProbe());
+}
+
+function maskedProblem(body: Draft): string | null {
+ for (const k of ['botToken', 'appToken']) if (masked(body[k])) return k;
+ return null;
+}
+
+// ── Routes ──────────────────────────────────────────────────────────────────
+
+const channels = new Hono();
+
+channels.get('/api/channels', (c) => {
+ const config = live();
+ return c.json({ channels: TYPES.map((t) => describe(t, config)), liveRestart: !!runtime });
+});
+
+channels.post('/api/channels/:type/check', async (c) => {
+ const type = c.req.param('type');
+ if (!isType(type)) return c.json({ ok: false, message: 'Unknown channel' }, 400);
+ const body = (await c.req.json().catch(() => ({}))) as Draft;
+ const bad = maskedProblem(body);
+ if (bad) return c.json({ ok: false, field: bad, message: 'That is the hidden form of the saved key. Paste the full key, or leave it empty to keep the saved one.' });
+ return c.json(await check(type, merged(type, live(), body)));
+});
+
+channels.put('/api/channels/:type', async (c) => {
+ const type = c.req.param('type');
+ if (!isType(type)) return c.json({ error: 'Unknown channel' }, 400);
+ const body = (await c.req.json().catch(() => ({}))) as Draft;
+ const bad = maskedProblem(body);
+ if (bad) return c.json({ error: 'That is the hidden form of the saved key. Paste the full key, or leave it empty to keep the saved one.', field: bad }, 400);
+ if (body.enabled !== undefined && typeof body.enabled !== 'boolean') return c.json({ error: 'enabled must be true or false' }, 400);
+ if (type === 'signal' && body.mode !== undefined && body.mode !== 'group' && body.mode !== 'private') return c.json({ error: 'mode is group or private', field: 'mode' }, 400);
+
+ const config = live();
+ const ch = config.channels[type] as { enabled: boolean };
+ const d = merged(type, config, body);
+ const willRun = typeof body.enabled === 'boolean' ? body.enabled : ch.enabled;
+ // Never turn on (or keep running) with credentials that don't work.
+ let identity: string | undefined;
+ if (willRun) {
+ const r = await check(type, d);
+ if (!r.ok) return c.json({ error: r.message, field: r.field }, 400);
+ identity = r.identity;
+ }
+
+ const cc = config.channels;
+ if (type === 'telegram') cc.telegram.botToken = d.botToken;
+ if (type === 'discord') Object.assign(cc.discord, { botToken: d.botToken, guildId: d.guildId || undefined, channelId: d.channelId || undefined, adminRoleName: d.adminRoleName || undefined });
+ if (type === 'slack') Object.assign(cc.slack, { botToken: d.botToken, appToken: d.appToken, channelId: d.channelId || undefined });
+ if (type === 'signal') {
+ if (cc.signal.phoneNumber && d.phoneNumber !== cc.signal.phoneNumber) { cc.signal.groupId = undefined; }
+ Object.assign(cc.signal, { phoneNumber: d.phoneNumber, mode: d.mode, groupName: d.groupName || cc.signal.groupName });
+ }
+ if (typeof body.streaming === 'boolean' && type !== 'signal') (cc[type] as { streaming?: boolean }).streaming = body.streaming;
+ if (typeof body.enabled === 'boolean') ch.enabled = body.enabled;
+ persist(config);
+
+ let state: { running: boolean; error?: string } = { running: false };
+ if (runtime) {
+ try { state = await runtime.restart(type); } catch (err) { state = { running: false, error: err instanceof Error ? err.message : String(err) }; }
+ }
+ return c.json({ ok: true, channel: describe(type, config), identity, ...state, restartRequired: !runtime });
+});
+
+channels.post('/api/channels/:type/access', async (c) => {
+ const type = c.req.param('type');
+ if (!isType(type)) return c.json({ error: 'Unknown channel' }, 400);
+ const body = (await c.req.json().catch(() => ({}))) as { action?: unknown; id?: unknown; role?: unknown };
+ const action = String(body.action ?? '');
+ const id = typeof body.id === 'string' ? body.id.trim() : typeof body.id === 'number' ? String(body.id) : '';
+ const config = live();
+ const r = applyAccess(type, config, action, id, body.role === 'admin' ? 'admin' : body.role === 'member' ? 'member' : undefined);
+ if (!r.ok) return c.json({ error: r.error }, r.status ?? 400);
+ persist(config);
+ if (r.welcome && runtime?.running(type)) {
+ void runtime.notify(type, r.welcome.target, r.welcome.text).catch((err) => logger.warn({ channel: type, err: err instanceof Error ? err.message : String(err) }, 'Could not tell the approved person'));
+ }
+ return c.json({ ok: true, channel: describe(type, config) });
+});
+
+type AccessResult = { ok: true; welcome?: { target: string; text: string } } | { ok: false; error: string; status?: 400 | 404 | 409 };
+
+/** One place for every channel's access rules: approve, reject, remove, promote, demote, reset. */
+export function applyAccess(type: ExternalChannel, config: MercuryConfig, action: string, id: string, role?: 'admin' | 'member'): AccessResult {
+ const ch = config.channels[type] as unknown as { admins: any[]; members: any[]; pending: any[] };
+ const keyOf = (u: any) => String(type === 'signal' ? u.phoneNumber : u.userId);
+ const find = (list: any[]) => list.find((u) => keyOf(u) === id);
+ if (action !== 'reset' && !id) return { ok: false, error: 'Who? (id is required)' };
+
+ switch (action) {
+ case 'approve': {
+ const req = find(ch.pending);
+ if (!req) return { ok: false, error: 'That request is no longer waiting (approved or turned down elsewhere).', status: 404 };
+ // The first person in becomes the admin, so the channel always has one.
+ const r = role ?? (ch.admins.length === 0 ? 'admin' : 'member');
+ const approved = type === 'telegram' ? approveTelegramPendingRequest(config, Number(id), r)
+ : type === 'discord' ? approveDiscordPendingRequest(config, id, r)
+ : type === 'slack' ? approveSlackPendingRequest(config, id, r)
+ : approveSignalPendingRequest(config, id, r);
+ if (!approved) return { ok: false, error: 'Could not approve that request.', status: 409 };
+ const target = type === 'telegram' ? String(req.chatId ?? req.userId) : id;
+ return { ok: true, welcome: { target, text: r === 'admin' ? '✅ You\'re in, as an admin. Talk to Mercury here any time.' : '✅ You\'re in. Talk to Mercury here any time.' } };
+ }
+ case 'reject': {
+ const done = type === 'telegram' ? rejectTelegramPendingRequest(config, Number(id))
+ : type === 'discord' ? rejectDiscordPendingRequest(config, id)
+ : type === 'slack' ? rejectSlackPendingRequest(config, id)
+ : rejectSignalPendingRequest(config, id);
+ return done ? { ok: true } : { ok: false, error: 'That request is no longer waiting.', status: 404 };
+ }
+ case 'remove': {
+ const admin = find(ch.admins);
+ if (admin && ch.admins.length <= 1) return { ok: false, error: 'That\'s the only admin. Make someone else admin first, or reset access.', status: 409 };
+ if (!admin && !find(ch.members)) return { ok: false, error: 'No such person.', status: 404 };
+ ch.admins = ch.admins.filter((u) => keyOf(u) !== id);
+ ch.members = ch.members.filter((u) => keyOf(u) !== id);
+ return { ok: true };
+ }
+ case 'promote': {
+ const m = find(ch.members);
+ if (!m) return { ok: false, error: 'Only members can be made admin.', status: 404 };
+ ch.members = ch.members.filter((u) => keyOf(u) !== id);
+ ch.admins.push('role' in m ? { ...m, role: 'admin' } : m);
+ return { ok: true };
+ }
+ case 'demote': {
+ const a = find(ch.admins);
+ if (!a) return { ok: false, error: 'Only admins can be made members.', status: 404 };
+ if (ch.admins.length <= 1) return { ok: false, error: 'The channel needs at least one admin.', status: 409 };
+ ch.admins = ch.admins.filter((u) => keyOf(u) !== id);
+ ch.members.push('role' in a ? { ...a, role: 'member' } : a);
+ return { ok: true };
+ }
+ case 'reset': {
+ if (type === 'telegram') clearTelegramAccess(config);
+ else if (type === 'discord') clearDiscordAccess(config);
+ else if (type === 'slack') clearSlackAccess(config);
+ else clearSignalAccess(config);
+ return { ok: true };
+ }
+ default:
+ return { ok: false, error: 'action must be approve, reject, remove, promote, demote or reset' };
+ }
+}
+
+// ── Signal: link this computer as a device of the owner's Signal account ────
+
+interface LinkState { status: 'starting' | 'waiting' | 'linked' | 'failed'; uri?: string; qrImage?: string; phoneNumber?: string; error?: string; startedAt: number }
+let link: LinkState | null = null;
+
+channels.post('/api/channels/signal/link', async (c) => {
+ if (link && (link.status === 'starting' || link.status === 'waiting') && Date.now() - link.startedAt < 120_000) return c.json(link);
+ link = { status: 'starting', startedAt: Date.now() };
+ const current = link;
+ try {
+ const { ensureSignalCli } = await import('../../signal/binary.js');
+ const { startLinking, waitForLinkCompletion } = await import('../../signal/setup.js');
+ const { qrSvg } = await import('../../plugins/qr-svg.js');
+ // signal-cli runs one process per account; the running channel stops while linking.
+ const config = live();
+ if (runtime?.running('signal')) { config.channels.signal.enabled = false; await runtime.restart('signal'); config.channels.signal.enabled = true; }
+ const binary = await ensureSignalCli();
+ const before = new Set(signalAccounts());
+ const session = await startLinking(binary);
+ if (!session) throw new Error('signal-cli couldn\'t start linking. Is Java 17+ installed?');
+ current.status = 'waiting';
+ current.uri = session.uri;
+ current.qrImage = `data:image/svg+xml;base64,${Buffer.from(qrSvg(session.uri)).toString('base64')}`;
+ void waitForLinkCompletion(session, 120_000).then(async (ok) => {
+ if (!ok) { current.status = 'failed'; current.error = 'The code wasn\'t scanned in 2 minutes. Try again.'; return; }
+ const added = signalAccounts().find((n) => !before.has(n)) ?? signalAccounts()[0];
+ const cfg = live();
+ if (added) cfg.channels.signal.phoneNumber = added;
+ cfg.channels.signal.enabled = true;
+ persist(cfg);
+ current.status = 'linked';
+ current.phoneNumber = added;
+ if (runtime) await runtime.restart('signal').catch(() => {});
+ });
+ return c.json(current);
+ } catch (err) {
+ current.status = 'failed';
+ current.error = err instanceof Error ? err.message : String(err);
+ return c.json(current, 502);
+ }
+});
+
+channels.get('/api/channels/signal/link', (c) => c.json(link ?? { status: 'none' }));
+
+export { TOKEN_SHAPES };
+export default channels;
diff --git a/src/web/server.ts b/src/web/server.ts
index 7548063a..e6a59d7a 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -14,6 +14,7 @@ import statusRoutes, { updateStatus } from './api/status.js';
import providerRoutes from './api/providers.js';
import cloudRoutes from './api/cloud.js';
import transcribeRoutes from './api/transcribe.js';
+import channelRoutes from './api/channels.js';
import configRoutes from './api/config.js';
import systemRoutes, { setScheduler } from './api/system.js';
import brainRoutes, { setUserMemory } from './api/brain.js';
@@ -95,6 +96,7 @@ app.route('/', statusRoutes);
app.route('/', providerRoutes);
app.route('/', cloudRoutes);
app.route('/', transcribeRoutes);
+app.route('/', channelRoutes);
app.route('/', configRoutes);
app.route('/', systemRoutes);
app.route('/', brainRoutes);