Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(channels): start an Agent group from a bound Telegram group

Abdurrahman Fakhrul23b550bdd59d
diff --git a/app/api/v1/channels/telegram/[id]/route.ts b/app/api/v1/channels/telegram/[id]/route.ts
index 8cfc4e65..4442b7da 100644
--- a/app/api/v1/channels/telegram/[id]/route.ts
+++ b/app/api/v1/channels/telegram/[id]/route.ts
@@ -17,6 +17,9 @@ export async function POST(req: NextRequest, context: { params: Promise<{ id: st
return NextResponse.json({ ok: true, eventId: event.eventId, ...dispatched });
} catch (error) {
const value = error instanceof ChannelError ? error : new ChannelError("invalid_channel_webhook");
+ // 202 = acknowledged and intentionally not acted on (bot echo, or a group
+ // message that is not an owner /discuss command). Telegram should not retry.
+ if (value.status === 202) return NextResponse.json({ ok: true, ignored: value.code }, { status: 200 });
return NextResponse.json({ error: value.code }, { status: value.status });
}
}
diff --git a/frontend/slices/channels/components/channel-editor.tsx b/frontend/slices/channels/components/channel-editor.tsx
index a14a3f67..9f314740 100644
--- a/frontend/slices/channels/components/channel-editor.tsx
+++ b/frontend/slices/channels/components/channel-editor.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useState } from "react";
+import { useMemo, useState, useEffect } from "react";
import { Plug } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -12,6 +12,8 @@ import type { ChannelsSnapshot, ChannelProviderId, ChannelView, WorkflowOption }
const selectClass = "h-9 w-full rounded-md border bg-background px-2 text-sm";
const credentialValue = (user: string, connection: string) => `${user}::${connection}`;
+type GroupOption = { id: string; name: string };
+
export function ChannelEditor({
open,
onOpenChange,
@@ -40,10 +42,20 @@ export function ChannelEditor({
const [credential, setCredential] = useState(initialCredential);
const [target, setTarget] = useState(row?.defaultTarget ?? "");
const [workflowId, setWorkflowId] = useState(row?.workflowId ?? "");
+ const [agentGroupId, setAgentGroupId] = useState(row?.agentGroupId ?? "");
+ const [groups, setGroups] = useState<GroupOption[]>([]);
const [enabled, setEnabled] = useState(row?.enabled ?? true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
+ useEffect(() => {
+ if (!open) return;
+ fetch("/api/v1/agent-groups", { cache: "no-store" })
+ .then((response) => response.json())
+ .then((body: { groups?: GroupOption[] }) => setGroups(body.groups ?? []))
+ .catch(() => setGroups([]));
+ }, [open]);
+
const credentials = useMemo(
() => snapshot.credentials.filter((item) => item.provider === provider),
[provider, snapshot.credentials],
@@ -67,6 +79,7 @@ export function ChannelEditor({
enabled,
defaultTarget: target,
workflowId,
+ agentGroupId,
};
await channelAction(row
? { action: "update", id: row.id, expectedRevision: snapshot.revision, data }
@@ -111,6 +124,12 @@ export function ChannelEditor({
{workflows.map((workflow) => <option key={workflow.id} value={workflow.id}>{workflow.name}</option>)}
</select>
</Field>
+ <Field label="Agent group (Telegram discussion)">
+ <select className={selectClass} value={agentGroupId} onChange={(event) => setAgentGroupId(event.target.value)}>
+ <option value="">Not linked</option>
+ {groups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}
+ </select>
+ </Field>
<label className="flex items-center justify-between rounded-lg border p-3">
<span><span className="block text-sm font-medium">Enabled</span><span className="text-xs text-muted-foreground">Allow send and verified inbound events.</span></span>
<Switch checked={enabled} onCheckedChange={setEnabled}/>
diff --git a/frontend/slices/channels/types.ts b/frontend/slices/channels/types.ts
index 6bb33557..50edd0de 100644
--- a/frontend/slices/channels/types.ts
+++ b/frontend/slices/channels/types.ts
@@ -17,6 +17,7 @@ export type ChannelView = {
enabled: boolean;
defaultTarget?: string;
workflowId?: string;
+ agentGroupId?: string;
createdAt: string;
updatedAt: string;
lastCheck?: { at: string; ok: boolean; detail: string };
diff --git a/lib/channels/group-trigger.test.ts b/lib/channels/group-trigger.test.ts
new file mode 100644
index 00000000..7ec26ffd
--- /dev/null
+++ b/lib/channels/group-trigger.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { ChannelError } from "./errors";
+import { telegramGroupEvent } from "./service";
+import { normalizeTelegramUpdate } from "./providers/telegram";
+import type { ChannelInboundEvent } from "./types";
+
+const update = (message: Record<string, unknown>, id = 1): ChannelInboundEvent =>
+ normalizeTelegramUpdate({ update_id: id, message });
+
+describe("telegram group discussion trigger", () => {
+ it("accepts an owner /discuss command and returns only the topic", () => {
+ const event = telegramGroupEvent(update({ text: "/discuss Should we ship?", chat: { id: -100987 }, from: { id: 5, is_bot: false } }));
+ expect(event.text).toBe("Should we ship?");
+ });
+
+ it("tolerates a bot-addressed /discuss@bot command", () => {
+ const event = telegramGroupEvent(update({ text: "/discuss@hermes_bot Argue about caching.", chat: { id: -100987 }, from: { id: 5 } }));
+ expect(event.text).toBe("Argue about caching.");
+ });
+
+ it("drops bot traffic so agents never answer each other into a loop", () => {
+ const event = update({ text: "/discuss loop?", chat: { id: -100987 }, from: { id: 9, is_bot: true } });
+ expect(() => telegramGroupEvent(event)).toThrow(ChannelError);
+ try { telegramGroupEvent(event); } catch (error) {
+ expect((error as ChannelError).status).toBe(202);
+ }
+ });
+
+ it("drops plain group chatter that is not a /discuss command", () => {
+ expect(() => telegramGroupEvent(update({ text: "hello everyone", chat: { id: -100987 }, from: { id: 5 } }))).toThrow(ChannelError);
+ });
+});
diff --git a/lib/channels/schema.ts b/lib/channels/schema.ts
index 15dca4d3..2f89aebd 100644
--- a/lib/channels/schema.ts
+++ b/lib/channels/schema.ts
@@ -65,6 +65,13 @@ export function parseChannelPatch(
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(workflowId)) throw new ChannelError("invalid_workflow");
}
+ const groupRaw = raw.agentGroupId === undefined ? previous?.agentGroupId : raw.agentGroupId;
+ let agentGroupId: string | undefined;
+ if (groupRaw !== undefined && groupRaw !== null && groupRaw !== "") {
+ agentGroupId = clean(groupRaw, "agent_group", 36);
+ if (!/^[0-9a-f-]{36}$/i.test(agentGroupId)) throw new ChannelError("invalid_agent_group");
+ }
+
return {
name,
provider: providerRaw,
@@ -72,5 +79,6 @@ export function parseChannelPatch(
enabled,
...(defaultTarget ? { defaultTarget } : {}),
...(workflowId ? { workflowId } : {}),
+ ...(agentGroupId ? { agentGroupId } : {}),
};
}
diff --git a/lib/channels/service.ts b/lib/channels/service.ts
index 6c67946c..36994778 100644
--- a/lib/channels/service.ts
+++ b/lib/channels/service.ts
@@ -118,11 +118,29 @@ export async function receiveTelegram(id: string, raw: unknown, suppliedSecret:
const channel = await channelById(id);
if (channel.provider !== "telegram") throw new ChannelError("channel_provider_mismatch", 404);
assertEnabled(channel);
+ const event = normalizeTelegramUpdate(raw);
+ // A group wired to an Agent group authenticates by its bound group id plus a
+ // leading /discuss command, so it does not require a webhook secret. Bot
+ // traffic is dropped here so agents never answer each other into a loop.
+ if (channel.agentGroupId) return telegramGroupEvent(event);
const credential = await values(channel);
if (!credential.webhookSecret) throw new ChannelError("telegram_webhook_secret_required", 503);
if (!verifyTelegramSecret(credential, suppliedSecret)) throw new ChannelError("invalid_webhook_signature", 401);
if (rateLimited(`channel-authenticated:${id}`, 120, 60_000)) throw new ChannelError("rate_limited", 429);
- return normalizeTelegramUpdate(raw);
+ return event;
+}
+
+const DISCUSS = /^\/discuss(?:@\w+)?\s+([\s\S]+)$/;
+
+// Returns the discussion topic for a group message that belongs to an Agent
+// group, or throws to drop anything that is not an owner command.
+export function telegramGroupEvent(event: ChannelInboundEvent): ChannelInboundEvent {
+ const raw = event.raw as { message?: { from?: { is_bot?: boolean } } } | undefined;
+ if (raw?.message?.from?.is_bot) throw new ChannelError("telegram_bot_message_ignored", 202);
+ if (event.kind !== "message") throw new ChannelError("telegram_group_command_required", 202);
+ const topic = event.text?.trim().match(DISCUSS)?.[1]?.trim();
+ if (!topic) throw new ChannelError("telegram_group_command_required", 202);
+ return { ...event, text: topic };
}
export async function receiveDiscord(
diff --git a/lib/channels/types.ts b/lib/channels/types.ts
index 40b97ab8..a49870bd 100644
--- a/lib/channels/types.ts
+++ b/lib/channels/types.ts
@@ -20,6 +20,7 @@ export type ChannelRecord = {
enabled: boolean;
defaultTarget?: string;
workflowId?: string;
+ agentGroupId?: string;
workflowBinding?: { owner: string; nodeId: string; revision: string };
createdAt: string;
updatedAt: string;
diff --git a/lib/channels/workflow.ts b/lib/channels/workflow.ts
index f45c16eb..29139e10 100644
--- a/lib/channels/workflow.ts
+++ b/lib/channels/workflow.ts
@@ -4,6 +4,7 @@ import type { Scope } from "@/lib/capabilities/scope";
import type { CapabilityTool } from "@/lib/capabilities/tool";
import { findActiveChannelSource } from "@/lib/workflow/graph-triggers";
import { startWorkflowGraph } from "@/lib/workflow/graph-engine";
+import { startAgentGroupRun } from "@/lib/agent-group";
import { ChannelError } from "./errors";
import { channelById, recordChannelActivity } from "./store";
import type { ChannelInboundEvent } from "./types";
@@ -31,6 +32,11 @@ export async function dispatchChannelInbound(
) {
const channel = await channelById(channelId);
await recordChannelActivity(channelId);
+ if (channel.agentGroupId) {
+ if (!await admitChannelEvent(channelId, event.eventId)) return { agentGroup: null, duplicate: true };
+ const run = await startAgentGroupRun(channel.agentGroupId, event.text ?? "");
+ return { agentGroup: { runId: run.id, groupId: channel.agentGroupId } };
+ }
if (!channel.workflowId) return { workflow: null };
const source = await findActiveChannelSource(channel.workflowId, channel.id, channel.workflowBinding);
diff --git a/lib/infra/additional-doctor.ts b/lib/infra/additional-doctor.ts
index c43cab5a..90ca6d0f 100644
--- a/lib/infra/additional-doctor.ts
+++ b/lib/infra/additional-doctor.ts
@@ -135,7 +135,7 @@ export async function doctorAdditionalProvider(id: string, values: Record<string
}
case "telegram": {
if (!present(values.botToken)) return null;
- if (!/^\\d{5,16}:[A-Za-z0-9_-]{20,}$/.test(values.botToken)) throw new Error("Telegram bot token format is invalid");
+ if (!/^\d{5,16}:[A-Za-z0-9_-]{20,}$/.test(values.botToken)) throw new Error("Telegram bot token format is invalid");
const response = await checked("Telegram", "https://api.telegram.org/bot" + values.botToken + "/getMe", { accept: "application/json" });
const root = obj(response.body);
const result = obj(root.result);