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 bot integration for notifications and commands (M56)

Adam Eivy8c19b0e72c0d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3704727500..df0f2a6c36 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,6 @@
## Added
+- **M56: Telegram Bot Integration** — Telegram bot for external notifications and conversational commands. Configure bot token and chat ID in Settings. Forwards PortOS notifications (filterable by type) to Telegram with rate limiting. Bot commands: `/status`, `/goals`, `/agents`, `/checkin`, `/help`. Check-in responses are persisted for goal tracking.
- **M49 P1: Goal Todos & Progress Tracking** — Enhanced goal model with explicit progress percentage, todo sub-tasks (with priority and time estimates), velocity tracking (percent/month with trend), projected completion dates, and time tracking aggregates. Progress bar and todos visible in both goal list rows and detail panel.
## Changed
diff --git a/PLAN.md b/PLAN.md
index 3e7aa5c131..74faa3a3d0 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -67,7 +67,7 @@ See [GOALS.md](./GOALS.md) for project goals and direction.
- [ ] **M50 P1-P4**: Email Management - Gmail + Outlook integration, AI categorization and priority extraction, Digital Twin voice drafting, review-before-send outbox, Brain knowledge capture
- [ ] **M34 P5-P7**: Digital Twin - Multi-modal capture, advanced testing, personas
- [ ] **M42 P5**: Unified Digital Twin Identity System - Cross-Insights Engine. See [Identity System](./docs/features/identity-system.md)
-- [ ] **M47**: Push Notifications - Webhook-based alerts when agents complete tasks, critical errors occur, or goals stall. Discord/Telegram integration for mobile awareness without needing the dashboard open.
+- [x] **M56**: Telegram Bot Integration - External notification channel via Telegram bot. ChatId allowlisting, notification forwarding with rate limiting and type filtering, conversational commands (/status, /goals, /agents, /checkin, /help), goal check-in persistence. Replaces M47.
- [x] **M48 P1-P5**: Google Calendar Integration - MCP push sync, subcalendar management, goal-calendar linking, daily review with auto-progress-logging, dormancy support
- [x] **M48 P6**: Calendar Consolidation - Moved Life Calendar from MeatSpace to Calendar > Lifetime tab with accuracy improvement tips
- [x] **M48 P7**: UI-Triggered Google Calendar Sync - "Sync Google" button in Sync tab + "Discover Calendars" in Config tab
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index 31a7c62bdf..c6ee1538d6 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -1,8 +1,18 @@
import { useState, useEffect } from 'react';
-import { Save, Plus, X } from 'lucide-react';
+import { Save, Plus, X, Eye, EyeOff, Trash2, Send } from 'lucide-react';
import toast from 'react-hot-toast';
import BrailleSpinner from '../components/BrailleSpinner';
-import { getSettings, updateSettings } from '../services/api';
+import { getSettings, updateSettings, getTelegramStatus, updateTelegramConfig, deleteTelegramConfig, testTelegram, updateTelegramForwardTypes } from '../services/api';
+
+const NOTIFICATION_TYPES = [
+ { key: 'memory_approval', label: 'Memory Approvals' },
+ { key: 'task_approval', label: 'Task Approvals' },
+ { key: 'code_review', label: 'Code Reviews' },
+ { key: 'health_issue', label: 'Health Issues' },
+ { key: 'briefing_ready', label: 'Briefings' },
+ { key: 'autobiography_prompt', label: 'Autobiography Prompts' },
+ { key: 'plan_question', label: 'Plan Questions' }
+];
export default function Settings() {
const [loading, setLoading] = useState(true);
@@ -13,13 +23,32 @@ export default function Settings() {
const [excludePaths, setExcludePaths] = useState([]);
const [newExclude, setNewExclude] = useState('');
+ // Telegram state
+ const [tgToken, setTgToken] = useState('');
+ const [tgChatId, setTgChatId] = useState('');
+ const [tgShowToken, setTgShowToken] = useState(false);
+ const [tgStatus, setTgStatus] = useState(null);
+ const [tgSaving, setTgSaving] = useState(false);
+ const [tgTesting, setTgTesting] = useState(false);
+ const [tgDisconnecting, setTgDisconnecting] = useState(false);
+ const [tgForwardTypes, setTgForwardTypes] = useState([]);
+
useEffect(() => {
- getSettings().then(settings => {
+ Promise.all([
+ getSettings(),
+ getTelegramStatus().catch(() => null)
+ ]).then(([settings, status]) => {
const backup = settings?.backup || {};
setDestPath(backup.destPath || '');
setEnabled(backup.enabled ?? false);
setCronExpression(backup.cronExpression || '0 2 * * *');
setExcludePaths(backup.excludePaths || []);
+
+ if (status) {
+ setTgStatus(status);
+ setTgChatId(settings?.telegram?.chatId || '');
+ setTgForwardTypes(status.forwardTypes || []);
+ }
}).catch(() => toast.error('Failed to load settings')).finally(() => setLoading(false));
}, []);
@@ -42,6 +71,53 @@ export default function Settings() {
setExcludePaths(excludePaths.filter((_, i) => i !== index));
};
+ const handleTelegramSave = () => {
+ if (!tgToken && !tgStatus?.hasToken) {
+ toast.error('Bot token is required');
+ return;
+ }
+ setTgSaving(true);
+ updateTelegramConfig({ token: tgToken, chatId: tgChatId })
+ .then(status => {
+ setTgStatus(status);
+ toast.success(tgChatId
+ ? 'Telegram connected — check your chat for a test message'
+ : 'Bot connected — now message your bot /start to get your Chat ID');
+ })
+ .catch(() => toast.error('Failed to configure Telegram'))
+ .finally(() => setTgSaving(false));
+ };
+
+ const handleTelegramTest = () => {
+ setTgTesting(true);
+ testTelegram()
+ .then(() => toast.success('Test message sent'))
+ .catch(() => toast.error('Failed to send test message'))
+ .finally(() => setTgTesting(false));
+ };
+
+ const handleTelegramDisconnect = () => {
+ setTgDisconnecting(true);
+ deleteTelegramConfig()
+ .then(() => {
+ setTgStatus(null);
+ setTgToken('');
+ setTgChatId('');
+ setTgForwardTypes([]);
+ toast.success('Telegram disconnected');
+ })
+ .catch(() => toast.error('Failed to disconnect'))
+ .finally(() => setTgDisconnecting(false));
+ };
+
+ const toggleForwardType = (type) => {
+ const updated = tgForwardTypes.includes(type)
+ ? tgForwardTypes.filter(t => t !== type)
+ : [...tgForwardTypes, type];
+ setTgForwardTypes(updated);
+ updateTelegramForwardTypes(updated).catch(() => toast.error('Failed to update forward types'));
+ };
+
if (loading) {
return (
<div className="flex items-center justify-center h-64">
@@ -133,6 +209,113 @@ export default function Settings() {
Save
</button>
</div>
+
+ {/* Telegram */}
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">
+ <div className="flex items-center justify-between">
+ <h2 className="text-lg font-semibold text-white">Telegram</h2>
+ {tgStatus?.connected && (
+ <span className="flex items-center gap-2 text-sm 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-sm text-port-error">
+ <span className="w-2 h-2 rounded-full bg-port-error" />
+ Disconnected
+ </span>
+ )}
+ </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'}
+ />
+ <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="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>
+
+ {/* Notification type toggles */}
+ {tgStatus?.connected && (
+ <div className="space-y-2 pt-2 border-t border-port-border">
+ <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">
+ {NOTIFICATION_TYPES.map(({ key, label }) => (
+ <label key={key} className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={tgForwardTypes.includes(key)}
+ onChange={() => toggleForwardType(key)}
+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ {label}
+ </label>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
</div>
);
}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index a63ce1a04b..d8260900af 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1611,6 +1611,22 @@ export const updateSettings = (data) => request('/settings', {
body: JSON.stringify(data)
});
+// Telegram
+export const getTelegramStatus = () => request('/telegram/status');
+export const updateTelegramConfig = (data) => request('/telegram/config', {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteTelegramConfig = () => request('/telegram/config', { method: 'DELETE' });
+export const testTelegram = (message) => request('/telegram/test', {
+ method: 'POST',
+ body: JSON.stringify({ message })
+});
+export const updateTelegramForwardTypes = (forwardTypes) => request('/telegram/forward-types', {
+ method: 'PUT',
+ body: JSON.stringify({ forwardTypes })
+});
+
// Insights
export const getGenomeHealthCorrelations = () => request('/insights/genome-health');
export const getInsightThemes = () => request('/insights/themes');
diff --git a/server/index.js b/server/index.js
index b4af6272b9..b4dcbdb9a6 100644
--- a/server/index.js
+++ b/server/index.js
@@ -55,6 +55,7 @@ import instancesRoutes from './routes/instances.js';
import meatspaceRoutes from './routes/meatspace.js';
import githubRoutes from './routes/github.js';
import settingsRoutes from './routes/settings.js';
+import telegramRoutes from './routes/telegram.js';
import updateRoutes from './routes/update.js';
import { ensureSelf, startPolling } from './services/instances.js';
import { initSyncLog } from './services/brainSyncLog.js';
@@ -70,6 +71,7 @@ import './services/subAgentSpawner.js'; // Initialize CoS agent spawner
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 { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, getCurrentVersion } from './services/updateChecker.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
@@ -243,6 +245,7 @@ app.use('/api/instances', instancesRoutes);
app.use('/api/meatspace', meatspaceRoutes);
app.use('/api/github', githubRoutes);
app.use('/api/settings', settingsRoutes);
+app.use('/api/telegram', telegramRoutes);
app.use('/api/update', updateRoutes);
// Initialize agent automation scheduler and action executor
@@ -257,6 +260,8 @@ 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}`));
// Check for update completion marker from a previous update cycle
const updateMarkerPath = join(__dirname, '..', 'data', 'update-complete.json');
const removeMarker = () => unlink(updateMarkerPath).catch(e => {
diff --git a/server/lib/telegramValidation.js b/server/lib/telegramValidation.js
new file mode 100644
index 0000000000..25e5d5d5b0
--- /dev/null
+++ b/server/lib/telegramValidation.js
@@ -0,0 +1,10 @@
+import { z } from 'zod';
+
+export const telegramConfigSchema = z.object({
+ token: z.string().optional().default(''),
+ chatId: z.string().optional().default('')
+});
+
+export const telegramTestSchema = z.object({
+ message: z.string().optional()
+});
diff --git a/server/package.json b/server/package.json
index e748dd1f5d..7125097d1d 100644
--- a/server/package.json
+++ b/server/package.json
@@ -17,6 +17,7 @@
"googleapis": "^171.4.0",
"multer": "^2.0.2",
"node-pty": "^1.2.0-beta.10",
+ "node-telegram-bot-api": "^0.67.0",
"pg": "^8.19.0",
"pm2": "^5.4.3",
"portos-ai-toolkit": "^0.8.0",
diff --git a/server/routes/telegram.js b/server/routes/telegram.js
new file mode 100644
index 0000000000..a3a0d921f3
--- /dev/null
+++ b/server/routes/telegram.js
@@ -0,0 +1,130 @@
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { telegramConfigSchema, telegramTestSchema } from '../lib/telegramValidation.js';
+import { getSettings, updateSettings } from '../services/settings.js';
+import * as telegram from '../services/telegram.js';
+
+const router = Router();
+
+// 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 || []
+ });
+}));
+
+// PUT /api/telegram/config
+router.put('/config', asyncHandler(async (req, res) => {
+ const result = telegramConfigSchema.safeParse(req.body);
+ if (!result.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: result.error.errors }
+ });
+ }
+
+ const { token, chatId } = result.data;
+ const settings = await getSettings();
+
+ // Preserve existing token if a new one wasn't provided
+ const finalToken = token || settings.secrets?.telegram?.token;
+
+ if (!finalToken) {
+ throw new ServerError('Bot token is required', {
+ status: 400,
+ code: 'VALIDATION_ERROR'
+ });
+ }
+
+ // Store token in secrets, chatId in telegram
+ await updateSettings({
+ secrets: {
+ ...settings.secrets,
+ telegram: { token: finalToken }
+ },
+ telegram: {
+ ...settings.telegram,
+ chatId: chatId || settings.telegram?.chatId || ''
+ }
+ });
+
+ // Initialize bot — send test message only if chatId is configured
+ const hasChatId = !!(chatId || settings.telegram?.chatId);
+ await telegram.init(hasChatId);
+ const status = telegram.getStatus();
+
+ res.json({
+ ...status,
+ hasToken: true,
+ hasChatId
+ });
+}));
+
+// DELETE /api/telegram/config
+router.delete('/config', asyncHandler(async (req, res) => {
+ await telegram.cleanup();
+
+ const settings = await getSettings();
+ await updateSettings({
+ telegram: null,
+ secrets: { ...settings.secrets, telegram: undefined }
+ });
+
+ res.json({ success: true });
+}));
+
+// POST /api/telegram/test
+router.post('/test', asyncHandler(async (req, res) => {
+ const result = telegramTestSchema.safeParse(req.body);
+ if (!result.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: result.error.errors }
+ });
+ }
+
+ const message = result.data.message || '🧪 Test message from PortOS';
+ const sendResult = await telegram.sendMessage(message);
+
+ if (!sendResult.success) {
+ throw new ServerError(sendResult.error || 'Failed to send test message', {
+ status: 502,
+ code: 'TELEGRAM_SEND_FAILED'
+ });
+ }
+
+ res.json({ success: true });
+}));
+
+// PUT /api/telegram/forward-types
+router.put('/forward-types', asyncHandler(async (req, res) => {
+ const { forwardTypes } = req.body;
+ if (!Array.isArray(forwardTypes)) {
+ throw new ServerError('forwardTypes must be an array', {
+ status: 400,
+ code: 'VALIDATION_ERROR'
+ });
+ }
+
+ const settings = await getSettings();
+ await updateSettings({
+ telegram: {
+ ...settings.telegram,
+ forwardTypes
+ }
+ });
+
+ // Update in-memory cache
+ telegram.updateCachedForwardTypes(forwardTypes);
+
+ res.json({ success: true, forwardTypes });
+}));
+
+export default router;
diff --git a/server/services/telegram.js b/server/services/telegram.js
new file mode 100644
index 0000000000..3e82191f11
--- /dev/null
+++ b/server/services/telegram.js
@@ -0,0 +1,514 @@
+/**
+ * Telegram Bot Service
+ *
+ * Manages Telegram bot lifecycle, messaging, notification forwarding,
+ * and conversational commands for PortOS.
+ */
+
+import TelegramBot from 'node-telegram-bot-api';
+import { writeFile, rename } from 'fs/promises';
+import { join } from 'path';
+import { v4 as uuidv4 } from 'uuid';
+import { getSettings } from './settings.js';
+import { notificationEvents, NOTIFICATION_TYPES, getNotifications } from './notifications.js';
+import { ensureDir, PATHS, readJSONFile, formatDuration } from '../lib/fileUtils.js';
+import { getActiveAgents } from './subAgentSpawner.js';
+import { getGoals } from './identity.js';
+
+// Module-level state
+let bot = null;
+let isConnected = false;
+let reconnectionTimeout = null;
+let healthCheckInterval = null;
+let reconnectionAttempts = 0;
+let botUsername = null;
+let notificationSubscription = null;
+
+// Cached config (refreshed on init)
+let authorizedChatId = null;
+let cachedForwardTypes = null;
+
+// Rate limiter: token bucket (30 messages/minute)
+let tokenBucket = 30;
+let lastTokenRefill = Date.now();
+const BUCKET_MAX = 30;
+const REFILL_INTERVAL = 60000; // 1 minute
+
+// Pending check-ins with 10-minute TTL
+const pendingCheckins = new Map();
+const CHECKIN_TTL = 10 * 60 * 1000;
+
+const CHECKINS_DIR = join(PATHS.data, 'telegram');
+const CHECKINS_FILE = join(CHECKINS_DIR, 'checkins.json');
+const MAX_CHECKINS = 500;
+
+// Emoji map for notification types
+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]: '❓'
+};
+
+// Priority emoji
+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 cleanExpiredCheckins() {
+ const now = Date.now();
+ for (const [key, value] of pendingCheckins) {
+ if (now - new Date(value.askedAt).getTime() > CHECKIN_TTL) {
+ pendingCheckins.delete(key);
+ }
+ }
+}
+
+function escapeHtml(text) {
+ if (!text) return '';
+ return text
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
+}
+
+/**
+ * Initialize the Telegram bot
+ * @param {boolean} sendTestMessage - Send a test message after connecting
+ */
+export async function init(sendTestMessage = false) {
+ await cleanup();
+
+ const settings = await getSettings();
+ const token = settings.secrets?.telegram?.token;
+ const chatId = settings.telegram?.chatId;
+ authorizedChatId = chatId || null;
+ cachedForwardTypes = settings.telegram?.forwardTypes || null;
+
+ if (!token) {
+ console.log('📱 Telegram: no token configured — skipping');
+ return;
+ }
+
+ // Ensure data directory exists once at init
+ await ensureDir(CHECKINS_DIR);
+
+ bot = new TelegramBot(token, { polling: true });
+ reconnectionAttempts = 0;
+
+ // Validate token
+ const me = await bot.getMe().catch(err => {
+ console.error(`📱 Telegram: invalid token — ${err.message}`);
+ bot = null;
+ return null;
+ });
+
+ if (!me) return;
+
+ botUsername = me.username;
+ isConnected = true;
+ console.log(`📱 Telegram: connected as @${botUsername}`);
+
+ // Register /start handler (always works, no auth required)
+ bot.onText(/\/start/, (msg) => {
+ const fromChatId = String(msg.chat.id);
+ bot.sendMessage(fromChatId,
+ `Your Chat ID: <code>${fromChatId}</code>\n\n` +
+ 'Paste this into the PortOS Settings → Telegram → Chat ID field, then click Save & Test.',
+ { parse_mode: 'HTML' }
+ );
+ });
+
+ // Register command handlers
+ bot.onText(/\/status/, async (msg) => {
+ if (!isAuthorized(msg)) return;
+ await handleStatusCommand(msg);
+ });
+
+ bot.onText(/\/goals/, async (msg) => {
+ if (!isAuthorized(msg)) return;
+ await handleGoalsCommand(msg);
+ });
+
+ bot.onText(/\/agents/, async (msg) => {
+ if (!isAuthorized(msg)) return;
+ await handleAgentsCommand(msg);
+ });
+
+ bot.onText(/\/checkin/, async (msg) => {
+ if (!isAuthorized(msg)) return;
+ await handleCheckinCommand(msg);
+ });
+
+ bot.onText(/\/help/, async (msg) => {
+ if (!isAuthorized(msg)) return;
+ bot.sendMessage(String(msg.chat.id),
+ '<b>PortOS Bot Commands</b>\n\n' +
+ '/status — System overview\n' +
+ '/goals — Active goals with progress\n' +
+ '/agents — Running agents\n' +
+ '/checkin — Goal check-in question\n' +
+ '/help — Show this message',
+ { parse_mode: 'HTML' }
+ );
+ });
+
+ // Handle non-command messages (check-in responses)
+ bot.on('message', async (msg) => {
+ if (msg.text?.startsWith('/')) return;
+ if (!isAuthorized(msg)) return;
+ await handleCheckinResponse(msg);
+ });
+
+ // Start health check
+ healthCheckInterval = setInterval(healthCheck, 30000);
+
+ // Subscribe to notification events
+ initNotificationForwarding();
+
+ if (sendTestMessage && chatId) {
+ await sendMessage('📱 PortOS Telegram bot connected successfully!');
+ }
+}
+
+/**
+ * Check if a message is from the authorized chatId
+ */
+function isAuthorized(msg) {
+ const fromChatId = String(msg.chat.id);
+ if (fromChatId !== authorizedChatId) {
+ bot?.sendMessage(fromChatId,
+ 'This bot is not configured for your chat ID.\n' +
+ 'If you own this bot, message /start to see your chat ID, then configure it in PortOS Settings.'
+ );
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Cleanup bot instance
+ */
+export async function cleanup() {
+ if (healthCheckInterval) {
+ clearInterval(healthCheckInterval);
+ healthCheckInterval = null;
+ }
+ if (reconnectionTimeout) {
+ clearTimeout(reconnectionTimeout);
+ reconnectionTimeout = null;
+ }
+ if (notificationSubscription) {
+ notificationEvents.removeListener('added', notificationSubscription);
+ notificationSubscription = null;
+ }
+ if (bot) {
+ await bot.stopPolling().catch(() => {});
+ bot = null;
+ }
+ isConnected = false;
+ botUsername = null;
+ authorizedChatId = null;
+ cachedForwardTypes = null;
+}
+
+/**
+ * Reconnect with exponential backoff
+ */
+async function reconnect() {
+ if (reconnectionAttempts >= 10) {
+ console.error('📱 Telegram: max reconnection attempts reached');
+ return;
+ }
+ reconnectionAttempts++;
+ const delay = 5000 * reconnectionAttempts;
+ console.log(`📱 Telegram: reconnecting in ${delay / 1000}s (attempt ${reconnectionAttempts}/10)`);
+
+ reconnectionTimeout = setTimeout(async () => {
+ await init(false).catch(err => {
+ console.error(`📱 Telegram: reconnection failed — ${err.message}`);
+ });
+ }, delay);
+}
+
+/**
+ * Health check
+ */
+async function healthCheck() {
+ if (!bot) return;
+ await bot.getMe().catch(async (err) => {
+ console.error(`📱 Telegram: health check failed — ${err.message}`);
+ isConnected = false;
+ await reconnect();
+ });
+}
+
+/**
+ * Send a message to the configured chatId
+ */
+export async function sendMessage(text) {
+ if (!bot || !authorizedChatId) return { success: false, error: !bot ? 'Bot not initialized' : 'No chatId configured' };
+
+ if (!consumeToken()) {
+ console.log('📱 Telegram: rate limit reached, skipping message');
+ return { success: false, error: 'Rate limit exceeded' };
+ }
+
+ const result = await bot.sendMessage(authorizedChatId, text, { parse_mode: 'HTML' }).catch(async (err) => {
+ console.error(`📱 Telegram: send failed — ${err.message}`);
+ isConnected = false;
+ await reconnect();
+ return null;
+ });
+
+ return result ? { success: true } : { success: false, error: 'Send failed' };
+}
+
+/**
+ * Get bot status
+ */
+export function getStatus() {
+ return {
+ connected: isConnected,
+ hasChatId: false, // Checked by caller via settings
+ hasToken: false, // Checked by caller via settings
+ botUsername
+ };
+}
+
+/**
+ * Update cached forward types (called from route on config change)
+ */
+export function updateCachedForwardTypes(forwardTypes) {
+ cachedForwardTypes = forwardTypes;
+}
+
+/**
+ * Forward a notification to Telegram
+ */
+async function forwardNotification(notification) {
+ // Use cached forwardTypes to avoid disk I/O on every 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 for forwarding
+ */
+function initNotificationForwarding() {
+ if (notificationSubscription) {
+ notificationEvents.removeListener('added', notificationSubscription);
+ }
+ notificationSubscription = forwardNotification;
+ notificationEvents.on('added', notificationSubscription);
+}
+
+// === Conversational Commands ===
+
+async function handleStatusCommand(msg) {
+ const chatId = String(msg.chat.id);
+ const lines = ['<b>📊 PortOS Status</b>\n'];
+
+ const agents = getActiveAgents();
+ lines.push(`<b>Agents:</b> ${agents.length} running`);
+
+ const notifications = await getNotifications({ limit: 5, unreadOnly: true });
+ lines.push(`<b>Unread notifications:</b> ${notifications.length}`);
+
+ const settings = await getSettings();
+ lines.push(`<b>Backup:</b> ${settings.backup?.enabled ? 'enabled' : 'disabled'}`);
+
+ await bot.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' });
+}
+
+async function handleGoalsCommand(msg) {
+ const chatId = String(msg.chat.id);
+ const data = await getGoals();
+ const activeGoals = data.goals.filter(g => g.status === 'active');
+
+ if (activeGoals.length === 0) {
+ await bot.sendMessage(chatId, 'No active goals.', { parse_mode: 'HTML' });
+ return;
+ }
+
+ const lines = ['<b>🎯 Active Goals</b>\n'];
+ for (const goal of activeGoals) {
+ const progress = goal.progress || 0;
+ const filled = Math.round(progress / 10);
+ const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);
+ const velocity = goal.velocity?.percentPerMonth
+ ? ` (${goal.velocity.percentPerMonth.toFixed(1)}%/mo)`
+ : '';
+ lines.push(`${bar} ${progress}% — <b>${escapeHtml(goal.title)}</b>${velocity}`);
+ }
+
+ await bot.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' });
+}
+
+async function handleAgentsCommand(msg) {
+ const chatId = String(msg.chat.id);
+ const agents = getActiveAgents();
+
+ if (agents.length === 0) {
+ await bot.sendMessage(chatId, 'No agents currently running.', { parse_mode: 'HTML' });
+ return;
+ }
+
+ const lines = ['<b>🤖 Running Agents</b>\n'];
+ for (const agent of agents) {
+ const runtime = formatDuration(agent.runningTime);
+ lines.push(`• <b>${escapeHtml(agent.taskId || agent.id)}</b> — ${runtime} (${agent.mode})`);
+ }
+
+ await bot.sendMessage(chatId, lines.join('\n'), { parse_mode: 'HTML' });
+}
+
+async function handleCheckinCommand(msg) {
+ const chatId = String(msg.chat.id);
+ const data = await getGoals();
+ const activeGoals = data.goals.filter(g => g.status === 'active');
+
+ if (activeGoals.length === 0) {
+ await bot.sendMessage(chatId, 'No active goals to check in on.', { parse_mode: 'HTML' });
+ return;
+ }
+
+ // Pick goal with oldest check-in or no check-ins
+ const checkins = await loadCheckins();
+ let targetGoal = null;
+ let oldestCheckinTime = Infinity;
+
+ for (const goal of activeGoals) {
+ const lastCheckin = checkins.checkins
+ .filter(c => c.goalId === goal.id)
+ .sort((a, b) => new Date(b.askedAt) - new Date(a.askedAt))[0];
+
+ const checkinTime = lastCheckin ? new Date(lastCheckin.askedAt).getTime() : 0;
+ if (checkinTime < oldestCheckinTime) {
+ oldestCheckinTime = checkinTime;
+ targetGoal = goal;
+ }
+ }
+
+ if (!targetGoal) return;
+
+ const question = `How's progress on "<b>${escapeHtml(targetGoal.title)}</b>"? (currently ${targetGoal.progress || 0}%)`;
+ pendingCheckins.set(chatId, {
+ question,
+ goalId: targetGoal.id,
+ askedAt: new Date().toISOString()
+ });
+
+ await bot.sendMessage(chatId, question, { parse_mode: 'HTML' });
+}
+
+async function handleCheckinResponse(msg) {
+ const chatId = String(msg.chat.id);
+ cleanExpiredCheckins();
+ const pending = pendingCheckins.get(chatId);
+ if (!pending) return;
+
+ const checkins = await loadCheckins();
+ checkins.checkins.push({
+ id: uuidv4(),
+ question: pending.question,
+ response: msg.text,
+ goalId: pending.goalId,
+ askedAt: pending.askedAt,
+ answeredAt: new Date().toISOString()
+ });
+
+ // Cap at MAX_CHECKINS entries
+ if (checkins.checkins.length > MAX_CHECKINS) {
+ checkins.checkins = checkins.checkins.slice(-MAX_CHECKINS);
+ }
+
+ await saveCheckins(checkins);
+ pendingCheckins.delete(chatId);
+
+ await bot.sendMessage(chatId, '✅ Check-in recorded. Thanks!', { parse_mode: 'HTML' });
+}
+
+/**
+ * Send a check-in prompt for a specific goal (or auto-pick)
+ * Exported for use by scheduled jobs
+ */
+export async function sendCheckin(goalId) {
+ if (!bot || !authorizedChatId) return;
+
+ const data = await getGoals();
+ const activeGoals = data.goals.filter(g => g.status === 'active');
+
+ let targetGoal;
+ if (goalId) {
+ targetGoal = activeGoals.find(g => g.id === goalId);
+ } else {
+ // Pick most stale goal
+ const checkins = await loadCheckins();
+ let oldestTime = Infinity;
+ for (const goal of activeGoals) {
+ const last = checkins.checkins
+ .filter(c => c.goalId === goal.id)
+ .sort((a, b) => new Date(b.askedAt) - new Date(a.askedAt))[0];
+ const t = last ? new Date(last.askedAt).getTime() : 0;
+ if (t < oldestTime) { oldestTime = t; targetGoal = goal; }
+ }
+ }
+
+ if (!targetGoal) return;
+
+ const question = `How's progress on "<b>${escapeHtml(targetGoal.title)}</b>"? (currently ${targetGoal.progress || 0}%)`;
+ pendingCheckins.set(authorizedChatId, {
+ question,
+ goalId: targetGoal.id,
+ askedAt: new Date().toISOString()
+ });
+
+ await sendMessage(question);
+}
+
+// === Check-in persistence ===
+
+async function loadCheckins() {
+ return readJSONFile(CHECKINS_FILE, { checkins: [] });
+}
+
+async function saveCheckins(data) {
+ const tmp = `${CHECKINS_FILE}.tmp`;
+ await writeFile(tmp, JSON.stringify(data, null, 2));
+ await rename(tmp, CHECKINS_FILE);
+}
+
+// Process signal handlers to prevent orphan polling
+process.on('SIGTERM', cleanup);
+process.on('SIGINT', cleanup);