Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: telegram MCP bridge mode and interactive storage backend chooser

Adam Eivy8b2c24d06e39
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1ab842d6ca..9d77324108 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,6 +7,9 @@
- Server-side nicotine service with daily log persistence, custom product management, and caching
- Date editing on alcohol and nicotine history entries (move items between dates)
- Nicotine sub-nav link in MeatSpace sidebar
+- Telegram MCP Bridge mode: uses Claude Code's Telegram plugin for outbound notifications via direct Bot API HTTP calls, with inbound messages handled by Claude Code's natural language processing instead of rigid bot commands
+- Settings toggle to switch between Manual Bot and Claude MCP Bridge integration methods
+- Interactive storage backend chooser during setup: Docker PostgreSQL, Native PostgreSQL, or file-based JSON (deprecated) when Docker is unavailable
## Changed
- Extracted shared `dayOfWeek` utility and `DAY_LABELS` constant to meatspace constants (deduplicated from AlcoholTab)
diff --git a/.env.example b/.env.example
index ad09fbbabe..4591b69e97 100644
--- a/.env.example
+++ b/.env.example
@@ -1,8 +1,8 @@
# PortOS Environment Variables
# Copy to .env and customize for your deployment.
-# Database mode: "native" uses system PostgreSQL (port 5432), "docker" uses containerized pg (port 5561)
-# PGMODE=native
+# Database mode: "docker" (containerized pg, port 5561), "native" (system pg, port 5432), "file" (deprecated JSON storage)
+# PGMODE=docker
# PostgreSQL password (must match docker-compose.yml POSTGRES_PASSWORD in Docker mode)
# Note: Changing this after initial setup requires manually updating the PostgreSQL user password (or recreating the DB volume).
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index fe06d9c04c..7e6ccf5a0c 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -6,7 +6,7 @@ import BrailleSpinner from '../components/BrailleSpinner';
import { formatBytes } from '../utils/formatters';
import {
getSettings, updateSettings, getTelegramStatus, updateTelegramConfig,
- deleteTelegramConfig, testTelegram, updateTelegramForwardTypes,
+ deleteTelegramConfig, testTelegram, updateTelegramForwardTypes, updateTelegramMethod,
getDatabaseStatus, switchDatabase, setupNativeDatabase, exportDatabase, fixDatabase,
syncDatabase, startDatabase, stopDatabase, destroyDatabase
} from '../services/api';
@@ -480,6 +480,8 @@ function DatabaseTab() {
function TelegramTab() {
const [loading, setLoading] = useState(true);
+ const [method, setMethod] = useState('manual');
+ const [switching, setSwitching] = useState(false);
const [tgToken, setTgToken] = useState('');
const [tgChatId, setTgChatId] = useState('');
const [tgShowToken, setTgShowToken] = useState(false);
@@ -496,6 +498,7 @@ function TelegramTab() {
]).then(([settings, status]) => {
if (status) {
setTgStatus(status);
+ setMethod(status.method || 'manual');
setTgChatId(settings?.telegram?.chatId || '');
setTgForwardTypes(status.forwardTypes || []);
}
@@ -503,6 +506,20 @@ function TelegramTab() {
.finally(() => setLoading(false));
}, []);
+ const handleMethodChange = (newMethod) => {
+ setSwitching(true);
+ updateTelegramMethod(newMethod)
+ .then(status => {
+ setMethod(newMethod);
+ setTgStatus(status);
+ toast.success(newMethod === 'mcp-bridge'
+ ? 'Switched to Claude MCP Bridge'
+ : 'Switched to Manual Bot');
+ })
+ .catch(() => toast.error('Failed to switch method'))
+ .finally(() => setSwitching(false));
+ };
+
const handleTelegramSave = () => {
if (!tgToken && !tgStatus?.hasToken) {
toast.error('Bot token is required');
@@ -555,93 +572,184 @@ function TelegramTab() {
}
return (
- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">
- <div className="flex items-center justify-between">
- <div className="text-sm">
- {tgStatus?.connected && (
- <span className="flex items-center gap-2 text-port-success">
- <span className="w-2 h-2 rounded-full bg-port-success" />
- @{tgStatus.botUsername}
- </span>
- )}
- {tgStatus && !tgStatus.connected && tgStatus.hasToken && (
- <span className="flex items-center gap-2 text-port-error">
- <span className="w-2 h-2 rounded-full bg-port-error" />
- Disconnected
- </span>
- )}
- </div>
- </div>
-
- <div className="space-y-1">
- <label className="block text-sm text-gray-400">Bot Token</label>
- <div className="flex gap-2">
- <input
- type={tgShowToken ? 'text' : 'password'}
- value={tgToken}
- onChange={e => setTgToken(e.target.value)}
- className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- placeholder={tgStatus?.hasToken ? '••••••••••• (configured)' : 'Paste bot token from @BotFather'}
- />
+ <div className="space-y-4">
+ {/* Method Selector */}
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">
+ <label className="block text-sm text-gray-400">Integration Method</label>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<button
- onClick={() => setTgShowToken(!tgShowToken)}
- className="px-3 py-2 bg-port-border hover:bg-port-border/70 text-white rounded-lg transition-colors"
+ onClick={() => method !== 'manual' && handleMethodChange('manual')}
+ disabled={switching}
+ className={`p-4 rounded-lg border text-left transition-colors ${
+ method === 'manual'
+ ? 'border-port-accent bg-port-accent/10'
+ : 'border-port-border bg-port-bg hover:border-port-accent/50'
+ }`}
>
- {tgShowToken ? <EyeOff size={16} /> : <Eye size={16} />}
+ <div className="text-sm font-medium text-white">Manual Bot</div>
+ <div className="text-xs text-gray-500 mt-1">
+ Self-hosted polling bot with /status, /goals, /checkin commands. Requires bot token and chat ID.
+ </div>
+ </button>
+ <button
+ onClick={() => method !== 'mcp-bridge' && handleMethodChange('mcp-bridge')}
+ disabled={switching}
+ className={`p-4 rounded-lg border text-left transition-colors ${
+ method === 'mcp-bridge'
+ ? 'border-port-accent bg-port-accent/10'
+ : 'border-port-border bg-port-bg hover:border-port-accent/50'
+ }`}
+ >
+ <div className="text-sm font-medium text-white">Claude MCP Bridge</div>
+ <div className="text-xs text-gray-500 mt-1">
+ Uses Claude Code&apos;s Telegram plugin. Natural language inbound, PortOS notifications outbound.
+ </div>
</button>
</div>
+ {switching && <BrailleSpinner text="Switching..." />}
</div>
- <div className="space-y-1">
- <label className="block text-sm text-gray-400">Chat ID</label>
- <input
- type="text"
- value={tgChatId}
- onChange={e => setTgChatId(e.target.value)}
- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- placeholder="Message your bot /start to get your chat ID"
- />
- </div>
+ {/* Method-specific config */}
+ {method === 'manual' ? (
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">
+ <div className="flex items-center justify-between">
+ <div className="text-sm">
+ {tgStatus?.connected && (
+ <span className="flex items-center gap-2 text-port-success">
+ <span className="w-2 h-2 rounded-full bg-port-success" />
+ @{tgStatus.botUsername}
+ </span>
+ )}
+ {tgStatus && !tgStatus.connected && tgStatus.hasToken && (
+ <span className="flex items-center gap-2 text-port-error">
+ <span className="w-2 h-2 rounded-full bg-port-error" />
+ Disconnected
+ </span>
+ )}
+ </div>
+ </div>
- <p className="text-xs text-gray-500">
- 1. Message <code>@BotFather</code> on Telegram, send <code>/newbot</code>, copy the token, paste above, click Save.
- 2. Message your bot <code>/start</code> — it will reply with your Chat ID.
- 3. Paste the Chat ID above and click Save & Test.
- </p>
+ <div className="space-y-1">
+ <label className="block text-sm text-gray-400">Bot Token</label>
+ <div className="flex gap-2">
+ <input
+ type={tgShowToken ? 'text' : 'password'}
+ value={tgToken}
+ onChange={e => setTgToken(e.target.value)}
+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ placeholder={tgStatus?.hasToken ? '••••••••••• (configured)' : 'Paste bot token from @BotFather'}
+ />
+ <button
+ onClick={() => setTgShowToken(!tgShowToken)}
+ className="px-3 py-2 bg-port-border hover:bg-port-border/70 text-white rounded-lg transition-colors"
+ >
+ {tgShowToken ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ </div>
- <div className="flex items-center gap-3">
- <button
- onClick={handleTelegramSave}
- disabled={tgSaving || (!tgToken && !tgStatus?.hasToken)}
- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
- >
- {tgSaving ? <BrailleSpinner /> : <Save size={16} />}
- {tgStatus?.connected && tgChatId ? 'Save & Test' : 'Save'}
- </button>
- {tgStatus?.connected && (
- <button
- onClick={handleTelegramTest}
- disabled={tgTesting}
- className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
- >
- {tgTesting ? <BrailleSpinner /> : <Send size={16} />}
- Send Test
- </button>
- )}
- {(tgStatus?.hasToken || tgStatus?.hasChatId) && (
- <button
- onClick={handleTelegramDisconnect}
- disabled={tgDisconnecting}
- className="flex items-center gap-2 px-4 py-2 bg-port-error/20 hover:bg-port-error/30 text-port-error text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
- >
- {tgDisconnecting ? <BrailleSpinner /> : <Trash2 size={16} />}
- Disconnect
- </button>
- )}
- </div>
+ <div className="space-y-1">
+ <label className="block text-sm text-gray-400">Chat ID</label>
+ <input
+ type="text"
+ value={tgChatId}
+ onChange={e => setTgChatId(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ placeholder="Message your bot /start to get your chat ID"
+ />
+ </div>
+
+ <p className="text-xs text-gray-500">
+ 1. Message <code>@BotFather</code> on Telegram, send <code>/newbot</code>, copy the token, paste above, click Save.
+ 2. Message your bot <code>/start</code> — it will reply with your Chat ID.
+ 3. Paste the Chat ID above and click Save & Test.
+ </p>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={handleTelegramSave}
+ disabled={tgSaving || (!tgToken && !tgStatus?.hasToken)}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
+ >
+ {tgSaving ? <BrailleSpinner /> : <Save size={16} />}
+ {tgStatus?.connected && tgChatId ? 'Save & Test' : 'Save'}
+ </button>
+ {tgStatus?.connected && (
+ <button
+ onClick={handleTelegramTest}
+ disabled={tgTesting}
+ className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
+ >
+ {tgTesting ? <BrailleSpinner /> : <Send size={16} />}
+ Send Test
+ </button>
+ )}
+ {(tgStatus?.hasToken || tgStatus?.hasChatId) && (
+ <button
+ onClick={handleTelegramDisconnect}
+ disabled={tgDisconnecting}
+ className="flex items-center gap-2 px-4 py-2 bg-port-error/20 hover:bg-port-error/30 text-port-error text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
+ >
+ {tgDisconnecting ? <BrailleSpinner /> : <Trash2 size={16} />}
+ Disconnect
+ </button>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">
+ <div className="flex items-center justify-between">
+ <div className="text-sm">
+ {tgStatus?.connected ? (
+ <span className="flex items-center gap-2 text-port-success">
+ <span className="w-2 h-2 rounded-full bg-port-success" />
+ @{tgStatus.botUsername} → {tgStatus.chatId}
+ </span>
+ ) : (
+ <span className="flex items-center gap-2 text-port-warning">
+ <span className="w-2 h-2 rounded-full bg-port-warning" />
+ Not connected
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="text-xs text-gray-500 space-y-2">
+ <p>
+ The MCP Bridge reads config from Claude Code&apos;s Telegram plugin at <code>~/.claude/channels/telegram/</code>.
+ Bot token comes from <code>.env</code>, chat ID from the first entry in <code>access.json</code> allowlist.
+ </p>
+ <p>
+ <b>Outbound:</b> PortOS sends notifications via direct Telegram Bot API calls (no polling conflict).
+ </p>
+ <p>
+ <b>Inbound:</b> Messages are handled by Claude Code via the MCP plugin — natural language instead of rigid commands.
+ </p>
+ {!tgStatus?.connected && (
+ <p className="text-port-warning">
+ Set up the Claude Code Telegram plugin first: run <code>/telegram:configure</code> in Claude Code, then <code>/telegram:access pair &lt;code&gt;</code> to approve your chat.
+ </p>
+ )}
+ </div>
+
+ {tgStatus?.connected && (
+ <div className="flex items-center gap-3">
+ <button
+ onClick={handleTelegramTest}
+ disabled={tgTesting}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
+ >
+ {tgTesting ? <BrailleSpinner /> : <Send size={16} />}
+ Send Test
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ {/* Forward types (shared between both methods) */}
{tgStatus?.connected && (
- <div className="space-y-2 pt-2 border-t border-port-border">
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-2">
<label className="block text-sm text-gray-400">Forward Notification Types</label>
<p className="text-xs text-gray-500">When all are unchecked, all types are forwarded</p>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 95a98c90f9..6f621a83c2 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1657,6 +1657,11 @@ export const updateTelegramForwardTypes = (forwardTypes) => request('/telegram/f
method: 'PUT',
body: JSON.stringify({ forwardTypes })
});
+export const updateTelegramMethod = (method) => request('/telegram/method', {
+ method: 'PUT',
+ body: JSON.stringify({ method })
+});
+export const reloadTelegramBridge = () => request('/telegram/bridge/reload', { method: 'POST' });
// Insights
export const getGenomeHealthCorrelations = () => request('/insights/genome-health');
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index c42dc7dc4c..1bd012d880 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -30,7 +30,7 @@ const PORTS = {
AUTOFIXER: 5559, // Autofixer API
AUTOFIXER_UI: 5560, // Autofixer UI
POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)
- POSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port
+ POSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port (unused in file mode)
};
module.exports = {
@@ -50,6 +50,7 @@ module.exports = {
HOST: '0.0.0.0',
PGPORT: PORTS.POSTGRES,
PGPASSWORD: process.env.PGPASSWORD || 'portos',
+ ...(pgMode === 'file' ? { MEMORY_BACKEND: 'file' } : {}),
PATH: process.env.PATH // Inherit PATH for git/node access in child processes
},
watch: ['server'],
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index 89d8d40233..80ded5d400 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -13,7 +13,7 @@ import { execFileSync } from 'child_process';
import { createInterface } from 'readline';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
-import { readFileSync } from 'fs';
+import { readFileSync, writeFileSync } from 'fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
@@ -119,43 +119,90 @@ function getDockerHints(issue) {
return issue === 'not_installed' ? hints.install : hints.start;
}
-// Prompt user to continue without Docker (TTY only)
-function promptContinue(message, hint) {
+// Write PGMODE to .env (create or update)
+function setPgMode(mode) {
+ const envPath = join(rootDir, '.env');
+ let content = '';
+ try {
+ content = readFileSync(envPath, 'utf8');
+ } catch { /* no .env yet */ }
+
+ if (content.match(/^PGMODE=/m)) {
+ content = content.replace(/^PGMODE=.*/m, `PGMODE=${mode}`);
+ } else {
+ content = `PGMODE=${mode}\n${content}`;
+ }
+ writeFileSync(envPath, content);
+}
+
+// Prompt user to choose storage mode (TTY only)
+function promptStorageChoice(message, hint) {
return new Promise((resolve) => {
- // Non-TTY (CI, piped scripts) — continue without prompting
+ // Non-TTY (CI, piped scripts) — default to file-based
if (!process.stdin.isTTY) {
- resolve(true);
+ resolve('file');
return;
}
console.log(`⚠️ ${message}`);
console.log(` ${hint}`);
console.log('');
+ console.log(' Choose a storage backend:');
+ console.log('');
+ console.log(' 1) Docker PostgreSQL (recommended — containerized, no system install)');
+ console.log(' 2) Native PostgreSQL (use system-installed PostgreSQL on port 5432)');
+ console.log(' 3) File-based JSON storage (deprecated — no vector search)');
+ console.log('');
const rl = createInterface({ input: process.stdin, output: process.stdout });
- rl.question(' Continue without Docker (file-based storage)? [Y/n] ', (answer) => {
+ rl.question(' Enter choice [1/2/3]: ', (answer) => {
rl.close();
- const trimmed = answer.trim().toLowerCase();
- // Default is Y (continue)
- resolve(trimmed === '' || trimmed === 'y' || trimmed === 'yes');
+ const trimmed = answer.trim();
+ if (trimmed === '2') resolve('native');
+ else if (trimmed === '3') resolve('file');
+ else resolve('exit'); // 1 or default = they want docker, so exit to install it
});
});
}
async function handleDockerUnavailable(message, issue) {
const hint = getDockerHints(issue);
- const shouldContinue = await promptContinue(message, hint);
+ const choice = await promptStorageChoice(message, hint);
+
+ if (choice === 'native') {
+ console.log(' Switching to native PostgreSQL mode...');
+ setPgMode('native');
+ if (isNativeReady()) {
+ console.log('✅ System PostgreSQL ready on port 5432');
+ } else if (process.platform === 'darwin') {
+ console.log('⚠️ Native PostgreSQL not detected — try: brew install postgresql@17 && brew services start postgresql@17');
+ console.log(' Then re-run setup');
+ } else {
+ console.log('⚠️ Native PostgreSQL not detected — install and start PostgreSQL, then re-run setup');
+ }
+ process.exit(0);
+ }
- if (shouldContinue) {
- console.log(' Memory system will use file-based JSON storage');
+ if (choice === 'file') {
+ setPgMode('file');
+ console.log(' Memory system will use file-based JSON storage (deprecated)');
process.exit(0);
- } else {
- console.log(' Exiting — install/start Docker and try again');
- process.exit(1);
}
+
+ // choice === 'exit' — user wants Docker, tell them to install/start it
+ console.log(` ${hint}`);
+ console.log(' Install/start Docker and re-run setup');
+ process.exit(1);
}
const mode = getMode();
+
+if (mode === 'file') {
+ console.log('🗄️ Storage mode: file-based JSON (deprecated)');
+ console.log(' Tip: switch to PostgreSQL with: scripts/db.sh set-mode docker');
+ process.exit(0);
+}
+
console.log(`🗄️ Setting up PostgreSQL (mode: ${mode})...`);
if (mode === 'native') {
diff --git a/server/index.js b/server/index.js
index 08d32c0148..740237a352 100644
--- a/server/index.js
+++ b/server/index.js
@@ -75,6 +75,8 @@ import * as automationScheduler from './services/automationScheduler.js';
import * as agentActionExecutor from './services/agentActionExecutor.js';
import { startBackupScheduler } from './services/backupScheduler.js';
import * as telegram from './services/telegram.js';
+import * as telegramBridge from './services/telegramBridge.js';
+import { getSettings as getInitSettings } from './services/settings.js';
import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, getCurrentVersion } from './services/updateChecker.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
@@ -265,8 +267,14 @@ startBrainScheduler();
initBrainMemoryBridge();
// Initialize backup scheduler for daily data backups
startBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));
-// Initialize Telegram bot (if configured)
-telegram.init().catch(err => console.error(`❌ Telegram init failed: ${err.message}`));
+// Initialize Telegram (manual bot or MCP bridge based on settings)
+getInitSettings().then(s => {
+ if (s.telegram?.method === 'mcp-bridge') {
+ telegramBridge.init().catch(err => console.error(`❌ TG Bridge init failed: ${err.message}`));
+ } else {
+ telegram.init().catch(err => console.error(`❌ Telegram init failed: ${err.message}`));
+ }
+}).catch(err => console.error(`❌ Telegram settings read failed: ${err.message}`));
// Check for update completion marker from a previous update cycle
const updateMarkerPath = join(PATHS.data, 'update-complete.json');
const removeMarker = () => unlink(updateMarkerPath).catch(e => {
diff --git a/server/lib/telegramValidation.js b/server/lib/telegramValidation.js
index 25e5d5d5b0..fc72f90e70 100644
--- a/server/lib/telegramValidation.js
+++ b/server/lib/telegramValidation.js
@@ -8,3 +8,7 @@ export const telegramConfigSchema = z.object({
export const telegramTestSchema = z.object({
message: z.string().optional()
});
+
+export const telegramMethodSchema = z.object({
+ method: z.enum(['manual', 'mcp-bridge'])
+});
diff --git a/server/routes/telegram.js b/server/routes/telegram.js
index a3a0d921f3..23df89e6a4 100644
--- a/server/routes/telegram.js
+++ b/server/routes/telegram.js
@@ -1,24 +1,102 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { telegramConfigSchema, telegramTestSchema } from '../lib/telegramValidation.js';
+import { telegramConfigSchema, telegramTestSchema, telegramMethodSchema } from '../lib/telegramValidation.js';
import { getSettings, updateSettings } from '../services/settings.js';
import * as telegram from '../services/telegram.js';
+import * as telegramBridge from '../services/telegramBridge.js';
const router = Router();
+/**
+ * Get the active telegram service based on configured method
+ */
+async function getActiveService() {
+ const settings = await getSettings();
+ return settings.telegram?.method === 'mcp-bridge' ? telegramBridge : telegram;
+}
+
// GET /api/telegram/status
router.get('/status', asyncHandler(async (req, res) => {
const settings = await getSettings();
- const status = telegram.getStatus();
- res.json({
- ...status,
- hasToken: !!settings.secrets?.telegram?.token,
- hasChatId: !!settings.telegram?.chatId,
- forwardTypes: settings.telegram?.forwardTypes || []
+ const method = settings.telegram?.method || 'manual';
+
+ if (method === 'mcp-bridge') {
+ const status = telegramBridge.getStatus();
+ res.json({
+ method,
+ ...status,
+ hasToken: status.hasBotToken,
+ hasChatId: status.hasChatId,
+ forwardTypes: settings.telegram?.forwardTypes || []
+ });
+ } else {
+ const status = telegram.getStatus();
+ res.json({
+ method,
+ ...status,
+ hasToken: !!settings.secrets?.telegram?.token,
+ hasChatId: !!settings.telegram?.chatId,
+ forwardTypes: settings.telegram?.forwardTypes || []
+ });
+ }
+}));
+
+// PUT /api/telegram/method
+router.put('/method', asyncHandler(async (req, res) => {
+ const result = telegramMethodSchema.safeParse(req.body);
+ if (!result.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: result.error.errors }
+ });
+ }
+
+ const { method } = result.data;
+ const settings = await getSettings();
+
+ // Save method preference
+ await updateSettings({
+ telegram: {
+ ...settings.telegram,
+ method
+ }
});
+
+ // Switch services
+ if (method === 'mcp-bridge') {
+ // Stop manual bot, start bridge
+ await telegram.cleanup();
+ const bridgeOk = await telegramBridge.init();
+ if (settings.telegram?.forwardTypes) {
+ telegramBridge.updateCachedForwardTypes(settings.telegram.forwardTypes);
+ }
+ const status = telegramBridge.getStatus();
+ res.json({
+ method,
+ ...status,
+ hasToken: status.hasBotToken,
+ hasChatId: status.hasChatId,
+ initialized: bridgeOk
+ });
+ } else {
+ // Stop bridge, start manual bot
+ await telegramBridge.cleanup();
+ await telegram.init(false);
+ if (settings.telegram?.forwardTypes) {
+ telegram.updateCachedForwardTypes(settings.telegram.forwardTypes);
+ }
+ const status = telegram.getStatus();
+ res.json({
+ method,
+ ...status,
+ hasToken: !!settings.secrets?.telegram?.token,
+ hasChatId: !!settings.telegram?.chatId
+ });
+ }
}));
-// PUT /api/telegram/config
+// PUT /api/telegram/config (manual bot only)
router.put('/config', asyncHandler(async (req, res) => {
const result = telegramConfigSchema.safeParse(req.body);
if (!result.success) {
@@ -68,9 +146,15 @@ router.put('/config', asyncHandler(async (req, res) => {
// DELETE /api/telegram/config
router.delete('/config', asyncHandler(async (req, res) => {
- await telegram.cleanup();
-
const settings = await getSettings();
+ const method = settings.telegram?.method || 'manual';
+
+ if (method === 'mcp-bridge') {
+ await telegramBridge.cleanup();
+ } else {
+ await telegram.cleanup();
+ }
+
await updateSettings({
telegram: null,
secrets: { ...settings.secrets, telegram: undefined }
@@ -91,7 +175,8 @@ router.post('/test', asyncHandler(async (req, res) => {
}
const message = result.data.message || '🧪 Test message from PortOS';
- const sendResult = await telegram.sendMessage(message);
+ const service = await getActiveService();
+ const sendResult = await service.sendMessage(message);
if (!sendResult.success) {
throw new ServerError(sendResult.error || 'Failed to send test message', {
@@ -121,10 +206,18 @@ router.put('/forward-types', asyncHandler(async (req, res) => {
}
});
- // Update in-memory cache
+ // Update cache on both services (only the active one matters)
telegram.updateCachedForwardTypes(forwardTypes);
+ telegramBridge.updateCachedForwardTypes(forwardTypes);
res.json({ success: true, forwardTypes });
}));
+// POST /api/telegram/bridge/reload — reload bridge config from MCP plugin files
+router.post('/bridge/reload', asyncHandler(async (req, res) => {
+ await telegramBridge.reload();
+ const status = telegramBridge.getStatus();
+ res.json(status);
+}));
+
export default router;
diff --git a/server/services/telegramBridge.js b/server/services/telegramBridge.js
new file mode 100644
index 0000000000..d014c17184
--- /dev/null
+++ b/server/services/telegramBridge.js
@@ -0,0 +1,246 @@
+/**
+ * Telegram MCP Bridge Service
+ *
+ * Sends outbound messages via direct Telegram Bot API HTTP calls.
+ * Used when telegram method is 'mcp-bridge' — the MCP plugin handles
+ * inbound messages via Claude Code, this service handles outbound only.
+ *
+ * Reads bot token from ~/.claude/channels/telegram/.env
+ * Reads chat ID from ~/.claude/channels/telegram/access.json (first allowFrom entry)
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { homedir } from 'os';
+import { notificationEvents, NOTIFICATION_TYPES } from './notifications.js';
+
+const CHANNELS_DIR = join(homedir(), '.claude', 'channels', 'telegram');
+const ENV_FILE = join(CHANNELS_DIR, '.env');
+const ACCESS_FILE = join(CHANNELS_DIR, 'access.json');
+const API_BASE = 'https://api.telegram.org/bot';
+
+// Module-level state
+let botToken = null;
+let chatId = null;
+let botUsername = null;
+let isActive = false;
+let notificationSubscription = null;
+
+// Rate limiter: token bucket (30 messages/minute)
+let tokenBucket = 30;
+let lastTokenRefill = Date.now();
+const BUCKET_MAX = 30;
+const REFILL_INTERVAL = 60000;
+
+// Emoji maps (shared with manual bot)
+const NOTIFICATION_EMOJI = {
+ [NOTIFICATION_TYPES.MEMORY_APPROVAL]: '🧠',
+ [NOTIFICATION_TYPES.TASK_APPROVAL]: '✅',
+ [NOTIFICATION_TYPES.CODE_REVIEW]: '🔍',
+ [NOTIFICATION_TYPES.HEALTH_ISSUE]: '⚠️',
+ [NOTIFICATION_TYPES.BRIEFING_READY]: '📋',
+ [NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT]: '📝',
+ [NOTIFICATION_TYPES.PLAN_QUESTION]: '❓'
+};
+
+const PRIORITY_EMOJI = {
+ low: '🟢',
+ medium: '🟡',
+ high: '🟠',
+ critical: '🔴'
+};
+
+function refillTokens() {
+ const now = Date.now();
+ if (now - lastTokenRefill >= REFILL_INTERVAL) {
+ tokenBucket = BUCKET_MAX;
+ lastTokenRefill = now;
+ }
+}
+
+function consumeToken() {
+ refillTokens();
+ if (tokenBucket <= 0) return false;
+ tokenBucket--;
+ return true;
+}
+
+function escapeHtml(text) {
+ if (!text) return '';
+ return text
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
+}
+
+/**
+ * Read bot token from MCP plugin's .env file
+ */
+async function loadBotToken() {
+ const content = await readFile(ENV_FILE, 'utf-8').catch(() => null);
+ if (!content) return null;
+ const match = content.match(/^TELEGRAM_BOT_TOKEN=(.+)$/m);
+ return match ? match[1].trim() : null;
+}
+
+/**
+ * Read first allowed chat ID from MCP plugin's access.json
+ */
+async function loadChatId() {
+ const content = await readFile(ACCESS_FILE, 'utf-8').catch(() => null);
+ if (!content) return null;
+ const access = JSON.parse(content);
+ return access.allowFrom?.[0] || null;
+}
+
+/**
+ * Make a Telegram Bot API call
+ */
+async function apiCall(method, params) {
+ if (!botToken) return null;
+ const url = `${API_BASE}${botToken}/${method}`;
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(params)
+ });
+ const data = await res.json();
+ if (!data.ok) {
+ console.error(`📱 TG Bridge: API error on ${method} — ${data.description}`);
+ return null;
+ }
+ return data.result;
+}
+
+/**
+ * Initialize the MCP bridge
+ */
+export async function init() {
+ await cleanup();
+
+ botToken = await loadBotToken();
+ if (!botToken) {
+ console.log('📱 TG Bridge: no bot token in ~/.claude/channels/telegram/.env — skipping');
+ return false;
+ }
+
+ chatId = await loadChatId();
+ if (!chatId) {
+ console.log('📱 TG Bridge: no allowFrom entries in access.json — skipping');
+ return false;
+ }
+
+ // Validate token
+ const me = await apiCall('getMe', {});
+ if (!me) {
+ console.error('📱 TG Bridge: invalid bot token');
+ botToken = null;
+ return false;
+ }
+
+ botUsername = me.username;
+ isActive = true;
+ console.log(`📱 TG Bridge: active as @${botUsername} → chat ${chatId}`);
+
+ // Subscribe to notification events
+ initNotificationForwarding();
+ return true;
+}
+
+/**
+ * Cleanup bridge state
+ */
+export async function cleanup() {
+ if (notificationSubscription) {
+ notificationEvents.removeListener('added', notificationSubscription);
+ notificationSubscription = null;
+ }
+ isActive = false;
+ botToken = null;
+ chatId = null;
+ botUsername = null;
+}
+
+/**
+ * Send a message via direct Bot API HTTP call
+ */
+export async function sendMessage(text) {
+ if (!botToken || !chatId) {
+ return { success: false, error: !botToken ? 'No bot token' : 'No chat ID' };
+ }
+
+ if (!consumeToken()) {
+ console.log('📱 TG Bridge: rate limit reached, skipping message');
+ return { success: false, error: 'Rate limit exceeded' };
+ }
+
+ const result = await apiCall('sendMessage', {
+ chat_id: chatId,
+ text,
+ parse_mode: 'HTML'
+ });
+
+ return result
+ ? { success: true }
+ : { success: false, error: 'Send failed' };
+}
+
+/**
+ * Get bridge status
+ */
+export function getStatus() {
+ return {
+ connected: isActive,
+ botUsername,
+ chatId,
+ hasBotToken: !!botToken,
+ hasChatId: !!chatId
+ };
+}
+
+/**
+ * Reload config from MCP plugin files (called when user changes MCP config externally)
+ */
+export async function reload() {
+ if (!isActive) return;
+ const newChatId = await loadChatId();
+ if (newChatId && newChatId !== chatId) {
+ chatId = newChatId;
+ console.log(`📱 TG Bridge: chat ID updated to ${chatId}`);
+ }
+}
+
+// Cached forward types (set by the route handler)
+let cachedForwardTypes = null;
+
+export function updateCachedForwardTypes(forwardTypes) {
+ cachedForwardTypes = forwardTypes;
+}
+
+/**
+ * Forward a notification to Telegram via HTTP API
+ */
+async function forwardNotification(notification) {
+ if (Array.isArray(cachedForwardTypes) && cachedForwardTypes.length > 0) {
+ if (!cachedForwardTypes.includes(notification.type)) return;
+ }
+
+ const emoji = NOTIFICATION_EMOJI[notification.type] || '🔔';
+ const priorityEmoji = PRIORITY_EMOJI[notification.priority] || '';
+ const lines = [`${emoji} <b>${escapeHtml(notification.title)}</b>`];
+ if (notification.description) lines.push(escapeHtml(notification.description));
+ if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
+
+ await sendMessage(lines.join('\n'));
+}
+
+/**
+ * Subscribe to notification events
+ */
+function initNotificationForwarding() {
+ if (notificationSubscription) {
+ notificationEvents.removeListener('added', notificationSubscription);
+ }
+ notificationSubscription = forwardNotification;
+ notificationEvents.on('added', notificationSubscription);
+}