This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-12 16:07:13 +01:00
1 parent 152ce6643f
commit d22b01b555
15 files changed
+2035 -4

No files matched your search

+15
View File
@@ -9,6 +9,7 @@ from cptr.routers import (
admin_router,
auth_router,
automations_router,
bridge_router,
chat_router,
events_router,
files_router,
@@ -55,6 +56,19 @@ async def startup():
asyncio.create_task(scheduler_worker_loop(app))
# Start messaging bots
from cptr.utils.bridge import BotManager
app.state.bot_manager = BotManager()
asyncio.create_task(app.state.bot_manager.start_all())
@app.on_event("shutdown")
async def shutdown():
bot_manager = getattr(app.state, "bot_manager", None)
if bot_manager:
await bot_manager.stop_all()
# Auth middleware
@app.middleware("http")
@@ -187,6 +201,7 @@ async def get_config():
app.include_router(admin_router)
app.include_router(auth_router)
app.include_router(automations_router)
app.include_router(bridge_router)
app.include_router(chat_router)
app.include_router(events_router)
app.include_router(files_router)
+70
View File
@@ -0,0 +1,70 @@
import { fetchJSON, jsonBody } from './index';
export type BotData = {
id: string;
platform: string;
name: string;
workspace: string;
model_id: string;
token_masked: string;
allowed_senders: string[];
is_active: boolean;
is_running: boolean;
meta: Record<string, any> | null;
created_at: number;
updated_at: number;
};
export type BotForm = {
platform: string;
name: string;
workspace: string;
model_id: string;
token: string;
allowed_senders?: string[];
is_active?: boolean;
};
export type BotUpdate = {
name?: string;
workspace?: string;
model_id?: string;
token?: string;
allowed_senders?: string[];
is_active?: boolean;
};
export async function listBots(): Promise<BotData[]> {
return fetchJSON('/api/admin/bots');
}
export async function createBot(form: BotForm): Promise<BotData> {
return fetchJSON('/api/admin/bots', jsonBody(form));
}
export async function updateBot(id: string, form: BotUpdate): Promise<BotData> {
return fetchJSON(`/api/admin/bots/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form)
});
}
export async function deleteBot(id: string): Promise<{ ok: boolean }> {
return fetchJSON(`/api/admin/bots/${id}`, { method: 'DELETE' });
}
export async function startBot(id: string): Promise<{ ok: boolean; is_running: boolean }> {
return fetchJSON(`/api/admin/bots/${id}/start`, { method: 'POST' });
}
export async function stopBot(id: string): Promise<{ ok: boolean; is_running: boolean }> {
return fetchJSON(`/api/admin/bots/${id}/stop`, { method: 'POST' });
}
export async function verifyBotToken(
platform: string,
token: string
): Promise<{ ok: boolean; info?: { username: string; id: string }; error?: string }> {
return fetchJSON('/api/admin/bots/verify', jsonBody({ platform, token }));
}
@@ -0,0 +1,262 @@
<script lang="ts">
/**
* Create / Edit bot modal.
* Follows the same pattern as CreateConnectionModal and AutomationModal.
*/
import Modal from '../Modal.svelte';
import Icon from '../Icon.svelte';
import DropdownMenu from '../DropdownMenu.svelte';
import ModelSelector from '../common/ModelSelector.svelte';
import { selectedModelId, workspaceList } from '$lib/stores';
import { createBot, updateBot, verifyBotToken, type BotData, type BotForm } from '$lib/apis/bots';
import { toast } from 'svelte-sonner';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
interface Props {
bot?: BotData | null;
onclose: () => void;
onsave: () => void;
}
let { bot = null, onclose, onsave }: Props = $props();
let platform = $state(bot?.platform || 'telegram');
let name = $state(bot?.name || '');
let token = $state('');
let modelId = $state(bot?.model_id || $selectedModelId || '');
let workspace = $state(bot?.workspace || '');
let allowedSenders = $state(bot?.allowed_senders?.join(', ') || '');
let saving = $state(false);
// Token verification
let verifying = $state(false);
let verifyResult = $state<{ ok: boolean; info?: any; error?: string } | null>(null);
// Workspace dropdown
let showWsMenu = $state(false);
let wsBtnEl: HTMLButtonElement | undefined = $state();
$effect(() => {
if (!workspace && $workspaceList.length > 0) {
workspace = $workspaceList[0].path;
}
});
let wsMenuItems = $derived(
$workspaceList.map((ws) => ({
label: ws.name,
icon: 'folder',
active: ws.path === workspace,
check: true,
onclick: () => { workspace = ws.path; }
}))
);
let selectedWsName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name || workspace.split('/').pop() || 'Select workspace'
);
const platformHints: Record<string, string> = {
telegram: 'Create a bot via @BotFather',
discord: 'Create a bot in the Developer Portal'
};
async function handleVerify() {
if (!token.trim()) return;
verifying = true;
verifyResult = null;
try {
verifyResult = await verifyBotToken(platform, token.trim());
} catch (e: any) {
verifyResult = { ok: false, error: e.message || 'Verification failed' };
} finally {
verifying = false;
}
}
async function handleSubmit() {
if (!name.trim() || !modelId || !workspace) return;
if (!bot && !token.trim()) return;
saving = true;
try {
if (bot) {
const update: any = {
name: name.trim(),
model_id: modelId,
workspace,
allowed_senders: allowedSenders.split(',').map((s) => s.trim()).filter(Boolean) || undefined
};
if (token.trim()) update.token = token.trim();
await updateBot(bot.id, update);
} else {
await createBot({
platform,
name: name.trim(),
token: token.trim(),
model_id: modelId,
workspace,
allowed_senders: allowedSenders.split(',').map((s) => s.trim()).filter(Boolean) || undefined
});
}
onsave();
onclose();
} catch (e: any) {
toast.error(e.message || 'Failed to save');
} finally {
saving = false;
}
}
</script>
<Modal {onclose} class="w-full max-w-md mx-4">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="p-4"
onkeydown={(e) => {
if (e.key === 'Enter' && name.trim() && (bot || token.trim())) handleSubmit();
}}
>
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-3">
{bot ? 'Edit Bot' : 'Add Bot'}
</h2>
{#if !bot}
<!-- Platform + Name on same row -->
<div class="flex gap-3">
<div class="flex-1">
<label class="text-[10px] text-gray-400 dark:text-gray-600">Name</label>
<input
type="text"
bind:value={name}
placeholder="My Bot"
autofocus
autocomplete="off"
spellcheck="false"
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5"
/>
</div>
<div class="w-28 shrink-0">
<label class="text-[10px] text-gray-400 dark:text-gray-600">Platform</label>
<select
bind:value={platform}
onchange={() => { verifyResult = null; }}
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
>
<option value="telegram">Telegram</option>
<option value="discord">Discord</option>
</select>
</div>
</div>
{:else}
<!-- Edit mode: just name -->
<label class="text-[10px] text-gray-400 dark:text-gray-600">Name</label>
<input
type="text"
bind:value={name}
placeholder="My Bot"
autofocus
autocomplete="off"
spellcheck="false"
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5"
/>
{/if}
<!-- Token -->
<label class="text-[10px] text-gray-400 dark:text-gray-600">
Token {#if bot}<span class="text-gray-300 dark:text-gray-700">({bot.token_masked})</span>{/if}
</label>
<div class="flex gap-2 items-center mb-0.5">
<input
type="password"
bind:value={token}
placeholder={bot ? 'Leave empty to keep current' : platformHints[platform] || 'Paste token'}
autocomplete="new-password"
class="flex-1 bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
/>
{#if !bot}
<button
type="button"
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors disabled:opacity-30"
onclick={handleVerify}
disabled={verifying || !token.trim()}
>
{#if verifying}
<Spinner size={10} />
{:else}
Verify
{/if}
</button>
{/if}
</div>
{#if verifyResult}
<p class="text-[10px] mb-1 text-gray-500 dark:text-gray-400">
{#if verifyResult.ok}
✓ {verifyResult.info?.username ? `@${verifyResult.info.username}` : `ID: ${verifyResult.info?.id}`}
{:else}
✗ {verifyResult.error}
{/if}
</p>
{/if}
<!-- Allowed senders -->
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">Allowed senders</label>
<p class="text-[10px] text-gray-300 dark:text-gray-700 mb-0.5">Comma-separated user IDs. Leave empty to allow all.</p>
<input
type="text"
bind:value={allowedSenders}
placeholder="123456789, 987654321"
autocomplete="off"
spellcheck="false"
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
/>
<!-- Bottom toolbar -->
<div class="flex items-center justify-between mt-3 pt-2 gap-2">
<div class="flex items-center gap-1 flex-1 min-w-0">
<!-- Model selector -->
<ModelSelector bind:selectedModel={modelId} />
<!-- Workspace selector -->
<button
bind:this={wsBtnEl}
type="button"
class="flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors duration-100"
onclick={() => (showWsMenu = !showWsMenu)}
>
<Icon name="folder" size={12} />
<span class="truncate max-w-[120px]">{selectedWsName}</span>
<svg class="w-3 h-3 opacity-50" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
</div>
<button
type="button"
disabled={saving || !name.trim() || (!bot && !token.trim()) || !modelId || !workspace}
onclick={handleSubmit}
class="text-[13px] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-30 disabled:pointer-events-none"
>
{#if saving}
<Spinner size={14} />
{:else}
{bot ? 'Save' : 'Add'} →
{/if}
</button>
</div>
</div>
</Modal>
{#if showWsMenu && wsBtnEl}
<DropdownMenu
items={wsMenuItems}
anchor={wsBtnEl}
onclose={() => (showWsMenu = false)}
preferAbove={true}
maxHeight="15rem"
className="w-48"
/>
{/if}
@@ -0,0 +1,149 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import Icon from '../Icon.svelte';
import CreateBotModal from './CreateBotModal.svelte';
import { onMount } from 'svelte';
import { listBots, deleteBot, startBot, stopBot, type BotData } from '$lib/apis/bots';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
let bots = $state<BotData[]>([]);
let loading = $state(true);
let showCreate = $state(false);
let editBot = $state<BotData | null>(null);
async function load() {
try {
bots = await listBots();
} catch {
toast.error('Failed to load bots');
} finally {
loading = false;
}
}
function handleSaved() {
showCreate = false;
editBot = null;
load();
}
async function toggleRunning(e: Event, bot: BotData) {
e.stopPropagation();
const wasRunning = bot.is_running;
// Optimistic
bot.is_running = !wasRunning;
bots = [...bots];
try {
if (wasRunning) {
await stopBot(bot.id);
} else {
await startBot(bot.id);
}
await load();
} catch {
bot.is_running = wasRunning;
bots = [...bots];
toast.error('Failed to toggle bot');
}
}
async function handleDelete(e: Event, bot: BotData) {
e.stopPropagation();
try {
await deleteBot(bot.id);
await load();
} catch {
toast.error('Failed to delete bot');
}
}
onMount(load);
</script>
<div class="flex items-center justify-between mb-4">
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{$t('admin.messaging')}</h2>
<button
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => (showCreate = true)}
>
<Icon name="plus" size={14} />
</button>
</div>
{#if loading}
<div class="flex justify-center py-8">
<Spinner size={16} />
</div>
{:else}
<div>
{#each bots as bot}
<div class="group flex items-center gap-2 w-full h-7">
<!-- Platform badge -->
<span class="text-[10px] uppercase tracking-wide w-5 text-center shrink-0
{bot.is_running ? 'text-gray-400 dark:text-gray-500' : 'text-gray-300 dark:text-gray-700'}">
{bot.platform === 'telegram' ? 'TG' : bot.platform === 'discord' ? 'DC' : bot.platform.slice(0, 2).toUpperCase()}
</span>
<!-- Name (clickable to edit) -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
class="flex-1 text-[13px] truncate cursor-pointer
{bot.is_running ? 'text-gray-700 dark:text-gray-300' : 'text-gray-400 dark:text-gray-600'}"
onclick={() => (editBot = bot)}
onkeydown={() => {}}
>
{bot.name}
</span>
<!-- Delete (hover) -->
<button
type="button"
class="opacity-0 group-hover:opacity-100 text-gray-300 dark:text-gray-700 hover:text-red-500 dark:hover:text-red-400 transition-all p-0.5"
onclick={(e) => handleDelete(e, bot)}
>
<Icon name="trash" size={11} />
</button>
<!-- Toggle switch -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
class="relative w-6 h-3.5 rounded-full shrink-0 cursor-pointer transition-colors duration-150
{bot.is_running ? 'bg-gray-900 dark:bg-white' : 'bg-gray-200 dark:bg-gray-700'}"
role="switch"
tabindex="-1"
aria-checked={bot.is_running}
onclick={(e) => toggleRunning(e, bot)}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleRunning(e, bot);
}
}}
>
<span
class="absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all duration-150
{bot.is_running ? 'left-3 bg-white dark:bg-gray-900' : 'left-0.5 bg-white dark:bg-gray-500'}"
></span>
</span>
</div>
{/each}
{#if bots.length === 0}
<p class="text-[13px] text-gray-400 dark:text-gray-600 py-4">No messaging bots configured.</p>
{/if}
</div>
{/if}
{#if showCreate}
<CreateBotModal onclose={() => (showCreate = false)} onsave={handleSaved} />
{/if}
{#if editBot}
<CreateBotModal
bot={editBot}
onclose={() => (editBot = null)}
onsave={handleSaved}
/>
{/if}
@@ -8,6 +8,7 @@
import Users from './Admin/Users.svelte';
import Connections from './Admin/Connections.svelte';
import Models from './Admin/Models.svelte';
import Messaging from './Admin/Messaging.svelte';
import AdminSettings from './Admin/Settings.svelte';
import { session } from '$lib/session';
import { t } from '$lib/i18n';
@@ -20,6 +21,7 @@
| 'users'
| 'connections'
| 'models'
| 'messaging'
| 'admin_settings';
interface Props {
@@ -44,6 +46,7 @@
{ id: 'users', label: $t('admin.users'), icon: 'user' },
{ id: 'connections', label: $t('admin.connections'), icon: 'plug' },
{ id: 'models', label: $t('admin.models'), icon: 'cube' },
{ id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' },
{ id: 'admin_settings', label: $t('settings.configuration'), icon: 'shield' }
]);
</script>
@@ -113,6 +116,8 @@
<Connections />
{:else if activeTab === 'models'}
<Models />
{:else if activeTab === 'messaging'}
<Messaging />
{:else if activeTab === 'admin_settings'}
<AdminSettings />
{/if}
+25 -1
View File
@@ -408,5 +408,29 @@
"automationModal.createBtn": "Create",
"automationModal.failedToSave": "Failed to save automation",
"connections.failedToUpdate": "Failed to update connection"
"connections.failedToUpdate": "Failed to update connection",
"admin.messaging": "Messaging",
"messaging.loadError": "Failed to load bots",
"messaging.fillRequired": "All fields are required",
"messaging.created": "Bot created",
"messaging.createError": "Failed to create bot",
"messaging.started": "Bot started",
"messaging.stopped": "Bot stopped",
"messaging.toggleError": "Failed to toggle bot",
"messaging.deleted": "Bot deleted",
"messaging.deleteError": "Failed to delete bot",
"messaging.empty": "No messaging bots configured",
"messaging.addFirst": "+ Add your first bot",
"messaging.addBot": "Add Bot",
"messaging.start": "Start",
"messaging.stop": "Stop",
"messaging.verify": "Verify",
"messaging.createBot": "Create Bot",
"messaging.tokenPlaceholder": "Bot token...",
"messaging.namePlaceholder": "Bot name...",
"messaging.workspacePlaceholder": "Workspace path (e.g. /Users/you/project)",
"messaging.modelPlaceholder": "Model ID (e.g. openrouter/claude-sonnet-4-20250514)",
"messaging.sendersPlaceholder": "Allowed user IDs (comma-separated, leave empty for all)"
}
+1
View File
@@ -21,3 +21,4 @@ __all__ = [
"Automation",
"AutomationRun",
]
+3
View File
@@ -3,6 +3,7 @@
from cptr.routers.admin import router as admin_router
from cptr.routers.auth import router as auth_router
from cptr.routers.automations import router as automations_router
from cptr.routers.bridge import router as bridge_router
from cptr.routers.chat import router as chat_router
from cptr.routers.events import router as events_router
from cptr.routers.files import router as files_router
@@ -18,6 +19,7 @@ __all__ = [
"admin_router",
"auth_router",
"automations_router",
"bridge_router",
"chat_router",
"events_router",
"files_router",
@@ -29,3 +31,4 @@ __all__ = [
"terminal_router",
"workspace_router",
]
+243
View File
@@ -0,0 +1,243 @@
"""Admin API for messaging bots — CRUD + start/stop + token verification.
Bot configs are stored in the Config key-value store (not a separate table).
"""
from __future__ import annotations
import logging
import time
import uuid
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from cptr.routers.admin import require_admin
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/admin/bots", tags=["bots"])
# ── Request schemas ──────────────────────────────────────────
class BotCreate(BaseModel):
platform: str
name: str
workspace: str
model_id: str
token: str
allowed_senders: list[str] | None = None
is_active: bool = True
class BotUpdate(BaseModel):
name: str | None = None
workspace: str | None = None
model_id: str | None = None
token: str | None = None
allowed_senders: list[str] | None = None
is_active: bool | None = None
class TokenVerify(BaseModel):
platform: str
token: str
# ── Helpers ──────────────────────────────────────────────────
def _mask_token(token: str) -> str:
if not token or len(token) < 8:
return "****"
return f"{token[:4]}...{token[-4:]}"
def _serialize_bot(bot: dict, running: bool = False) -> dict:
"""Serialize a bot config for API response (token masked)."""
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import decrypt_key
try:
plain_token = decrypt_key(bot.get("token", ""), _get_jwt_secret())
masked = _mask_token(plain_token)
except Exception:
masked = "****"
return {
"id": bot.get("id"),
"platform": bot.get("platform"),
"name": bot.get("name"),
"workspace": bot.get("workspace"),
"model_id": bot.get("model_id"),
"token_masked": masked,
"allowed_senders": bot.get("allowed_senders") or [],
"is_active": bot.get("is_active", True),
"is_running": running,
"created_at": bot.get("created_at"),
"updated_at": bot.get("updated_at"),
}
# ── Endpoints ────────────────────────────────────────────────
@router.get("")
async def list_bots(request: Request):
auth = require_admin(request)
from cptr.utils.bridge import get_bot_configs
bots = await get_bot_configs()
# Filter to bots owned by this user
user_bots = [b for b in bots if b.get("user_id") == auth.user_id]
bot_manager = getattr(request.app.state, "bot_manager", None)
status = bot_manager.get_status() if bot_manager else {}
return [_serialize_bot(b, running=status.get(b["id"], False)) for b in user_bots]
@router.post("")
async def create_bot(request: Request, body: BotCreate):
auth = require_admin(request)
from cptr.utils.bridge import upsert_bot
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import encrypt_key
if body.platform not in ("telegram", "discord"):
raise HTTPException(400, f"Unsupported platform: {body.platform}")
now = int(time.time_ns())
bot = {
"id": str(uuid.uuid4()),
"user_id": auth.user_id,
"platform": body.platform,
"name": body.name,
"workspace": body.workspace,
"model_id": body.model_id,
"token": encrypt_key(body.token, _get_jwt_secret()),
"allowed_senders": body.allowed_senders,
"is_active": body.is_active,
"created_at": now,
"updated_at": now,
}
await upsert_bot(bot)
# Auto-start if active
if bot["is_active"]:
bot_manager = getattr(request.app.state, "bot_manager", None)
if bot_manager:
try:
await bot_manager.start_bot(bot)
except Exception:
logger.exception("Failed to auto-start bot %s", bot["id"][:8])
return _serialize_bot(bot)
@router.put("/{bot_id}")
async def update_bot(request: Request, bot_id: str, body: BotUpdate):
require_admin(request)
from cptr.utils.bridge import get_bot_by_id, upsert_bot
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import encrypt_key
bot = await get_bot_by_id(bot_id)
if not bot:
raise HTTPException(404, "Bot not found")
if body.name is not None:
bot["name"] = body.name
if body.workspace is not None:
bot["workspace"] = body.workspace
if body.model_id is not None:
bot["model_id"] = body.model_id
if body.token is not None:
bot["token"] = encrypt_key(body.token, _get_jwt_secret())
if body.allowed_senders is not None:
bot["allowed_senders"] = body.allowed_senders
if body.is_active is not None:
bot["is_active"] = body.is_active
bot["updated_at"] = int(time.time_ns())
await upsert_bot(bot)
# Restart if running (config changed)
bot_manager = getattr(request.app.state, "bot_manager", None)
if bot_manager and bot_manager.is_running(bot_id):
await bot_manager.stop_bot(bot_id)
if bot.get("is_active", True):
await bot_manager.start_bot(bot)
running = bot_manager.is_running(bot_id) if bot_manager else False
return _serialize_bot(bot, running=running)
@router.delete("/{bot_id}")
async def delete_bot(request: Request, bot_id: str):
require_admin(request)
from cptr.utils.bridge import delete_bot_config
bot_manager = getattr(request.app.state, "bot_manager", None)
if bot_manager and bot_manager.is_running(bot_id):
await bot_manager.stop_bot(bot_id)
ok = await delete_bot_config(bot_id)
if not ok:
raise HTTPException(404, "Bot not found")
return {"ok": True}
@router.post("/{bot_id}/start")
async def start_bot(request: Request, bot_id: str):
require_admin(request)
from cptr.utils.bridge import get_bot_by_id
bot = await get_bot_by_id(bot_id)
if not bot:
raise HTTPException(404, "Bot not found")
bot_manager = getattr(request.app.state, "bot_manager", None)
if not bot_manager:
raise HTTPException(500, "Bot manager not initialized")
if bot_manager.is_running(bot_id):
raise HTTPException(400, "Bot is already running")
await bot_manager.start_bot(bot)
return {"ok": True, "is_running": True}
@router.post("/{bot_id}/stop")
async def stop_bot(request: Request, bot_id: str):
require_admin(request)
bot_manager = getattr(request.app.state, "bot_manager", None)
if not bot_manager:
raise HTTPException(500, "Bot manager not initialized")
await bot_manager.stop_bot(bot_id)
return {"ok": True, "is_running": False}
@router.post("/verify")
async def verify_token(request: Request, body: TokenVerify):
require_admin(request)
try:
if body.platform == "telegram":
from cptr.utils.adapters.telegram import verify_token as tg_verify
info = await tg_verify(body.token)
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
elif body.platform == "discord":
from cptr.utils.adapters.discord import verify_token as dc_verify
info = await dc_verify(body.token)
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
else:
raise HTTPException(400, f"Unsupported platform: {body.platform}")
except Exception as e:
return {"ok": False, "error": str(e)}
+4
View File
@@ -213,6 +213,8 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
"""Discover models from a provider's /models endpoint."""
import httpx
from cptr.utils.ai import _openrouter_headers
secret = _get_jwt_secret()
api_key = decrypt_key(conn.get("api_key", ""), secret) if conn.get("api_key") else None
provider = conn.get("provider", "")
@@ -227,6 +229,7 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
headers={
"x-api-key": api_key or "",
"anthropic-version": "2023-06-01",
**_openrouter_headers(url),
},
)
if r.status_code == 200:
@@ -247,6 +250,7 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
url,
headers={
"Authorization": f"Bearer {api_key or ''}",
**_openrouter_headers(url),
},
)
if r.status_code == 200:
+1
View File
@@ -0,0 +1 @@
"""Messaging platform adapters."""
+259
View File
@@ -0,0 +1,259 @@
"""Discord adapter — zero SDK dependencies.
Uses raw WebSocket for the Discord Gateway and httpx for the REST API.
- Gateway v10 WebSocket: IDENTIFY → HEARTBEAT loop → MESSAGE_CREATE
- REST: ``POST /channels/{id}/messages`` for sending
- REST: ``PATCH /channels/{id}/messages/{id}`` for editing (streaming)
- REST: ``POST /channels/{id}/typing`` for typing indicators
"""
from __future__ import annotations
import asyncio
import json
import logging
import sys
from typing import Optional
import httpx
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
logger = logging.getLogger(__name__)
GATEWAY_URL = "wss://gateway.discord.gg/?v=10&encoding=json"
API_BASE = "https://discord.com/api/v10"
MAX_MESSAGE_LEN = 2000
RECONNECT_BASE_DELAY = 2.0
RECONNECT_MAX_DELAY = 60.0
# Gateway opcodes
OP_DISPATCH = 0
OP_HEARTBEAT = 1
OP_IDENTIFY = 2
OP_RESUME = 6
OP_RECONNECT = 7
OP_INVALID_SESSION = 9
OP_HELLO = 10
OP_HEARTBEAT_ACK = 11
# Required gateway intents
INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15)
class DiscordAdapter(BaseAdapter):
"""Discord bot via raw Gateway WebSocket + REST API."""
platform = "discord"
def __init__(self, token: str) -> None:
super().__init__()
self._token = token
self._http: Optional[httpx.AsyncClient] = None
self._ws = None
self._running = False
self._bot_id: str = ""
self._session_id: str = ""
self._resume_url: str = ""
self._seq: Optional[int] = None
self._heartbeat_task: Optional[asyncio.Task] = None
self._gateway_task: Optional[asyncio.Task] = None
# ── Lifecycle ──────────────────────────────────────────
async def connect(self) -> bool:
self._http = httpx.AsyncClient(
timeout=15,
headers={
"Authorization": f"Bot {self._token}",
"Content-Type": "application/json",
},
)
try:
resp = await self._http.get(f"{API_BASE}/users/@me")
resp.raise_for_status()
me = resp.json()
self._bot_id = me["id"]
logger.info("Discord bot connected: %s#%s", me.get("username"), me.get("discriminator"))
except Exception:
logger.exception("Discord token verification failed")
await self._http.aclose()
self._http = None
return False
self._running = True
self._gateway_task = asyncio.create_task(self._gateway_loop())
return True
async def disconnect(self) -> None:
self._running = False
if self._heartbeat_task and not self._heartbeat_task.done():
self._heartbeat_task.cancel()
if self._gateway_task and not self._gateway_task.done():
self._gateway_task.cancel()
try:
await self._gateway_task
except (asyncio.CancelledError, Exception):
pass
if self._ws:
try:
await self._ws.close()
except Exception:
pass
if self._http:
await self._http.aclose()
self._http = None
# ── Sending ────────────────────────────────────────────
async def send(self, chat_id: str, text: str) -> str | None:
"""Send a message. Returns the message ID for later editing."""
if not self._http:
return None
chunks = chunk_message(text, MAX_MESSAGE_LEN)
msg_id = None
for chunk in chunks:
resp = await self._http.post(
f"{API_BASE}/channels/{chat_id}/messages",
json={"content": chunk},
)
if msg_id is None and resp.status_code == 200:
data = resp.json()
msg_id = data.get("id")
return msg_id
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""Edit a previously sent message."""
if not self._http:
return
await self._http.patch(
f"{API_BASE}/channels/{chat_id}/messages/{message_id}",
json={"content": text[:MAX_MESSAGE_LEN]},
)
async def send_typing(self, chat_id: str) -> None:
if not self._http:
return
try:
await self._http.post(f"{API_BASE}/channels/{chat_id}/typing")
except Exception:
pass
# ── Gateway WebSocket ──────────────────────────────────
async def _gateway_loop(self) -> None:
delay = RECONNECT_BASE_DELAY
while self._running:
try:
await self._run_gateway_session()
delay = RECONNECT_BASE_DELAY
except asyncio.CancelledError:
return
except Exception as e:
logger.warning("Discord gateway error (%s), reconnecting in %.0fs", type(e).__name__, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
async def _run_gateway_session(self) -> None:
try:
import websockets
except ImportError:
logger.error("Discord adapter requires 'websockets' package. Install: pip install websockets")
self._running = False
return
url = self._resume_url or GATEWAY_URL
async with websockets.connect(url) as ws:
self._ws = ws
hello = json.loads(await ws.recv())
if hello.get("op") != OP_HELLO:
raise RuntimeError(f"Expected HELLO, got op={hello.get('op')}")
heartbeat_interval = hello["d"]["heartbeat_interval"] / 1000.0
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop(ws, heartbeat_interval))
if self._session_id and self._seq is not None:
await ws.send(json.dumps({
"op": OP_RESUME,
"d": {"token": self._token, "session_id": self._session_id, "seq": self._seq},
}))
else:
await ws.send(json.dumps({
"op": OP_IDENTIFY,
"d": {
"token": self._token,
"intents": INTENTS,
"properties": {"os": sys.platform, "browser": "cptr", "device": "cptr"},
},
}))
async for raw in ws:
if not self._running:
return
payload = json.loads(raw)
op = payload.get("op")
if op == OP_DISPATCH:
self._seq = payload.get("s")
event_type = payload.get("t")
data = payload.get("d", {})
if event_type == "READY":
self._session_id = data.get("session_id", "")
self._resume_url = data.get("resume_gateway_url", "")
logger.info("Discord gateway READY")
elif event_type == "MESSAGE_CREATE":
await self._handle_message_create(data)
elif op == OP_HEARTBEAT:
await ws.send(json.dumps({"op": OP_HEARTBEAT, "d": self._seq}))
elif op == OP_RECONNECT:
return
elif op == OP_INVALID_SESSION:
if not payload.get("d", False):
self._session_id = ""
self._seq = None
await asyncio.sleep(3)
return
async def _heartbeat_loop(self, ws, interval: float) -> None:
try:
while True:
await asyncio.sleep(interval)
await ws.send(json.dumps({"op": OP_HEARTBEAT, "d": self._seq}))
except (asyncio.CancelledError, Exception):
pass
async def _handle_message_create(self, data: dict) -> None:
author = data.get("author", {})
if author.get("bot", False) or author.get("id") == self._bot_id:
return
content = data.get("content", "").strip()
if not content:
return
event = MessageEvent(
platform="discord",
chat_id=data.get("channel_id", ""),
sender_id=author.get("id", ""),
sender_name=author.get("global_name") or author.get("username", "User"),
text=content,
)
if self.on_message:
await self.on_message(event)
async def verify_token(token: str) -> dict:
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.get(
f"{API_BASE}/users/@me",
headers={"Authorization": f"Bot {token}"},
)
if resp.status_code == 401:
raise ValueError("Invalid Discord bot token")
resp.raise_for_status()
return resp.json()
+270
View File
@@ -0,0 +1,270 @@
"""Telegram adapter — zero SDK dependencies.
Uses raw httpx calls to the Telegram Bot API:
- ``sendMessageDraft`` for native streaming (Bot API 9.5+)
- ``editMessageText`` as fallback for older clients
- ``getUpdates`` long-polling for inbound messages
- ``sendChatAction(typing)`` for typing indicators
"""
from __future__ import annotations
import asyncio
import logging
from typing import Optional
import httpx
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
logger = logging.getLogger(__name__)
API_BASE = "https://api.telegram.org/bot{token}"
POLL_TIMEOUT = 30 # seconds (Telegram long-poll)
MAX_MESSAGE_LEN = 4096
RECONNECT_BASE_DELAY = 2.0
RECONNECT_MAX_DELAY = 60.0
class TelegramAdapter(BaseAdapter):
"""Telegram bot via raw HTTP — getUpdates long-polling + native streaming."""
platform = "telegram"
def __init__(self, token: str) -> None:
super().__init__()
self._token = token
self._base = API_BASE.format(token=token)
self._client: Optional[httpx.AsyncClient] = None
self._offset: int = 0
self._poll_task: Optional[asyncio.Task] = None
self._running = False
self._bot_info: dict = {}
self._supports_draft: bool = True # Assume 9.5+, fallback on error
# ── Lifecycle ──────────────────────────────────────────
async def connect(self) -> bool:
self._client = httpx.AsyncClient(timeout=httpx.Timeout(POLL_TIMEOUT + 10))
try:
info = await self._api("getMe")
self._bot_info = info
logger.info(
"Telegram bot connected: @%s (%s)",
info.get("username", "?"),
info.get("id", "?"),
)
except Exception:
logger.exception("Telegram getMe failed — bad token?")
await self._client.aclose()
self._client = None
return False
self._running = True
self._poll_task = asyncio.create_task(self._poll_loop())
return True
async def disconnect(self) -> None:
self._running = False
if self._poll_task and not self._poll_task.done():
self._poll_task.cancel()
try:
await self._poll_task
except (asyncio.CancelledError, Exception):
pass
if self._client:
await self._client.aclose()
self._client = None
# ── Sending ────────────────────────────────────────────
async def send(self, chat_id: str, text: str) -> str | None:
"""Send a message. Returns the message ID for later editing."""
chunks = chunk_message(text, MAX_MESSAGE_LEN)
msg_id = None
for chunk in chunks:
result = await self._api(
"sendMessage",
chat_id=chat_id,
text=chunk,
parse_mode="Markdown",
disable_web_page_preview=True,
)
if msg_id is None and result:
msg_id = str(result.get("message_id", ""))
return msg_id
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""Edit a previously sent message."""
try:
await self._api(
"editMessageText",
chat_id=chat_id,
message_id=int(message_id),
text=text[:MAX_MESSAGE_LEN],
parse_mode="Markdown",
disable_web_page_preview=True,
)
except TelegramAPIError as e:
if "message is not modified" in e.description.lower():
pass # Content unchanged, ignore
elif "parse" in e.description.lower():
# Markdown parse error — retry without parse_mode
await self._api(
"editMessageText",
chat_id=chat_id,
message_id=int(message_id),
text=text[:MAX_MESSAGE_LEN],
disable_web_page_preview=True,
)
else:
raise
async def send_draft(self, chat_id: str, text: str, draft_id: str | None = None) -> str:
"""Send a streaming draft using sendMessageDraft (Bot API 9.5+).
Returns the draft_id for subsequent updates.
Falls back to edit-based streaming if the API doesn't support drafts.
"""
if not self._supports_draft:
raise TelegramAPIError(400, "Draft not supported")
try:
params: dict = {
"chat_id": chat_id,
"text": text[:MAX_MESSAGE_LEN],
"parse_mode": "Markdown",
}
if draft_id:
params["draft_id"] = draft_id
result = await self._api("sendMessageDraft", **params)
return str(result.get("draft_id", result.get("message_id", "")))
except TelegramAPIError as e:
if e.code == 404 or "unknown method" in e.description.lower():
# API doesn't support sendMessageDraft — fall back
self._supports_draft = False
logger.info("Telegram sendMessageDraft not available, falling back to editMessageText")
raise
# Markdown parse failure — retry without parse_mode
if "parse" in e.description.lower():
params.pop("parse_mode", None)
result = await self._api("sendMessageDraft", **params)
return str(result.get("draft_id", result.get("message_id", "")))
raise
async def send_typing(self, chat_id: str) -> None:
try:
await self._api("sendChatAction", chat_id=chat_id, action="typing")
except Exception:
pass
# ── Polling ────────────────────────────────────────────
async def _poll_loop(self) -> None:
delay = RECONNECT_BASE_DELAY
while self._running:
try:
updates = await self._api(
"getUpdates",
offset=self._offset,
timeout=POLL_TIMEOUT,
allowed_updates=["message"],
)
delay = RECONNECT_BASE_DELAY
for update in updates:
try:
await self._process_update(update)
except Exception:
logger.exception("Error processing Telegram update")
except asyncio.CancelledError:
return
except httpx.TimeoutException:
continue
except (httpx.ConnectError, httpx.ReadError, httpx.WriteError, OSError) as e:
logger.warning("Telegram poll network error (%s), retrying in %.0fs", type(e).__name__, delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
except Exception:
logger.exception("Telegram poll error, retrying in %.0fs", delay)
await asyncio.sleep(delay)
delay = min(delay * 2, RECONNECT_MAX_DELAY)
async def _process_update(self, update: dict) -> None:
update_id = update.get("update_id", 0)
self._offset = max(self._offset, update_id + 1)
message = update.get("message")
if not message:
return
text = message.get("text") or message.get("caption") or ""
if not text.strip():
return
chat = message.get("chat", {})
sender = message.get("from", {})
event = MessageEvent(
platform="telegram",
chat_id=str(chat.get("id", "")),
sender_id=str(sender.get("id", "")),
sender_name=(
sender.get("first_name", "")
+ (" " + sender.get("last_name", "") if sender.get("last_name") else "")
).strip() or "User",
text=text,
)
if self.on_message:
await self.on_message(event)
# ── API helpers ────────────────────────────────────────
async def _api(self, method: str, **params) -> any:
if not self._client:
raise RuntimeError("Telegram client not connected")
url = f"{self._base}/{method}"
data = {k: v for k, v in params.items() if v is not None}
resp = await self._client.post(url, json=data)
body = resp.json()
if not body.get("ok"):
error_code = body.get("error_code", resp.status_code)
description = body.get("description", "Unknown error")
# Markdown parse failure — retry without parse_mode
if error_code == 400 and "parse" in description.lower() and "text" in data:
data.pop("parse_mode", None)
resp = await self._client.post(url, json=data)
body = resp.json()
if body.get("ok"):
return body.get("result")
raise TelegramAPIError(error_code, description)
return body.get("result")
class TelegramAPIError(Exception):
def __init__(self, code: int, description: str):
self.code = code
self.description = description
super().__init__(f"Telegram API error {code}: {description}")
async def verify_token(token: str) -> dict:
"""Verify a Telegram bot token by calling getMe."""
async with httpx.AsyncClient(timeout=10) as client:
url = f"{API_BASE.format(token=token)}/getMe"
resp = await client.get(url)
body = resp.json()
if not body.get("ok"):
raise TelegramAPIError(
body.get("error_code", resp.status_code),
body.get("description", "Invalid token"),
)
return body["result"]
+718
View File
@@ -0,0 +1,718 @@
"""Messaging bridge: adapter base class, BotManager lifecycle, and message routing.
Integrates external messaging platforms (Telegram, Discord, etc.) as alternative
frontends to cptr. Each platform adapter connects via its native protocol (long-
polling, WebSocket) and translates inbound messages into cptr chat tasks using the
same agentic loop as the web UI.
Bot configs are stored in the Config key-value store (same as connections).
Thread mappings (external chat → cptr chat) are stored in chat.meta.
"""
from __future__ import annotations
import asyncio
import logging
import time
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, Optional
logger = logging.getLogger(__name__)
# How often to edit the streaming message (seconds).
STREAM_EDIT_INTERVAL = 2.0
# Typing indicator refresh interval (seconds).
TYPING_INTERVAL = 5.0
# ── Adapter interface ────────────────────────────────────────
@dataclass
class MessageEvent:
"""Normalized inbound message from any platform."""
platform: str # "telegram", "discord", etc.
chat_id: str # Platform's chat/channel ID
sender_id: str # Platform's user ID
sender_name: str # Display name
text: str # Message content
class BaseAdapter(ABC):
"""Abstract base for messaging platform adapters.
Subclasses implement the required methods. The adapter does NOT
interpret message content — it only shuttles text between the platform
and the bridge core.
"""
platform: str = "unknown"
# Set by BotManager when the adapter is started.
on_message: Optional[Callable[[MessageEvent], Awaitable[None]]] = None
@abstractmethod
async def connect(self) -> bool:
"""Start listening for messages. Return True on success."""
...
@abstractmethod
async def disconnect(self) -> None:
"""Stop listening and release resources."""
...
@abstractmethod
async def send(self, chat_id: str, text: str) -> str | None:
"""Send a text message. Returns the platform message ID (for editing)."""
...
@abstractmethod
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
"""Edit a previously sent message."""
...
@abstractmethod
async def send_typing(self, chat_id: str) -> None:
"""Show a typing indicator in the chat."""
...
# ── Message chunking ─────────────────────────────────────────
def chunk_message(text: str, max_len: int = 4096) -> list[str]:
"""Split a long message at paragraph / sentence boundaries."""
if len(text) <= max_len:
return [text]
chunks: list[str] = []
remaining = text
while remaining:
if len(remaining) <= max_len:
chunks.append(remaining)
break
cut = remaining.rfind("\n\n", 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[:cut])
remaining = remaining[cut + 2:]
continue
cut = remaining.rfind("\n", 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[:cut])
remaining = remaining[cut + 1:]
continue
for sep in (". ", "! ", "? "):
cut = remaining.rfind(sep, 0, max_len)
if cut > max_len // 4:
chunks.append(remaining[: cut + 1])
remaining = remaining[cut + 2:]
break
else:
chunks.append(remaining[:max_len])
remaining = remaining[max_len:]
return [c for c in chunks if c.strip()]
# ── Config-backed bot storage ────────────────────────────────
async def get_bot_configs() -> list[dict]:
"""Load all bot configs from the Config store."""
from cptr.models import Config
bots = await Config.get("bots")
return bots if isinstance(bots, list) else []
async def save_bot_configs(bots: list[dict]) -> None:
"""Save all bot configs to the Config store."""
from cptr.models import Config
await Config.upsert({"bots": bots})
async def get_bot_by_id(bot_id: str) -> dict | None:
"""Find a single bot config by ID."""
for bot in await get_bot_configs():
if bot.get("id") == bot_id:
return bot
return None
async def upsert_bot(bot: dict) -> None:
"""Insert or update a single bot config."""
bots = await get_bot_configs()
for i, b in enumerate(bots):
if b.get("id") == bot.get("id"):
bots[i] = bot
await save_bot_configs(bots)
return
bots.append(bot)
await save_bot_configs(bots)
async def delete_bot_config(bot_id: str) -> bool:
"""Remove a bot config by ID."""
bots = await get_bot_configs()
filtered = [b for b in bots if b.get("id") != bot_id]
if len(filtered) == len(bots):
return False
await save_bot_configs(filtered)
return True
# ── Thread mapping via chat.meta ─────────────────────────────
async def find_chat_for_thread(bot_id: str, external_thread_id: str) -> str | None:
"""Find an existing cptr chat_id for a platform thread.
Scans chats with matching bridge metadata. This is fine for the
small number of active bridge threads (typically < 100).
"""
from cptr.models import Chat
from cptr.utils.db import get_db
from sqlalchemy import select
async with await get_db() as db:
result = await db.execute(
select(Chat).where(Chat.user_id.isnot(None))
)
for chat in result.scalars():
meta = chat.meta or {}
if (
meta.get("bridge_bot_id") == bot_id
and meta.get("bridge_external_thread_id") == external_thread_id
):
return chat.id
return None
# ── BotManager ───────────────────────────────────────────────
class BotManager:
"""Manages messaging bot lifecycles.
Singleton attached to ``app.state.bot_manager``. Reads bot configs
from the Config store on startup, creates adapters, and runs them as
asyncio tasks.
"""
def __init__(self) -> None:
self._adapters: dict[str, BaseAdapter] = {} # bot_id → adapter
self._tasks: dict[str, asyncio.Task] = {} # bot_id → polling task
self._stream_tasks: dict[str, asyncio.Task] = {} # key → streaming task
# ── Lifecycle ──────────────────────────────────────────
async def start_all(self) -> None:
"""Load all active bots from Config and start them."""
bots = await get_bot_configs()
started = 0
for bot in bots:
if not bot.get("is_active", True):
continue
try:
await self.start_bot(bot)
started += 1
except Exception:
logger.exception("Failed to start bot %s", bot.get("name", "?"))
if started:
logger.info("Bot manager started %d bot(s)", started)
async def start_bot(self, bot: dict) -> None:
"""Start a single bot adapter."""
bot_id = bot["id"]
if bot_id in self._tasks:
logger.warning("Bot %s already running", bot_id[:8])
return
adapter = self._create_adapter(bot)
if adapter is None:
logger.error("Unknown platform '%s' for bot %s", bot.get("platform"), bot_id[:8])
return
adapter.on_message = lambda event, _bot=bot: self._handle_message(event, _bot)
self._adapters[bot_id] = adapter
async def _run() -> None:
try:
ok = await adapter.connect()
if not ok:
logger.error("Bot %s failed to connect", bot.get("name", "?"))
return
logger.info("Bot %s connected on %s", bot.get("name"), bot.get("platform"))
while True:
await asyncio.sleep(3600)
except asyncio.CancelledError:
pass
except Exception:
logger.exception("Bot %s crashed", bot_id[:8])
finally:
try:
await adapter.disconnect()
except Exception:
logger.debug("Adapter disconnect error", exc_info=True)
self._tasks[bot_id] = asyncio.create_task(_run())
async def stop_bot(self, bot_id: str) -> None:
task = self._tasks.pop(bot_id, None)
if task and not task.done():
task.cancel()
try:
await asyncio.wait_for(task, timeout=5.0)
except (asyncio.CancelledError, asyncio.TimeoutError):
pass
self._adapters.pop(bot_id, None)
logger.info("Bot %s stopped", bot_id[:8])
async def stop_all(self) -> None:
for bot_id in list(self._tasks.keys()):
await self.stop_bot(bot_id)
def is_running(self, bot_id: str) -> bool:
task = self._tasks.get(bot_id)
return task is not None and not task.done()
def get_status(self) -> dict[str, bool]:
return {bid: not t.done() for bid, t in self._tasks.items()}
# ── Adapter factory ────────────────────────────────────
def _create_adapter(self, bot: dict) -> BaseAdapter | None:
from cptr.utils.config import _get_jwt_secret
from cptr.utils.crypto import decrypt_key
token = decrypt_key(bot["token"], _get_jwt_secret())
if bot["platform"] == "telegram":
from cptr.utils.adapters.telegram import TelegramAdapter
return TelegramAdapter(token=token)
if bot["platform"] == "discord":
from cptr.utils.adapters.discord import DiscordAdapter
return DiscordAdapter(token=token)
return None
# ── Message handling ───────────────────────────────────
async def _handle_message(self, event: MessageEvent, bot: dict) -> None:
"""Core message handler: auth → commands → thread map → create chat → start_task → stream."""
# 1. Auth check
allowed = bot.get("allowed_senders") or []
if allowed and event.sender_id not in allowed:
logger.debug("Ignoring unauthorized sender %s on bot %s", event.sender_id, bot["id"][:8])
return
adapter = self._adapters.get(bot["id"])
text = (event.text or "").strip()
# Normalize: strip Discord bot mention prefix (<@123456>)
# and Telegram command suffix (/cmd@BotName → /cmd)
import re
clean = re.sub(r"<@!?\d+>\s*", "", text).strip()
cmd = clean.split("@")[0].lower() if clean.startswith("/") else ""
# 2. Slash commands
if cmd in ("/new", "/reset", "/start"):
await self._create_chat(event, bot)
if adapter:
try:
await adapter.send(event.chat_id, "✨ New conversation started.")
except Exception:
pass
return
if cmd == "/help":
help_text = (
"/new — Start a new conversation\n"
"/reset — Same as /new\n"
"/help — Show this message"
)
if adapter:
try:
await adapter.send(event.chat_id, help_text)
except Exception:
pass
return
if not clean:
return
# 3. Thread mapping — find or create a cptr chat
chat_id = await find_chat_for_thread(bot["id"], event.chat_id)
if not chat_id:
chat_id = await self._create_chat(event, bot)
# Use the cleaned text (bot mention stripped) for the actual message
event.text = clean
# 4. Dispatch task with streaming
await self._dispatch_task(chat_id, event, bot, adapter)
async def _create_chat(self, event: MessageEvent, bot: dict) -> str:
from cptr.models import Chat
from cptr.utils.config import now_ms
title = f"{event.sender_name} ({bot['platform']})"
chat = await Chat.create(
user_id=bot["user_id"],
title=title[:100],
meta={
"workspace": bot["workspace"],
"bridge_bot_id": bot["id"],
"bridge_platform": bot["platform"],
"bridge_external_thread_id": event.chat_id,
"params": {"tool_approval_mode": "full"},
},
created_at=now_ms(),
)
from pathlib import Path
chats_dir = Path(bot["workspace"]) / ".cptr" / "chats"
chats_dir.mkdir(parents=True, exist_ok=True)
(chats_dir / f"{chat.id}.json").write_text("{}")
return chat.id
async def _dispatch_task(
self, chat_id: str, event: MessageEvent, bot: dict, adapter: BaseAdapter | None,
) -> None:
from cptr.models import Chat, ChatMessage
from cptr.routers.chat import _resolve_connection
from cptr.utils.chat_task import start_task, _task_chat
from cptr.utils.config import now_ms
# Get current chat state for parent_id threading
chat = await Chat.get_by_id(chat_id)
parent_id = chat.current_message_id if chat else None
# Don't dispatch if a task is already running for this chat
active_chat_ids = set(_task_chat.values())
if chat_id in active_chat_ids:
await ChatMessage.create(
chat_id=chat_id, role="user", content=event.text,
parent_id=parent_id,
meta={"queued": True}, created_at=now_ms(),
)
logger.info("[bridge] Queued message for busy chat %s", chat_id[:8])
return
# Create user message — parent_id chains to previous assistant reply
user_msg = await ChatMessage.create(
chat_id=chat_id, role="user", content=event.text,
parent_id=parent_id, created_at=now_ms(),
)
# Resolve model connection
try:
connection, bare_model = await _resolve_connection(bot["model_id"])
except Exception:
logger.exception("[bridge] Failed to resolve model %s", bot["model_id"])
if adapter:
await adapter.send(event.chat_id, "⚠️ Model connection error. Check settings.")
return
# Create assistant placeholder
assistant_msg = await ChatMessage.create(
chat_id=chat_id, role="assistant", content="", parent_id=user_msg.id,
model=bot["model_id"], done=False, created_at=now_ms(),
)
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
# Export JSON so the web UI can see the chat immediately
from cptr.utils.chat_export import export_chat_to_file
await export_chat_to_file(chat_id)
# Send initial "thinking" message for non-draft platforms (Discord)
# Telegram uses sendMessageDraft which handles this natively
platform_msg_id = None
if adapter and bot["platform"] != "telegram":
try:
platform_msg_id = await adapter.send(event.chat_id, "⏳ Thinking...")
except Exception:
logger.debug("[bridge] Failed to send initial message", exc_info=True)
# Start the streaming edit loop
stream_key = f"{bot['id']}:{event.chat_id}"
self._stream_tasks[stream_key] = asyncio.create_task(
self._stream_loop(
adapter, event.chat_id, platform_msg_id,
assistant_msg.id, bot,
)
)
# Start the agentic loop
start_task(
message_id=assistant_msg.id,
chat_id=chat_id,
user_id=bot["user_id"],
connection=connection,
workspace=bot["workspace"],
model=bare_model,
)
logger.info("[bridge] Started task for bot %s, chat %s", bot["id"][:8], chat_id[:8])
async def _stream_loop(
self,
adapter: BaseAdapter | None,
platform_chat_id: str,
platform_msg_id: str | None,
task_message_id: str,
bot: dict,
) -> None:
"""Stream task output to the platform in real time.
Telegram: uses sendMessageDraft for smooth native streaming, then
sendMessage to persist the final response (drafts are ephemeral).
Discord: uses edit-based streaming (PATCH /messages).
"""
from cptr.utils.chat_task import _task_state, _tasks
if not adapter:
return
max_len = 4096 if bot["platform"] == "telegram" else 2000
last_sent = ""
is_telegram = bot["platform"] == "telegram"
# Telegram: use draft-based streaming
draft_id: int | None = None
use_draft = is_telegram
if use_draft:
try:
from cptr.utils.adapters.telegram import TelegramAdapter
if isinstance(adapter, TelegramAdapter):
# Start with empty draft → shows "Thinking..." placeholder
draft_id = await adapter.send_draft(platform_chat_id, "", None)
else:
use_draft = False
except Exception:
use_draft = False
logger.debug("[bridge] Draft not supported, falling back to edit", exc_info=True)
# Fallback: if draft failed or non-Telegram, ensure we have a message to edit
if not use_draft and not platform_msg_id:
try:
platform_msg_id = await adapter.send(platform_chat_id, "⏳ Thinking...")
except Exception:
logger.debug("[bridge] Failed to send fallback message", exc_info=True)
try:
while True:
task = _tasks.get(task_message_id)
task_done = task is None or task.done()
state = _task_state.get(task_message_id)
content = (state.get("content", "") if state else "").strip()
output_items = state.get("output", []) if state else []
# Build display: tool progress + text content
tool_lines = _render_tool_progress(output_items)
display_parts = []
if tool_lines:
display_parts.append(tool_lines)
if content:
display_parts.append(content)
display = "\n\n".join(display_parts).strip()
if display and display != last_sent:
display = display[:max_len]
if use_draft:
try:
draft_id = await adapter.send_draft(
platform_chat_id, display, draft_id
)
last_sent = display
except Exception:
use_draft = False
if not use_draft and platform_msg_id:
try:
await adapter.edit(platform_chat_id, platform_msg_id, display)
last_sent = display
except Exception:
pass
elif not display and not last_sent:
if not use_draft:
try:
await adapter.send_typing(platform_chat_id)
except Exception:
pass
if task_done:
break
await asyncio.sleep(STREAM_EDIT_INTERVAL)
# ── Task complete — send final response ──
from cptr.models import ChatMessage
msg = await ChatMessage.get_by_id(task_message_id)
final_content = (msg.content if msg else content).strip()
if not final_content:
if use_draft:
await adapter.send(platform_chat_id, "✅ Done (no text output)")
elif platform_msg_id:
await adapter.edit(platform_chat_id, platform_msg_id, "✅ Done (no text output)")
return
final_display = final_content
if use_draft:
# Draft is ephemeral — must send a real message to persist
chunks = chunk_message(final_display, max_len)
for chunk in chunks:
try:
await adapter.send(platform_chat_id, chunk)
except Exception:
logger.exception("[bridge] Failed to send final chunk")
else:
# Discord: edit the placeholder, then send overflow
if len(final_display) <= max_len and platform_msg_id:
try:
await adapter.edit(platform_chat_id, platform_msg_id, final_display)
return
except Exception:
pass
chunks = chunk_message(final_display, max_len)
if platform_msg_id and chunks:
try:
await adapter.edit(platform_chat_id, platform_msg_id, chunks[0])
chunks = chunks[1:]
except Exception:
pass
for chunk in chunks:
try:
await adapter.send(platform_chat_id, chunk)
except Exception:
logger.exception("[bridge] Failed to send reply chunk")
break
except asyncio.CancelledError:
pass
except Exception:
logger.exception("[bridge] Stream loop error")
# ── Tool call rendering ──────────────────────────────────────
# Map tool names to compact emoji + labels
_TOOL_ICONS = {
"bash": "💻",
"shell": "💻",
"run_command": "💻",
"read_file": "📄",
"write_file": "✏️",
"edit_file": "✏️",
"create_file": "✏️",
"replace_file": "✏️",
"search": "🔍",
"grep": "🔍",
"find_files": "🔍",
"web_search": "🌐",
"browser": "🌐",
"create_artifact": "📎",
}
def _render_tool_progress(output_items: list[dict]) -> str:
"""Render tool calls as compact status lines for streaming display.
Example output:
💻 `ls -la src/`
📄 `main.py` (reading)
✏️ `config.ts` (editing)
"""
lines = []
for item in output_items:
item_type = item.get("type", "")
if item_type != "function_call":
continue
name = item.get("name", "")
status = item.get("status", "")
args = item.get("arguments", {})
icon = _TOOL_ICONS.get(name, "🔧")
# Extract the most relevant argument for display
label = _tool_label(name, args)
status_text = "" if status == "completed" else " _(running)_"
lines.append(f"{icon} `{label}`{status_text}")
return "\n".join(lines[-5:]) # Show last 5 tool calls max
def _render_tool_summary(output_items: list[dict]) -> str:
"""Render a compact summary of all tools used (for final message).
Example: "🔧 Used 3 tools: bash, read_file, write_file"
"""
tool_names = []
for item in output_items:
if item.get("type") == "function_call":
name = item.get("name", "unknown")
if name not in tool_names:
tool_names.append(name)
if not tool_names:
return ""
count = sum(1 for i in output_items if i.get("type") == "function_call")
names = ", ".join(tool_names[:5])
if len(tool_names) > 5:
names += f" +{len(tool_names) - 5} more"
return f"🔧 _{count} tool call{'s' if count != 1 else ''}: {names}_"
def _tool_label(name: str, args: dict) -> str:
"""Extract a short, meaningful label from tool arguments."""
if isinstance(args, str):
return name
# Command execution
if name in ("bash", "shell", "run_command"):
cmd = args.get("command", args.get("cmd", ""))
if isinstance(cmd, str):
return cmd[:60] if cmd else name
return name
# File operations
for key in ("path", "file", "file_path", "filename", "target"):
val = args.get(key, "")
if val and isinstance(val, str):
# Just show the basename
parts = val.rsplit("/", 1)
return parts[-1] if parts else val
# Search
if name in ("search", "grep", "find_files"):
query = args.get("query", args.get("pattern", ""))
if isinstance(query, str):
return query[:40] if query else name
return name
+10 -3
View File
@@ -944,20 +944,27 @@ async def run_chat_task(
)
if should_auto:
# Show tool call in progress BEFORE execution
item["status"] = "in_progress"
output_items.append(item)
if flushed_item:
await emit(output=flushed_item)
await emit(output=item)
_sync_state()
if name == "create_artifact":
result = await create_artifact(**event["arguments"], workspace=workspace)
else:
result = await execute_tool(name, event["arguments"], {"workspace": workspace, "user_id": user_id, "model_id": model})
# Update status to completed
item["status"] = "completed"
output_items.append(item)
result_item = {
"type": "function_call_output",
"call_id": event["call_id"],
"output": result,
}
output_items.append(result_item)
if flushed_item:
await emit(output=flushed_item)
await emit(output=item)
await emit(output=result_item)
_sync_state()