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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(agent-group): multi-agent discussion groups over Hermes profiles
Abdurrahman Fakhrul9782e75d91e5
diff --git a/.env.example b/.env.exampleindex 25c75c76..5c010133 100644--- a/.env.example+++ b/.env.example@@ -231,6 +231,9 @@ OS_SESSION_SECRET=# OS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json # durable explicit local messages/tasks (0600)# OS_LOCAL_AGENT_STANDBY_STORE=~/.mso/private/local-agent-standby.json # durable workflow-bound standby/claim state (0600)# OS_ORGANIZATION_STORE=~/.mso/private/organization.json # owner-private org units/seats/reporting/agent bindings (0600)+# OS_AGENT_GROUP_STORE=~/.mso/private/agent-groups.json # owner-private multi-agent discussion groups and run transcripts (0600)+# Multi-agent groups run each member as a headless Hermes profile turn.+# HERMES_BIN=~/.local/bin/hermes # path to the hermes CLI used by Agent groups# OS_LOCAL_AGENT_LEASE_MS=60000 # receiver lease; CLI heartbeat is lighter than this expiry# OS_TOOL_FORGE_DIR=~/.mso/tool-forge # private inert Tool Forge candidate/evaluation records# OS_TOOL_FORGE_NODE_IMAGE=mso-forge-sandbox:node22-v1 # labelled cached Docker image used only for executable Forge fixturesdiff --git a/app/api/v1/agent-groups/route.ts b/app/api/v1/agent-groups/route.tsnew file mode 100644index 00000000..37d3ce39--- /dev/null+++ b/app/api/v1/agent-groups/route.ts@@ -0,0 +1,76 @@+import { NextRequest, NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { readSetupJson } from "@/lib/infra/setup-http";+import { rateLimited } from "@/lib/host/rate-limit";+import {+ AgentGroupError,+ agentGroupsSnapshot,+ createAgentGroup,+ deleteAgentGroup,+ getAgentGroup,+ startAgentGroupRun,+ stopAgentGroupRun,+ updateAgentGroup,+} from "@/lib/agent-group";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";+const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer" };++const failure = (error: unknown) => {+ const value = error instanceof AgentGroupError ? error : new AgentGroupError("agent_group_operation_failed", 400);+ return NextResponse.json({ error: value.code }, { status: value.status, headers });+};++async function owner() {+ const context = await getSessionContext();+ return context?.role === "owner" ? context : null;+}++export async function GET(req: NextRequest) {+ if (!(await owner())) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });+ try {+ const id = req.nextUrl.searchParams.get("id");+ return NextResponse.json(id ? await getAgentGroup(id) : await agentGroupsSnapshot(), { headers });+ } catch (error) {+ return failure(error);+ }+}++export async function POST(req: NextRequest) {+ const context = await owner();+ if (!context) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });+ try {+ const body = await readSetupJson(req, 64 * 1024);+ const action = typeof body.action === "string" ? body.action : "";+ if (rateLimited(`agent-groups:${action}:${context.session.device_id}`, action === "run" ? 30 : 60, 60_000)) {+ throw new AgentGroupError("rate_limited", 429);+ }+ if (action === "create") {+ if (!body.data || typeof body.data !== "object" || Array.isArray(body.data)) throw new AgentGroupError("invalid_group_data");+ return NextResponse.json((await createAgentGroup(body.data as Record<string, unknown>)).result, { headers });+ }+ if (action === "update") {+ if (typeof body.id !== "string" || !Number.isSafeInteger(body.expectedRevision) || !body.data || typeof body.data !== "object" || Array.isArray(body.data)) {+ throw new AgentGroupError("invalid_group_update");+ }+ return NextResponse.json((await updateAgentGroup(body.id, Number(body.expectedRevision), body.data as Record<string, unknown>)).result, { headers });+ }+ if (action === "delete") {+ if (typeof body.id !== "string" || !Number.isSafeInteger(body.expectedRevision)) throw new AgentGroupError("invalid_group_delete");+ return NextResponse.json((await deleteAgentGroup(body.id, Number(body.expectedRevision))).result, { headers });+ }+ if (action === "run") {+ if (typeof body.id !== "string" || typeof body.prompt !== "string") throw new AgentGroupError("invalid_group_run");+ const members = Array.isArray(body.members) ? body.members.filter((value): value is string => typeof value === "string") : undefined;+ return NextResponse.json(await startAgentGroupRun(body.id, body.prompt, members), { headers });+ }+ if (action === "stop") {+ if (typeof body.runId !== "string") throw new AgentGroupError("invalid_group_stop");+ return NextResponse.json(await stopAgentGroupRun(body.runId), { headers });+ }+ throw new AgentGroupError("unknown_group_action");+ } catch (error) {+ return failure(error);+ }+}diff --git a/bin/mso b/bin/msoindex 460ebedd..99115d3e 100755--- a/bin/mso+++ b/bin/mso@@ -53,6 +53,7 @@# workflow * Visual/private Workflow Graph v2 CRUD + run/status (workflow --help)# integrations Named credential users, connections, sources, setup and execution# channels * Telegram/Discord channels: list, create/save/delete, test, send+# agent-groups * Multi-agent discussion groups: list, show, create/save/delete, run, stop# provider * Infrastructure credentials: list | set | rm | doctor# providers * Alias for provider# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domaindiff --git a/bin/mso.test.ts b/bin/mso.test.tsindex 6bc25277..e94c5475 100644--- a/bin/mso.test.ts+++ b/bin/mso.test.ts@@ -16,6 +16,7 @@ const commandOwnerFiles = ["scripts/cli/flows.sh","scripts/cli/workflows.sh","scripts/cli/channels.sh",+ "scripts/cli/agent-groups.sh","scripts/cli/commands-state.sh","scripts/cli/organization.sh","scripts/cli/config-command.sh",diff --git a/docs/CLI.md b/docs/CLI.mdindex 1cedaafc..c5567c15 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -93,6 +93,7 @@ Commands:workflow * Visual/private Workflow Graph v2 CRUD + run/status (workflow --help)integrations Named credential users, connections, sources, setup and executionchannels * Telegram/Discord channels: list, create/save/delete, test, send+ agent-groups * Multi-agent discussion groups: list, show, create/save/delete, run, stopprovider * Infrastructure credentials: list | set | rm | doctorproviders * Alias for providergateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domaindiff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.mdindex d96dc9e4..84efbd73 100644--- a/docs/SLICE-CATALOG.md+++ b/docs/SLICE-CATALOG.md@@ -3,16 +3,17 @@> **Current reference.** Counts are checked against the directory tree by> `scripts/check-docs.mjs`; the directory remains the final authority.-<!-- slice-catalog: slices=30 appshell-features=10 -->+<!-- slice-catalog: slices=31 appshell-features=10 -->Every application is a vertical slice under `frontend/slices/`. Host-facing slices use theshared API/host seam rather than reaching arbitrary Node host APIs from client code.-## Slices (30)+## Slices (31)| Slug | Purpose ||---|---|| `agent-vault` | Separate private repository agent-progress snapshots in an Obsidian-compatible Markdown vault |+| `agent-group` | Multi-agent discussion groups: several Hermes profiles take turns on one topic and mirror replies into a Telegram group || `app-store` | App Store / app discovery surface || `appshell` | Generic desktop/mobile shell framework || `assistant` | Alfa assistant, agents/playbooks and tool activity |diff --git a/frontend/slices/agent-group/app.test.ts b/frontend/slices/agent-group/app.test.tsnew file mode 100644index 00000000..4eda0348--- /dev/null+++ b/frontend/slices/agent-group/app.test.ts@@ -0,0 +1,24 @@+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";+import { agentGroupApp } from "./index";++describe("Agent groups shell feature", () => {+ it("is a first-class app registered in the shell and App Store", () => {+ expect(agentGroupApp.id).toBe("agent-group");+ expect(agentGroupApp.noDock).not.toBe(true);+ expect(readFileSync("frontend/slices/os-shell/shell.manifest.ts", "utf8")).toContain('withSlug(withArtwork(agentGroupApp), "agent-groups")');+ expect(readFileSync("frontend/slices/app-store/lib/system-catalog.ts", "utf8")).toContain('id: "agent-group", title: "Agent groups", kind: "app"');+ });++ it("keeps bot secrets in Integrations and drives run/stop/turn rendering", () => {+ const app = readFileSync("frontend/slices/agent-group/app.tsx", "utf8");+ const editor = readFileSync("frontend/slices/agent-group/components/agent-group-editor.tsx", "utf8");+ const card = readFileSync("frontend/slices/agent-group/components/agent-group-card.tsx", "utf8");+ const api = readFileSync("frontend/slices/agent-group/lib/api.ts", "utf8");+ expect(app).toContain('data-slot="agent-group-feature"');+ expect(api).toContain("/api/v1/channels");+ expect(editor).not.toContain("botToken");+ expect(card).toContain('data-slot="agent-group-turn"');+ expect(card).toContain("stopAgentGroup");+ });+});diff --git a/frontend/slices/agent-group/app.tsx b/frontend/slices/agent-group/app.tsxnew file mode 100644index 00000000..57330f6a--- /dev/null+++ b/frontend/slices/agent-group/app.tsx@@ -0,0 +1,77 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { Plus, RefreshCw, Users } from "lucide-react";+import type { AppProps } from "@/features/appshell";+import { AppFrame, openWindow } from "@/features/appshell";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { AgentGroupCard } from "./components/agent-group-card";+import { AgentGroupEditor } from "./components/agent-group-editor";+import { loadAgentGroups } from "./lib/api";+import type { AgentGroupsSnapshot, AgentGroupView } from "./types";++const empty: AgentGroupsSnapshot = { groups: [], revision: 0 };++export default function AgentGroupApp(_: AppProps) {+ const [snapshot, setSnapshot] = useState<AgentGroupsSnapshot>(empty);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState("");+ const [editor, setEditor] = useState<AgentGroupView | "new" | null>(null);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ setSnapshot(await loadAgentGroups());+ setError("");+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Could not load agent groups.");+ } finally { setLoading(false); }+ }, []);++ useEffect(() => {+ const frame = requestAnimationFrame(() => void load());+ window.addEventListener("focus", load);+ return () => { cancelAnimationFrame(frame); window.removeEventListener("focus", load); };+ }, [load]);++ const toolbar = <div className="flex h-11 min-w-0 items-center gap-2 px-3">+ <div className="flex min-w-0 flex-1 items-center gap-2"><span className="text-sm font-semibold">Agent groups</span><Badge variant="outline">{snapshot.groups.length}</Badge></div>+ <Button size="icon" variant="ghost" aria-label="Refresh groups" onClick={() => void load()}><RefreshCw className="size-4"/></Button>+ <Button size="sm" onClick={() => setEditor("new")}><Plus className="mr-2 size-3"/>New group</Button>+ </div>;++ return <div data-slot="agent-group-feature" className="@container h-full min-h-0 min-w-0">+ <AppFrame safeArea={false} className="h-full min-w-0 bg-background" toolbar={toolbar} bodyClassName="overflow-hidden">+ <div className="h-full overflow-y-auto p-3 @min-[720px]:p-4">+ {error ? <div role="alert" className="mb-3 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{error}</div> : null}+ {snapshot.groups.length ? <div className="grid gap-3 @min-[900px]:grid-cols-2">+ {snapshot.groups.map((row) => <AgentGroupCard key={row.id} row={row} revision={snapshot.revision} onEdit={() => setEditor(row)} onReload={load}/>)}+ </div> : <Empty loading={loading} onAdd={() => setEditor("new")}/>}+ </div>+ </AppFrame>+ <AgentGroupEditor+ key={editor === "new" ? `new:${snapshot.revision}` : editor?.id ?? "closed"}+ open={editor !== null}+ onOpenChange={(open) => { if (!open) setEditor(null); }}+ row={editor && editor !== "new" ? editor : null}+ revision={snapshot.revision}+ onSaved={load}+ />+ </div>;+}++function Empty({ loading, onAdd }: { loading: boolean; onAdd: () => void }) {+ return <div className="grid min-h-[55vh] place-items-center">+ <div className="w-full max-w-xl rounded-xl border bg-card p-5">+ <div className="flex items-start gap-3"><div className="grid size-10 place-items-center rounded-lg border bg-muted/40"><Users className="size-5"/></div><div>+ <h2 className="text-base font-semibold">{loading ? "Loading agent groups…" : "Let your agents talk to each other"}</h2>+ <p className="mt-1 text-sm text-muted-foreground">Group several Hermes profiles into one discussion. Each agent keeps its own persona and memory, replies in turn, and can mirror its voice into a Telegram group.</p>+ </div></div>+ {!loading ? <div className="mt-4 flex flex-wrap gap-2">+ <Button onClick={onAdd}><Plus className="mr-2 size-3"/>New group</Button>+ <Button variant="outline" onClick={() => openWindow("channels", "Channels")}>Open Channels</Button>+ </div> : null}+ </div>+ </div>;+}diff --git a/frontend/slices/agent-group/components/agent-group-card.tsx b/frontend/slices/agent-group/components/agent-group-card.tsxnew file mode 100644index 00000000..17258737--- /dev/null+++ b/frontend/slices/agent-group/components/agent-group-card.tsx@@ -0,0 +1,125 @@+"use client";++import { useEffect, useState } from "react";+import { Pencil, Play, Square, Trash2, Users } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Textarea } from "@/components/ui/textarea";+import { agentGroupAction, loadAgentGroup, runAgentGroup, stopAgentGroup } from "../lib/api";+import type { AgentGroupRun, AgentGroupView } from "../types";++const stateTone = (state: AgentGroupRun["state"]) =>+ state === "completed" ? "text-muted-foreground" : state === "running" ? "text-primary" : "text-destructive";++export function AgentGroupCard({+ row,+ revision,+ onEdit,+ onReload,+}: {+ row: AgentGroupView;+ revision: number;+ onEdit: () => void;+ onReload: () => Promise<void>;+}) {+ const [topic, setTopic] = useState("");+ const [busy, setBusy] = useState("");+ const [message, setMessage] = useState("");+ const [live, setLive] = useState<AgentGroupRun | null>(null);+ const run0 = row.runs[0] ?? null;+ const latest = live && (!run0 || live.updatedAt >= run0.updatedAt) ? live : run0;++ useEffect(() => {+ if (latest?.state !== "running") return;+ let cancelled = false;+ const timer = setInterval(async () => {+ try {+ const next = await loadAgentGroup(row.id);+ if (!cancelled) setLive(next.runs[0] ?? null);+ } catch { /* keep polling */ }+ }, 2500);+ return () => { cancelled = true; clearInterval(timer); };+ }, [latest?.state, latest?.id, row.id]);++ const run = async (name: string, body: Record<string, unknown>, reload = true) => {+ setBusy(name); setMessage("");+ try {+ await agentGroupAction(body);+ if (reload) await onReload();+ if (name === "stop") setMessage("Discussion stopped.");+ } catch (cause) {+ setMessage(cause instanceof Error ? cause.message : "Action failed.");+ } finally { setBusy(""); }+ };++ const start = async () => {+ setBusy("run"); setMessage("");+ try {+ const started = await runAgentGroup(row.id, topic);+ setLive(started);+ setTopic("");+ await onReload();+ } catch (cause) {+ setMessage(cause instanceof Error ? cause.message : "Could not start the discussion.");+ } finally { setBusy(""); }+ };++ const stop = async () => {+ if (!latest) return;+ setBusy("stop");+ try { setLive(await stopAgentGroup(latest.id)); await onReload(); }+ catch (cause) { setMessage(cause instanceof Error ? cause.message : "Could not stop."); }+ finally { setBusy(""); }+ };++ return <article className="flex min-w-0 flex-col rounded-xl border bg-card" data-slot="agent-group-card">+ <header className="flex items-start gap-3 border-b p-4">+ <div className="grid size-9 shrink-0 place-items-center rounded-lg border bg-muted/40"><Users className="size-4"/></div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="truncate text-sm font-semibold">{row.name}</h3>+ <Badge variant="outline">{row.members.length} agents</Badge>+ <Badge variant="outline">{row.maxRounds} round{row.maxRounds > 1 ? "s" : ""}</Badge>+ {!row.enabled ? <Badge variant="outline" className="text-destructive">Disabled</Badge> : null}+ </div>+ <div className="mt-1.5 flex flex-wrap gap-1.5">+ {row.members.map((member) => <span key={member.id} className="rounded-md border bg-muted/30 px-1.5 py-0.5 text-[10px]">+ {member.name} · {member.profile}{member.telegram ? " · TG" : ""}+ </span>)}+ </div>+ </div>+ <Button size="icon" variant="ghost" aria-label="Edit group" onClick={onEdit}><Pencil className="size-3"/></Button>+ <Button size="icon" variant="ghost" aria-label="Delete group" disabled={Boolean(busy)} onClick={() => {+ if (window.confirm(`Delete ${row.name}?`)) void run("delete", { action: "delete", id: row.id, expectedRevision: revision });+ }}><Trash2 className="size-3"/></Button>+ </header>++ <div className="space-y-3 p-4">+ <Textarea value={topic} rows={2} maxLength={4000} placeholder="Discussion topic — e.g. Should we ship the new onboarding?" onChange={(event) => setTopic(event.target.value)}/>+ <div className="flex flex-wrap items-center gap-2">+ <Button size="sm" disabled={Boolean(busy) || !topic.trim() || !row.enabled} onClick={() => void start()}>+ <Play className="mr-2 size-3"/>{busy === "run" ? "Starting…" : "Start discussion"}+ </Button>+ {latest?.state === "running" ? <Button size="sm" variant="outline" disabled={Boolean(busy)} onClick={() => void stop()}>+ <Square className="mr-2 size-3"/>Stop+ </Button> : null}+ {latest ? <span className={`text-xs ${stateTone(latest.state)}`}>{latest.state} · {latest.turns.length} turn{latest.turns.length === 1 ? "" : "s"}</span> : null}+ </div>++ {latest ? <div className="max-h-80 space-y-2 overflow-y-auto rounded-lg border bg-muted/20 p-3">+ <div className="text-[10px] uppercase tracking-wide text-muted-foreground">Topic: {latest.prompt}</div>+ {latest.turns.length ? latest.turns.map((turn, index) => <div key={`${turn.memberId}:${turn.round}:${index}`} className="text-xs" data-slot="agent-group-turn">+ <div className="flex items-center gap-2">+ <span className="font-semibold">{turn.name}</span>+ <span className="text-[10px] text-muted-foreground">round {turn.round}</span>+ </div>+ <p className={turn.error ? "text-destructive" : "text-muted-foreground"}>+ {turn.error ? `No reply: ${turn.error}` : turn.text}+ </p>+ </div>) : <p className="text-xs text-muted-foreground">Waiting for the first reply…</p>}+ </div> : null}++ {message ? <p className="text-xs text-muted-foreground">{message}</p> : null}+ </div>+ </article>;+}diff --git a/frontend/slices/agent-group/components/agent-group-editor.tsx b/frontend/slices/agent-group/components/agent-group-editor.tsxnew file mode 100644index 00000000..0d728921--- /dev/null+++ b/frontend/slices/agent-group/components/agent-group-editor.tsx@@ -0,0 +1,137 @@+"use client";++import { useEffect, useState } from "react";+import { Plus, Trash2, Users } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { FormDrawer } from "@/features/appshell";+import { agentGroupAction, loadTelegramCredentials, type TelegramCredentialOption } from "../lib/api";+import type { AgentGroupMember, AgentGroupView } from "../types";++const selectClass = "h-9 w-full rounded-md border bg-background px-2 text-sm";+const credValue = (user: string, connection: string) => `${user}::${connection}`;++type DraftMember = { name: string; profile: string; credential: string; target: string };+const emptyMember = (): DraftMember => ({ name: "", profile: "", credential: "", target: "" });++export function AgentGroupEditor({+ open,+ onOpenChange,+ row,+ revision,+ onSaved,+}: {+ open: boolean;+ onOpenChange: (value: boolean) => void;+ row: AgentGroupView | null;+ revision: number;+ onSaved: () => Promise<void>;+}) {+ const [name, setName] = useState(row?.name ?? "");+ const [maxRounds, setMaxRounds] = useState(row?.maxRounds ?? 1);+ const [enabled, setEnabled] = useState(row?.enabled ?? true);+ const [members, setMembers] = useState<DraftMember[]>(+ row?.members.length+ ? row.members.map((member) => ({+ name: member.name,+ profile: member.profile,+ credential: member.telegram ? credValue(member.telegram.user, member.telegram.connection) : "",+ target: member.telegram?.target ?? "",+ }))+ : [emptyMember()],+ );+ const [credentials, setCredentials] = useState<TelegramCredentialOption[]>([]);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ useEffect(() => {+ if (!open) return;+ loadTelegramCredentials().then(setCredentials).catch(() => setCredentials([]));+ }, [open]);++ const patch = (index: number, next: Partial<DraftMember>) =>+ setMembers((rows) => rows.map((rowItem, position) => (position === index ? { ...rowItem, ...next } : rowItem)));++ const save = async () => {+ const parsed: AgentGroupMember[] = [];+ for (const member of members) {+ if (!member.name.trim() || !member.profile.trim()) { setError("Every agent needs a name and a Hermes profile."); return; }+ const payload: AgentGroupMember = { id: "", name: member.name.trim(), profile: member.profile.trim() };+ if (member.credential) {+ const [user, connection] = member.credential.split("::");+ if (!user || !connection || !member.target.trim()) { setError("A Telegram link needs a connection and a target."); return; }+ payload.telegram = { user, connection, target: member.target.trim() };+ }+ parsed.push(payload);+ }+ setBusy(true); setError("");+ try {+ const data = { name, maxRounds, enabled, members: parsed.map((member, index) => ({ ...member, id: member.id || `m${index + 1}` })) };+ await agentGroupAction(row ? { action: "update", id: row.id, expectedRevision: revision, data } : { action: "create", data });+ await onSaved();+ onOpenChange(false);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Could not save the group.");+ } finally { setBusy(false); }+ };++ return <FormDrawer open={open} onOpenChange={onOpenChange} size="lg">+ <FormDrawer.Header>+ <FormDrawer.Title>{row ? "Edit agent group" : "New agent group"}</FormDrawer.Title>+ <FormDrawer.Description>+ Each agent runs as its own Hermes profile. Replies are mirrored to the group Telegram channel when a connection is set.+ </FormDrawer.Description>+ </FormDrawer.Header>+ <FormDrawer.Body className="space-y-4">+ <div className="grid gap-3 sm:grid-cols-2">+ <label className="block space-y-1.5"><span className="text-xs font-medium">Group name</span>+ <Input value={name} maxLength={120} placeholder="Council" onChange={(event) => setName(event.target.value)}/></label>+ <label className="block space-y-1.5"><span className="text-xs font-medium">Rounds</span>+ <select className={selectClass} value={maxRounds} onChange={(event) => setMaxRounds(Number(event.target.value))}>+ <option value={1}>1 — opening statements</option>+ <option value={2}>2 — open + respond</option>+ <option value={3}>3 — open + respond + close</option>+ </select></label>+ </div>++ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium">Agents</span>+ <Button size="sm" variant="outline" onClick={() => setMembers((rows) => [...rows, emptyMember()])}><Plus className="mr-2 size-3"/>Add agent</Button>+ </div>+ {members.map((member, index) => <div key={index} className="space-y-2 rounded-lg border p-3">+ <div className="flex items-center gap-2">+ <Users className="size-3.5 text-muted-foreground"/>+ <Input value={member.name} maxLength={60} placeholder="Display name" onChange={(event) => patch(index, { name: event.target.value })}/>+ <Input value={member.profile} maxLength={64} placeholder="Hermes profile (e.g. dita)" onChange={(event) => patch(index, { profile: event.target.value })}/>+ {members.length > 1 ? <Button size="icon" variant="ghost" aria-label="Remove agent" onClick={() => setMembers((rows) => rows.filter((_, position) => position !== index))}><Trash2 className="size-3"/></Button> : null}+ </div>+ <div className="grid gap-2 sm:grid-cols-2">+ <select className={selectClass} value={member.credential} onChange={(event) => patch(index, { credential: event.target.value })}>+ <option value="">No Telegram link</option>+ {credentials.map((item) => <option key={`${item.user}:${item.id}`} value={credValue(item.user, item.id)}>+ {item.userLabel} / {item.label} · {item.state}+ </option>)}+ </select>+ <Input value={member.target} placeholder="Telegram chat ID (-100…)" disabled={!member.credential} onChange={(event) => patch(index, { target: event.target.value })}/>+ </div>+ </div>)}+ </div>++ <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 starting discussions from this app.</span></span>+ <Switch checked={enabled} onCheckedChange={setEnabled}/>+ </label>++ <div className="rounded-lg bg-muted/40 p-3 text-xs text-muted-foreground">+ Telegram bot tokens stay in Integrations. Pick one or more Telegram connections — each agent posts as its own bot.+ </div>+ {error ? <p className="text-xs text-destructive">{error}</p> : null}+ </FormDrawer.Body>+ <FormDrawer.Footer>+ <Button variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>+ <Button disabled={busy || !name.trim()} onClick={() => void save()}>{busy ? "Saving…" : "Save group"}</Button>+ </FormDrawer.Footer>+ </FormDrawer>;+}diff --git a/frontend/slices/agent-group/index.ts b/frontend/slices/agent-group/index.tsnew file mode 100644index 00000000..7d11b01b--- /dev/null+++ b/frontend/slices/agent-group/index.ts@@ -0,0 +1,11 @@+import { Users } from "lucide-react";+import type { AppDescriptor } from "@/features/appshell";++export const agentGroupApp: AppDescriptor = {+ id: "agent-group",+ title: "Agent groups",+ icon: Users,+ gradient: "var(--primary)",+ load: () => import("./app"),+ defaultSize: { w: 1120, h: 760 },+};diff --git a/frontend/slices/agent-group/lib/api.ts b/frontend/slices/agent-group/lib/api.tsnew file mode 100644index 00000000..49305478--- /dev/null+++ b/frontend/slices/agent-group/lib/api.ts@@ -0,0 +1,31 @@+import type { AgentGroupRun, AgentGroupView, AgentGroupsSnapshot } from "../types";++async function json<T>(input: RequestInfo, init?: RequestInit): Promise<T> {+ const response = await fetch(input, {+ ...init,+ cache: "no-store",+ headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },+ });+ const body = await response.json().catch(() => ({}));+ if (!response.ok) throw new Error(typeof body.error === "string" ? body.error : `request failed (${response.status})`);+ return body as T;+}++export const loadAgentGroups = () => json<AgentGroupsSnapshot>("/api/v1/agent-groups");+export const loadAgentGroup = (id: string) => json<AgentGroupView>(`/api/v1/agent-groups?id=${encodeURIComponent(id)}`);+export const agentGroupAction = <T = unknown>(body: Record<string, unknown>) =>+ json<T>("/api/v1/agent-groups", { method: "POST", body: JSON.stringify(body) });++export const runAgentGroup = (id: string, prompt: string, members?: string[]) =>+ agentGroupAction<AgentGroupRun>({ action: "run", id, prompt, ...(members ? { members } : {}) });+export const stopAgentGroup = (runId: string) => agentGroupAction<AgentGroupRun>({ action: "stop", runId });++export type TelegramCredentialOption = { user: string; userLabel: string; id: string; label: string; state: string };++// Reuses the Channels snapshot the Integrations/Channels apps already expose:+// agent-group mirrors each member's reply through the same Telegram connections.+export async function loadTelegramCredentials() {+ const snapshot = await json<{ credentials: TelegramCredentialOption[] }>("/api/v1/channels");+ return snapshot.credentials.filter((item) => item.user && item.id);+}+diff --git a/frontend/slices/agent-group/types.ts b/frontend/slices/agent-group/types.tsnew file mode 100644index 00000000..f004bc13--- /dev/null+++ b/frontend/slices/agent-group/types.ts@@ -0,0 +1,45 @@+export type AgentGroupMemberTelegram = { user: string; connection: string; target: string };++export type AgentGroupMember = {+ id: string;+ name: string;+ profile: string;+ telegram?: AgentGroupMemberTelegram;+};++export type AgentGroupTurn = {+ round: number;+ memberId: string;+ name: string;+ profile: string;+ text: string;+ at: string;+ error?: string;+};++export type AgentGroupRun = {+ id: string;+ groupId: string;+ prompt: string;+ turns: AgentGroupTurn[];+ state: "running" | "completed" | "failed" | "stopped";+ error?: string;+ startedAt: string;+ updatedAt: string;+};++export type AgentGroupView = {+ id: string;+ name: string;+ members: AgentGroupMember[];+ maxRounds: number;+ enabled: boolean;+ createdAt: string;+ updatedAt: string;+ runs: AgentGroupRun[];+};++export type AgentGroupsSnapshot = {+ groups: AgentGroupView[];+ revision: number;+};diff --git a/frontend/slices/app-store/lib/system-catalog.ts b/frontend/slices/app-store/lib/system-catalog.tsindex ddec7daa..794eee63 100644--- a/frontend/slices/app-store/lib/system-catalog.ts+++ b/frontend/slices/app-store/lib/system-catalog.ts@@ -20,6 +20,7 @@ import {ServerCog,Plug,MessageSquareMore,+ Users,type LucideIcon,} from "lucide-react";@@ -46,6 +47,7 @@ export const SYSTEM_CATALOG: SystemEntry[] = [// ── Built-in apps ─────────────────────────────────────────────────────────{ id: "integrations", title: "Integrations", kind: "app", icon: Plug, gradient: "var(--primary)", desc: "Manage native service accounts, connections, and private setup." },{ id: "channels", title: "Channels", kind: "app", icon: MessageSquareMore, gradient: "var(--primary)", desc: "Connect Telegram and Discord to MSO Workflows and outbound messaging." },+ { id: "agent-group", title: "Agent groups", kind: "app", icon: Users, gradient: "var(--primary)", desc: "Let several Hermes profiles discuss a topic in turn and mirror into a Telegram group." },{ id: "files-manager", title: "Files", kind: "app", icon: Folder, gradient: "linear-gradient(160deg,#3aa0ff,#1f6dff)", desc: "Browse, upload, and manage host files." },{ id: "browser", title: "Browser", kind: "app", icon: Globe, gradient: "linear-gradient(160deg,#22b1ff,#1666e0)", desc: "Tabbed web viewer — pages render in a sandboxed embedded frame." },{ id: "code-editor", title: "Code", kind: "app", icon: Code, gradient: "linear-gradient(160deg,#7a5cff,#4f2fd6)", desc: "Edit host files in a tabbed code editor." },diff --git a/frontend/slices/os-shell/shell.manifest.ts b/frontend/slices/os-shell/shell.manifest.tsindex 0a671af6..087c056a 100644--- a/frontend/slices/os-shell/shell.manifest.ts+++ b/frontend/slices/os-shell/shell.manifest.ts@@ -22,6 +22,7 @@ import { quicklinksApp } from "@/features/quicklinks";import { docsApp } from "@/features/docs";import { integrationsApp } from "@/features/integrations";import { channelsApp } from "@/features/channels";+import { agentGroupApp } from "@/features/agent-group";import { workflowsApp } from "@/features/workflows";import { n8nApp } from "@/features/n8n";import { organizationApp } from "@/features/organization";@@ -86,6 +87,7 @@ export const BUILTIN_APPS: AppDescriptor[] = [withSlug(withArtwork(docsApp), "docs"),pin(withSlug(withArtwork(osSettingsApp), "settings")),withSlug(agentVaultApp, "agent-vault"),+ withSlug(withArtwork(agentGroupApp), "agent-groups"),withSlug(withArtwork(quicklinksApp), "links"),withSlug(withArtwork(createAppApp), "create"),];diff --git a/lib/agent-group/errors.ts b/lib/agent-group/errors.tsnew file mode 100644index 00000000..546694a2--- /dev/null+++ b/lib/agent-group/errors.ts@@ -0,0 +1,12 @@+export class AgentGroupError extends Error {+ constructor(+ public readonly code: string,+ public readonly status = 400,+ ) {+ super(code);+ }+}++export function agentGroupError(error: unknown): AgentGroupError {+ return error instanceof AgentGroupError ? error : new AgentGroupError("agent_group_operation_failed", 400);+}diff --git a/lib/agent-group/hermes-runner.ts b/lib/agent-group/hermes-runner.tsnew file mode 100644index 00000000..7dd54773--- /dev/null+++ b/lib/agent-group/hermes-runner.ts@@ -0,0 +1,104 @@+import { spawn } from "node:child_process";+import path from "node:path";+import { AgentGroupError } from "./errors";++const TIMEOUT_MS = 90_000;+const MAX_OUTPUT = 64 * 1024;+const PROFILE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;+const SESSION = /^[A-Za-z0-9_-]{1,80}$/;++export type HermesTurnInput = {+ profile: string;+ prompt: string;+ system?: string;+ resumeSessionId?: string;+ timeoutMs?: number;+ signal?: AbortSignal;+};++export type HermesTurnResult = {+ text: string;+ sessionId?: string;+};++// Hermes writes a status banner and session id to stderr; stdout holds the+// model reply plus occasional informational lines. Keep only reply lines.+function cleanReply(raw: string): string {+ return raw+ .split("\n")+ .filter((line) => !/^\s*(?:⚠|warning:|session_id:|\[hermes\]|info:|debug:)/i.test(line))+ .join("\n")+ .trim();+}++export function buildHermesQuery(prompt: string, system?: string): string {+ return system ? `${system}\n\n---\n\n${prompt}` : prompt;+}++// Runs one headless Hermes turn for a single profile. Never uses a shell, so+// arbitrary prompt text is passed verbatim (no quoting or injection risk).+export async function runHermesTurn(input: HermesTurnInput): Promise<HermesTurnResult> {+ const profile = input.profile.trim();+ if (!PROFILE.test(profile)) throw new AgentGroupError("invalid_group_profile");+ if (!input.prompt.trim()) throw new AgentGroupError("invalid_group_prompt");+ if (input.prompt.length > 4000) throw new AgentGroupError("invalid_group_prompt");+ let resumeSessionId: string | undefined;+ if (input.resumeSessionId !== undefined) {+ if (!SESSION.test(input.resumeSessionId)) throw new AgentGroupError("invalid_group_session");+ resumeSessionId = input.resumeSessionId;+ }++ const binary = process.env.HERMES_BIN ?? path.join(process.env.HOME ?? "/home", ".local", "bin", "hermes");+ const args = ["chat", "-p", profile, "-Q", "-q", buildHermesQuery(input.prompt, input.system)];+ if (resumeSessionId) args.push("-r", resumeSessionId);++ const captured = await new Promise<{ out: string; err: string }>((resolve, reject) => {+ const child = spawn(binary, args, {+ env: process.env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ let out = "";+ let err = "";+ let settled = false;+ const finish = (fn: () => void) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ input.signal?.removeEventListener("abort", onAbort);+ fn();+ };+ const onAbort = () => {+ child.kill("SIGKILL");+ finish(() => reject(new AgentGroupError("agent_group_stopped", 409)));+ };+ const timer = setTimeout(() => {+ child.kill("SIGKILL");+ finish(() => reject(new AgentGroupError("agent_group_timeout", 504)));+ }, input.timeoutMs ?? TIMEOUT_MS);+ input.signal?.addEventListener("abort", onAbort, { once: true });++ child.stdout.setEncoding("utf8");+ child.stdout.on("data", (chunk: string) => {+ out += chunk;+ if (out.length > MAX_OUTPUT) {+ child.kill("SIGKILL");+ finish(() => reject(new AgentGroupError("agent_group_output_too_large", 413)));+ }+ });+ child.stderr.setEncoding("utf8");+ child.stderr.on("data", (chunk: string) => {+ err += chunk;+ if (err.length > MAX_OUTPUT) err = err.slice(-MAX_OUTPUT);+ });+ child.on("error", () => finish(() => reject(new AgentGroupError("agent_group_spawn_failed", 500))));+ child.on("close", (code) => {+ finish(() => {+ if (code === 0) resolve({ out, err });+ else reject(new AgentGroupError(`agent_group_exit_${code ?? "signal"}`, 502));+ });+ });+ });++ const sessionId = `${captured.out}\n${captured.err}`.match(/session_id:\s*([A-Za-z0-9_-]+)/)?.[1] ?? undefined;+ return { text: cleanReply(captured.out), ...(sessionId ? { sessionId } : {}) };+}diff --git a/lib/agent-group/index.ts b/lib/agent-group/index.tsnew file mode 100644index 00000000..2bb68fe4--- /dev/null+++ b/lib/agent-group/index.ts@@ -0,0 +1,5 @@+export * from "./types";+export * from "./errors";+export * from "./schema";+export { createAgentGroup, updateAgentGroup, deleteAgentGroup, listAgentGroups, readAgentGroupState } from "./store";+export { agentGroupsSnapshot, getAgentGroup, startAgentGroupRun, stopAgentGroupRun } from "./service";diff --git a/lib/agent-group/schema.ts b/lib/agent-group/schema.tsnew file mode 100644index 00000000..a6dcb3f9--- /dev/null+++ b/lib/agent-group/schema.ts@@ -0,0 +1,70 @@+import { AgentGroupError } from "./errors";+import type { AgentGroupMember, AgentGroupMemberTelegram } from "./types";++const PROFILE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;+const TELEGRAM_TARGET = /^(?:-?\d{1,20}|@[A-Za-z][A-Za-z0-9_]{4,31})$/;++const clean = (value: unknown, label: string, max = 120): string => {+ if (typeof value !== "string" || !value.trim() || value.length > max || /[\x00-\x1f\x7f]/.test(value)) {+ throw new AgentGroupError(`invalid_group_${label}`);+ }+ return value.trim();+};++function parseTelegram(raw: unknown): AgentGroupMemberTelegram | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "object" || Array.isArray(raw)) throw new AgentGroupError("invalid_group_telegram");+ const row = raw as Record<string, unknown>;+ const target = clean(row.target, "telegram_target", 128);+ if (!TELEGRAM_TARGET.test(target)) throw new AgentGroupError("invalid_group_telegram_target");+ return { user: clean(row.user, "telegram_user"), connection: clean(row.connection, "telegram_connection"), target };+}++function parseMember(raw: unknown, index: number): AgentGroupMember {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new AgentGroupError("invalid_group_member");+ const row = raw as Record<string, unknown>;+ const profile = clean(row.profile, "profile", 64);+ if (!PROFILE.test(profile)) throw new AgentGroupError("invalid_group_profile");+ const telegram = parseTelegram(row.telegram);+ return {+ id: typeof row.id === "string" && row.id ? row.id : `m${index + 1}`,+ name: clean(row.name, "member_name", 60),+ profile,+ ...(telegram ? { telegram } : {}),+ };+}++export type AgentGroupPatch = {+ name: string;+ members: AgentGroupMember[];+ maxRounds: number;+ enabled: boolean;+};++export function parseAgentGroupPatch(raw: Record<string, unknown>, previous?: AgentGroupPatch): AgentGroupPatch {+ const nameRaw = raw.name === undefined ? previous?.name : raw.name;+ const name = clean(nameRaw, "name");++ const membersRaw = raw.members === undefined ? previous?.members : raw.members;+ if (!Array.isArray(membersRaw) || membersRaw.length < 1 || membersRaw.length > 12) {+ throw new AgentGroupError("invalid_group_members");+ }+ const members = membersRaw.map((item, index) => parseMember(item, index));+ if (new Set(members.map((member) => member.id)).size !== members.length) {+ throw new AgentGroupError("duplicate_group_member");+ }+ if (new Set(members.map((member) => member.profile)).size !== members.length) {+ throw new AgentGroupError("duplicate_group_profile");+ }++ const roundsRaw = raw.maxRounds === undefined ? previous?.maxRounds : raw.maxRounds;+ const maxRounds = roundsRaw === undefined ? 1 : roundsRaw;+ if (typeof maxRounds !== "number" || !Number.isSafeInteger(maxRounds) || maxRounds < 1 || maxRounds > 3) {+ throw new AgentGroupError("invalid_group_max_rounds");+ }++ const enabledRaw = raw.enabled === undefined ? previous?.enabled ?? true : raw.enabled;+ if (typeof enabledRaw !== "boolean") throw new AgentGroupError("invalid_group_enabled");++ return { name, members, maxRounds, enabled: enabledRaw };+}diff --git a/lib/agent-group/service.ts b/lib/agent-group/service.tsnew file mode 100644index 00000000..abbd4202--- /dev/null+++ b/lib/agent-group/service.ts@@ -0,0 +1,96 @@+import { directConnectionValues } from "@/lib/infra/connection-service";+import { sendTelegramText } from "@/lib/channels/providers/telegram";+import { AgentGroupError } from "./errors";+import { runHermesTurn } from "./hermes-runner";+import { appendTurn, createRun, finishRun, listRuns, readAgentGroupState, readRun } from "./store";+import type { AgentGroupMember, AgentGroupRecord, AgentGroupRun, AgentGroupView } from "./types";++const active = new Map<string, AbortController>();++const MODERATOR =+ "You are one specialist in a live multi-agent discussion with other specialists. Keep each reply short (2-4 sentences), speak in your own role, build on or challenge what others said, and move the discussion forward. Do not use tools unless essential.";++const openingPrompt = (topic: string) => `${MODERATOR}\n\nDiscussion topic: ${topic}\n\nGive your opening position.`;+const continuingPrompt = (topic: string, transcript: string) =>+ `${MODERATOR}\n\nDiscussion topic: ${topic}\n\nDiscussion so far:\n${transcript}\n\nContinue the discussion now: respond to the others and add your next points.`;+const transcript = (turns: AgentGroupRun["turns"]) =>+ turns.map((turn) => `${turn.name}: ${turn.text || `(no reply: ${turn.error ?? "error"})`}`).join("\n").slice(-8000);++async function mirrorToTelegram(member: AgentGroupMember, text: string) {+ if (!member.telegram || !text.trim()) return;+ const values = await directConnectionValues("telegram", { user: member.telegram.user, connection: member.telegram.connection });+ if (!values.botToken) return;+ await sendTelegramText(values, member.telegram.target, `${member.name}:\n${text}`.slice(0, 4096));+}++async function execute(group: AgentGroupRecord, runId: string, prompt: string, signal: AbortSignal) {+ try {+ for (let round = 1; round <= group.maxRounds; round += 1) {+ for (const member of group.members) {+ if (signal.aborted) throw new AgentGroupError("agent_group_stopped", 409);+ const current = await readRun(runId);+ const query = round === 1 ? openingPrompt(prompt) : continuingPrompt(prompt, transcript(current.turns));+ try {+ const result = await runHermesTurn({ profile: member.profile, prompt: query, signal });+ const { result: updated } = await appendTurn(+ runId,+ { round, memberId: member.id, name: member.name, profile: member.profile, text: result.text },+ "running",+ );+ const latest = updated.turns.at(-1);+ if (latest && latest.error === undefined && result.text.trim()) await mirrorToTelegram(member, result.text).catch(() => undefined);+ } catch (error) {+ if (error instanceof AgentGroupError && error.code === "agent_group_stopped") throw error;+ await appendTurn(+ runId,+ { round, memberId: member.id, name: member.name, profile: member.profile, text: "", error: error instanceof AgentGroupError ? error.code : "agent_group_turn_failed" },+ "running",+ );+ }+ }+ }+ await finishRun(runId, "completed");+ } catch (error) {+ const code = error instanceof AgentGroupError ? error.code : "agent_group_run_failed";+ await finishRun(runId, code === "agent_group_stopped" ? "stopped" : "failed", code).catch(() => undefined);+ } finally {+ active.delete(runId);+ }+}++export async function agentGroupsSnapshot(): Promise<{ groups: AgentGroupView[]; revision: number }> {+ const state = await readAgentGroupState();+ const groups: AgentGroupView[] = [];+ for (const group of state.groups) groups.push({ ...group, runs: await listRuns(group.id) });+ return { groups, revision: state.revision };+}++export async function getAgentGroup(groupId: string): Promise<AgentGroupView> {+ const state = await readAgentGroupState();+ const group = state.groups.find((item) => item.id === groupId);+ if (!group) throw new AgentGroupError("agent_group_not_found", 404);+ return { ...group, runs: await listRuns(groupId) };+}++export async function startAgentGroupRun(groupId: string, prompt: string, members?: string[]) {+ const { groups } = await readAgentGroupState();+ const group = groups.find((item) => item.id === groupId);+ if (!group) throw new AgentGroupError("agent_group_not_found", 404);+ if (!group.enabled) throw new AgentGroupError("agent_group_disabled", 409);+ const text = prompt.trim();+ if (!text || text.length > 4000) throw new AgentGroupError("invalid_group_prompt");+ const selected = members && members.length ? group.members.filter((member) => members.includes(member.id)) : group.members;+ if (!selected.length) throw new AgentGroupError("invalid_group_members");+ const { result: run } = await createRun(groupId, text);+ const controller = new AbortController();+ active.set(run.id, controller);+ void execute({ ...group, members: selected }, run.id, text, controller.signal);+ return run;+}++export async function stopAgentGroupRun(runId: string) {+ active.get(runId)?.abort(new AgentGroupError("agent_group_stopped", 409));+ active.delete(runId);+ const { result } = await finishRun(runId, "stopped", "agent_group_stopped");+ return result;+}diff --git a/lib/agent-group/store.test.ts b/lib/agent-group/store.test.tsnew file mode 100644index 00000000..689f2cad--- /dev/null+++ b/lib/agent-group/store.test.ts@@ -0,0 +1,78 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { AgentGroupError } from "./errors";+import { parseAgentGroupPatch } from "./schema";+import { appendTurn, createAgentGroup, createRun, finishRun, listAgentGroups, readAgentGroupState, readRun, updateAgentGroup } from "./store";++let dir = "";+beforeEach(async () => {+ dir = await mkdtemp(path.join(os.tmpdir(), "mso-agent-group-"));+ process.env.OS_AGENT_GROUP_STORE = path.join(dir, "agent-groups.json");+});+afterEach(async () => {+ delete process.env.OS_AGENT_GROUP_STORE;+ await rm(dir, { recursive: true, force: true });+});++const group = () => ({+ name: "Council",+ members: [+ { name: "Lara", profile: "default" },+ { name: "Dita", profile: "dita" },+ ],+ maxRounds: 2,+});++describe("agent-group schema", () => {+ it("rejects duplicate profiles, bad profile names, and out-of-range rounds", () => {+ expect(() => parseAgentGroupPatch({ ...group(), members: [{ name: "A", profile: "x" }, { name: "B", profile: "x" }] })).toThrow(AgentGroupError);+ expect(() => parseAgentGroupPatch({ ...group(), members: [{ name: "A", profile: "bad profile" }] })).toThrow(AgentGroupError);+ expect(() => parseAgentGroupPatch({ ...group(), maxRounds: 4 })).toThrow(AgentGroupError);+ });++ it("parses a valid member list with optional telegram routing", () => {+ const parsed = parseAgentGroupPatch({+ name: "Council",+ members: [{ name: "Dita", profile: "dita", telegram: { user: "owner", connection: "telegram-dita", target: "-100123" } }],+ });+ expect(parsed.members).toHaveLength(1);+ expect(parsed.members[0]!.telegram?.target).toBe("-100123");+ expect(parsed.maxRounds).toBe(1);+ });+});++describe("agent-group store", () => {+ it("creates, lists, updates and bumps revision", async () => {+ const created = await createAgentGroup(group());+ expect(created.state.revision).toBe(1);+ expect(created.result.members).toHaveLength(2);++ const updated = await updateAgentGroup(created.result.id, 1, { ...group(), name: "Council 2" });+ expect(updated.state.revision).toBe(2);+ expect(updated.result.name).toBe("Council 2");++ const state = await readAgentGroupState();+ expect(state.groups).toHaveLength(1);+ expect((await listAgentGroups())[0]!.name).toBe("Council 2");+ });++ it("rejects a stale update revision", async () => {+ const created = await createAgentGroup(group());+ await expect(updateAgentGroup(created.result.id, 999, { ...group(), name: "x" })).rejects.toThrow(AgentGroupError);+ });++ it("records a run transcript and terminal state", async () => {+ const created = await createAgentGroup(group());+ const { result: run } = await createRun(created.result.id, "Should we ship?");+ expect(run.state).toBe("running");++ const appended = await appendTurn(run.id, { round: 1, memberId: "m1", name: "Lara", profile: "default", text: "Yes." }, "running");+ expect(appended.state.runs[0]!.turns).toHaveLength(1);++ const finished = await finishRun(run.id, "completed");+ expect(finished.state.runs[0]!.state).toBe("completed");+ expect((await readRun(run.id)).turns[0]!.text).toBe("Yes.");+ });+});diff --git a/lib/agent-group/store.ts b/lib/agent-group/store.tsnew file mode 100644index 00000000..ea86cfb3--- /dev/null+++ b/lib/agent-group/store.ts@@ -0,0 +1,195 @@+import { randomUUID } from "node:crypto";+import { constants, promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { expandOwnerStorePath } from "@/lib/owner-store-path.js";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { AgentGroupError } from "./errors";+import { parseAgentGroupPatch } from "./schema";+import type { AgentGroupRecord, AgentGroupRun, AgentGroupState } from "./types";++const MAX_BYTES = 1024 * 1024;+const MAX_RUNS = 50;+const MAX_TURNS_PER_RUN = 24;+const storePath = () =>+ expandOwnerStorePath(process.env.OS_AGENT_GROUP_STORE ?? path.join(os.homedir(), ".mso", "private", "agent-groups.json"));+const empty = (): AgentGroupState => ({ version: 1, revision: 0, groups: [], runs: [] });++function validRun(raw: unknown): AgentGroupRun {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new AgentGroupError("invalid_group_store");+ const run = raw as AgentGroupRun;+ if (+ typeof run.id !== "string" ||+ typeof run.groupId !== "string" ||+ typeof run.prompt !== "string" ||+ !["running", "completed", "failed", "stopped"].includes(run.state) ||+ !Array.isArray(run.turns) ||+ typeof run.startedAt !== "string" ||+ typeof run.updatedAt !== "string"+ ) {+ throw new AgentGroupError("invalid_group_store");+ }+ return run;+}++function validateState(value: unknown): AgentGroupState {+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new AgentGroupError("invalid_group_store");+ const state = value as Partial<AgentGroupState>;+ if (state.version !== 1 || !Number.isSafeInteger(state.revision) || (state.revision ?? -1) < 0 || !Array.isArray(state.groups)) {+ throw new AgentGroupError("invalid_group_store");+ }+ const ids = new Set<string>();+ const groups = state.groups.map((raw) => {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new AgentGroupError("invalid_group_store");+ const row = raw as AgentGroupRecord;+ if (typeof row.id !== "string" || !/^[0-9a-f-]{36}$/i.test(row.id) || ids.has(row.id)) throw new AgentGroupError("invalid_group_store");+ ids.add(row.id);+ const parsed = parseAgentGroupPatch(row as unknown as Record<string, unknown>);+ if (typeof row.createdAt !== "string" || typeof row.updatedAt !== "string") throw new AgentGroupError("invalid_group_store");+ return { id: row.id, ...parsed, createdAt: row.createdAt, updatedAt: row.updatedAt } satisfies AgentGroupRecord;+ });+ const runs = Array.isArray(state.runs) ? state.runs.map(validRun) : [];+ return { version: 1, revision: state.revision!, groups, runs };+}++async function readUnlocked(): Promise<AgentGroupState> {+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;+ try {+ handle = await fs.open(storePath(), constants.O_RDONLY | constants.O_NOFOLLOW);+ const stat = await handle.stat();+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_BYTES || stat.mode & 0o077) throw new AgentGroupError("unsafe_group_store");+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new AgentGroupError("unsafe_group_store");+ return validateState(JSON.parse(await handle.readFile("utf8")));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return empty();+ throw error;+ } finally {+ await handle?.close().catch(() => undefined);+ }+}++async function writeUnlocked(state: AgentGroupState) {+ const file = storePath();+ const dir = path.dirname(file);+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });+ await fs.chmod(dir, 0o700);+ state.runs = state.runs.slice(-MAX_RUNS);+ const body = JSON.stringify(state, null, 2) + "\n";+ if (Buffer.byteLength(body) > MAX_BYTES) throw new AgentGroupError("agent_group_store_capacity", 409);+ const temp = `${file}.${randomUUID()}.tmp`;+ try {+ await fs.writeFile(temp, body, { flag: "wx", mode: 0o600 });+ await fs.rename(temp, file);+ await fs.chmod(file, 0o600);+ } finally {+ await fs.unlink(temp).catch(() => undefined);+ }+}++export async function readAgentGroupState() {+ return structuredClone(await readUnlocked());+}++async function mutate<T>(fn: (state: AgentGroupState) => T | Promise<T>, bumpRevision = true) {+ return withSecurityStoreLock(storePath(), async () => {+ const state = await readUnlocked();+ const result = await fn(state);+ if (bumpRevision) state.revision += 1;+ await writeUnlocked(state);+ return { result, state: structuredClone(state) };+ });+}++export async function listAgentGroups() {+ return (await readUnlocked()).groups;+}++export async function agentGroupById(id: string) {+ const row = (await readUnlocked()).groups.find((item) => item.id === id);+ if (!row) throw new AgentGroupError("agent_group_not_found", 404);+ return structuredClone(row);+}++export async function createAgentGroup(raw: Record<string, unknown>) {+ return mutate((state) => {+ const now = new Date().toISOString();+ const row: AgentGroupRecord = { id: randomUUID(), ...parseAgentGroupPatch(raw), createdAt: now, updatedAt: now };+ state.groups.push(row);+ return structuredClone(row);+ });+}++export async function updateAgentGroup(id: string, expectedRevision: number, raw: Record<string, unknown>) {+ return mutate((state) => {+ if (state.revision !== expectedRevision) throw new AgentGroupError("agent_group_revision_changed", 409);+ const index = state.groups.findIndex((row) => row.id === id);+ if (index < 0) throw new AgentGroupError("agent_group_not_found", 404);+ const previous = state.groups[index]!;+ const row: AgentGroupRecord = {+ ...previous,+ ...parseAgentGroupPatch(raw, previous),+ id: previous.id,+ createdAt: previous.createdAt,+ updatedAt: new Date().toISOString(),+ };+ state.groups[index] = row;+ return structuredClone(row);+ });+}++export async function deleteAgentGroup(id: string, expectedRevision: number) {+ return mutate((state) => {+ if (state.revision !== expectedRevision) throw new AgentGroupError("agent_group_revision_changed", 409);+ const index = state.groups.findIndex((row) => row.id === id);+ if (index < 0) throw new AgentGroupError("agent_group_not_found", 404);+ const removed = state.groups.splice(index, 1)[0]!;+ state.runs = state.runs.filter((run) => run.groupId !== id);+ return structuredClone(removed);+ });+}++export async function readRun(id: string): Promise<AgentGroupRun> {+ const row = (await readUnlocked()).runs.find((run) => run.id === id);+ if (!row) throw new AgentGroupError("agent_group_run_not_found", 404);+ return structuredClone(row);+}++export async function listRuns(groupId: string): Promise<AgentGroupRun[]> {+ return (await readUnlocked())+ .runs.filter((run) => run.groupId === groupId)+ .sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1));+}++export async function createRun(groupId: string, prompt: string) {+ return mutate((state) => {+ if (!state.groups.some((group) => group.id === groupId)) throw new AgentGroupError("agent_group_not_found", 404);+ const now = new Date().toISOString();+ const run: AgentGroupRun = { id: randomUUID(), groupId, prompt, turns: [], state: "running", startedAt: now, updatedAt: now };+ state.runs.push(run);+ state.runs = state.runs.slice(-MAX_RUNS);+ return structuredClone(run);+ });+}++export async function appendTurn(runId: string, turn: Omit<AgentGroupRun["turns"][number], "at">, state: AgentGroupRun["state"]) {+ return mutate((stored) => {+ const run = stored.runs.find((row) => row.id === runId);+ if (!run) throw new AgentGroupError("agent_group_run_not_found", 404);+ run.turns.push({ ...turn, at: new Date().toISOString() });+ run.turns = run.turns.slice(-MAX_TURNS_PER_RUN);+ run.state = state;+ run.updatedAt = new Date().toISOString();+ return structuredClone(run);+ }, false);+}++export async function finishRun(runId: string, state: AgentGroupRun["state"], error?: string) {+ return mutate((stored) => {+ const run = stored.runs.find((row) => row.id === runId);+ if (!run) throw new AgentGroupError("agent_group_run_not_found", 404);+ run.state = state;+ if (error) run.error = error.slice(0, 300);+ run.updatedAt = new Date().toISOString();+ return structuredClone(run);+ }, false);+}diff --git a/lib/agent-group/types.ts b/lib/agent-group/types.tsnew file mode 100644index 00000000..6929a2a2--- /dev/null+++ b/lib/agent-group/types.ts@@ -0,0 +1,56 @@+export type AgentGroupMemberTelegram = {+ user: string;+ connection: string;+ target: string;+};++export type AgentGroupMember = {+ id: string;+ name: string;+ profile: string;+ telegram?: AgentGroupMemberTelegram;+};++export type AgentGroupRecord = {+ id: string;+ name: string;+ members: AgentGroupMember[];+ maxRounds: number;+ enabled: boolean;+ createdAt: string;+ updatedAt: string;+};++export type AgentGroupTurn = {+ round: number;+ memberId: string;+ name: string;+ profile: string;+ text: string;+ at: string;+ error?: string;+};++export type AgentGroupRunState = "running" | "completed" | "failed" | "stopped";++export type AgentGroupRun = {+ id: string;+ groupId: string;+ prompt: string;+ turns: AgentGroupTurn[];+ state: AgentGroupRunState;+ error?: string;+ startedAt: string;+ updatedAt: string;+};++export type AgentGroupState = {+ version: 1;+ revision: number;+ groups: AgentGroupRecord[];+ runs: AgentGroupRun[];+};++export type AgentGroupView = AgentGroupRecord & {+ runs: AgentGroupRun[];+};diff --git a/scripts/cli/agent-groups.sh b/scripts/cli/agent-groups.shnew file mode 100644index 00000000..4aad8e58--- /dev/null+++ b/scripts/cli/agent-groups.sh@@ -0,0 +1,45 @@+#!/usr/bin/env bash+# Agent groups CLI. Each member runs as its own headless Hermes profile; bot+# tokens stay in Integrations and are only referenced by connection id here.+run_agent_groups() {+ local sub="${1:-list}" id="" run_id="" input='{}' revision="" prompt="" members="" body+ shift || true+ case "$sub" in+ show|save|delete|run) id="${1:?group id required}"; shift ;;+ stop) run_id="${1:?run id required}"; shift ;;+ esac+ while [ $# -gt 0 ]; do+ case "$1" in+ --input) input="${2:?JSON or @file required}"; shift 2 ;;+ --revision) revision="${2:?revision required}"; shift 2 ;;+ --prompt) prompt="${2:?prompt required}"; shift 2 ;;+ --members) members="${2:?comma-separated member ids required}"; shift 2 ;;+ *) die "unknown agent-groups option: $1" ;;+ esac+ done+ if [ "${input:0:1}" = "@" ]; then input=$(cat -- "${input:1}"); fi+ case "$sub" in+ list) jget "/api/v1/agent-groups" ;;+ show) jget "/api/v1/agent-groups?id=$(enc "$id")" ;;+ create)+ body=$(jq -n --argjson data "$input" '{action:"create",data:$data}')+ jpost "/api/v1/agent-groups" "$body" ;;+ save)+ [ -n "$revision" ] || die "agent-groups save requires --revision"+ body=$(jq -n --arg id "$id" --argjson revision "$revision" --argjson data "$input" '{action:"update",id:$id,expectedRevision:$revision,data:$data}')+ jpost "/api/v1/agent-groups" "$body" ;;+ delete)+ [ -n "$revision" ] || die "agent-groups delete requires --revision"+ body=$(jq -n --arg id "$id" --argjson revision "$revision" '{action:"delete",id:$id,expectedRevision:$revision}')+ jpost "/api/v1/agent-groups" "$body" ;;+ run)+ [ -n "$prompt" ] || die "agent-groups run requires --prompt"+ body=$(jq -n --arg id "$id" --arg prompt "$prompt" --arg members "$members" \+ '{action:"run",id:$id,prompt:$prompt}+if $members!="" then {members:($members|split(","))} else {} end')+ jpost "/api/v1/agent-groups" "$body" ;;+ stop)+ body=$(jq -n --arg runId "$run_id" '{action:"stop",runId:$runId}')+ jpost "/api/v1/agent-groups" "$body" ;;+ *) die "usage: mso ${U_agent_groups:-agent-groups}" ;;+ esac+}diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.shindex a43d7703..4b909811 100755--- a/scripts/cli/commands-runtime.sh+++ b/scripts/cli/commands-runtime.sh@@ -11,6 +11,7 @@ case "$cmd" inonboard) run_onboard "${1-}" ;;integrations) run_integrations "$@" ;;channels) source "$ROOT/scripts/cli/channels.sh"; run_channels "$@" ;;+ agent-groups) source "$ROOT/scripts/cli/agent-groups.sh"; run_agent_groups "$@" ;;flow) source "$ROOT/scripts/cli/flows.sh"; run_flow "$@" ;;workflow) source "$ROOT/scripts/cli/workflows.sh"; run_workflow "$@" ;;provider|providers) run_provider "$@" ;;diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex 865d6848..c6d6c1f3 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -28,6 +28,7 @@ U_flow="flow list|inspect <id> [--project <project>]|run <id> --input <JSON|@filU_workflow="workflow list|embeds|embed-save --input <JSON|@file>|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|runs <id>|versions <id>|restore <id> --revision <current> --version <saved>|catalog [--query q]|templates|template <id>|variables|variable-set <KEY> --input <JSON> [--secret]|variable-delete <KEY>|ai --prompt <text>"U_integrations="integrations [interactive]|transfer|status|users|catalog|connections [user] [provider]|which [folder]|request|resolve <user> <provider> [connection]|create-user <id> [label]|create-connection <user> <provider> <id> <source> <auth>|manage <JSON>|setup|verify <user> <provider> <connection>|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute <JSON>"U_channels="channels list|create --input <JSON|@file>|save <id> --revision <n> --input <JSON|@file>|delete <id> --revision <n>|test <id>|send <id> --text <message> [--target <id>]"+U_agent_groups="agent-groups list|show <id>|create --input <JSON|@file>|save <id> --revision <n> --input <JSON|@file>|delete <id> --revision <n>|run <id> --prompt <text> [--members <ids>]|stop <run-id>"U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"@@ -101,7 +102,7 @@ mso_cli_main() {case "$cmd" inversion|--version|-V|-v|ls|cat|raw|share|usage|search|project-candidates|write|mkdir|rm|mv|cp|zip|upload|exec|stats|ps|units|unit|packages|cleanup|status|health|doctor)mso_cmd_host "$cmd" "$@" ;;- agent|chat|model|setup|onboard|provider|providers|integrations|channels|flow|workflow|gateway|heartbeat|web|camoufox|apps|mapp|term)+ agent|chat|model|setup|onboard|provider|providers|integrations|channels|agent-groups|flow|workflow|gateway|heartbeat|web|camoufox|apps|mapp|term)mso_cmd_runtime "$cmd" "$@" ;;ai|cockpit|threads|agent-sessions|agents|org|a2a|memory|memory-graph|agent-vault|config|prefs|federation|models|jev|skills|changelog|stock)mso_cmd_state "$cmd" "$@" ;;