Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): web cockpit — Mercury Bots section on the local dashboard

Salman Qureshi59c71299eff9
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.md
index 40937980..cb2c6fd9 100644
--- a/BOTS-ARCHITECTURE.md
+++ b/BOTS-ARCHITECTURE.md
@@ -187,6 +187,7 @@ Inherited from Mercury's "always uses a solution" ethos, hardened:
| Surface | How |
|---|---|
| **Real-time activity bus** | Every bot turn emits granular events (turn-start, step, tool start/finish, turn-end) via `BotManager.onBotActivity`. Consumed by: the open bot thread's live region (same spinner block as the main chat), the `/bots` roster `↳ activity` line and `fleet_status` (mirrored into the activity map), and the web SSE feed (`bot_activity` events — dashboards / third-party backends). |
+| **Web cockpit** ("Mercury Bots" section) | Full fleet management in the dashboard (`ui/src/pages/Bots.tsx` + `ui/src/components/bots/`): live roster with fleet nesting (SSE `bot_activity` over `GET /api/bots/events`, 4s poll fallback), onboarding wizard with executable permission tiers, persona + permissions editors (single source of truth), per-bot panels (send/daily ops/DLQ replay), **deliverables inbox** (`bot_deliver` → `outputs/<botId>/` — fleet-wide list/preview/download/remove + live `Delivered` banner; exempt from the janitor, removed only by the owner), bundle export/import. Endpoints in `src/web/api/bots.ts` (output file routes containment-guarded like `deliver()`). |
| **TUI** | New `/bots` slash command (fast-path, like `/agents`) → interactive panel: list bots (live states), onboard (guided, fully automatic config generation), edit config/persona, view journal, enable/disable, send a message. Also a TUI page in `cli.ts` command layer. |
| **Local HTTP API** | Hono module `src/web/api/bots.ts`: `GET /api/bots`, `POST /api/bots` (onboard), `GET/PATCH/DELETE /api/bots/:id`, `POST /api/bots/:id/message` (enqueue; returns job id), `POST /api/bots/:id/enable|disable`, `GET /api/bots/:id/journal`, `POST /api/bots/:id/replay`. Auth: existing web auth + attach token. |
| **Mercury Cloud** | `agent.command` envelope gains `bot.*` command types (list, message, configure) — same pattern as existing `model.select`/`task.stop`; cross-instance bot↔bot via `agent.message.relay`. |
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index cf63d0ee..adcfbacd 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -1,7 +1,7 @@
import { cpus } from 'node:os';
import { randomUUID } from 'node:crypto';
import { basename, extname, isAbsolute, relative, resolve, join } from 'node:path';
-import { copyFileSync, existsSync, mkdirSync, renameSync, statSync, unlinkSync } from 'node:fs';
+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from 'node:fs';
import type { Tool } from 'ai';
import type { MercuryConfig } from '../utils/config.js';
import type { ProviderRegistry } from '../providers/registry.js';
@@ -1287,16 +1287,21 @@ export class BotManager {
}
const outputsDir = join(this.store.outputsDir(), botId);
mkdirSync(outputsDir, { recursive: true });
- const stem = basename(candidate, extname(candidate));
- const extMatch = extname(candidate);
- const requested = (rename || stem)
+ // Default name keeps the FULL basename — the extension is part of the
+ // artifact (a report.md stayed .md; the stem-only default silently
+ // stripped it). `saveAs` is honored as written; dedupe inserts the -N
+ // before whatever extension remains.
+ const ext = extname(rename || basename(candidate));
+ const stem = basename(rename || basename(candidate), ext);
+ const requested = (stem)
.replace(/[ <>:"/\\|?*]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 120) || 'output';
- let dest = join(outputsDir, requested);
+ const finalExt = ext;
+ let dest = join(outputsDir, `${requested}${finalExt}`);
for (let i = 2; existsSync(dest); i++) {
- dest = join(outputsDir, `${requested}-${i}${extMatch}`);
+ dest = join(outputsDir, `${requested}-${i}${finalExt}`);
}
try {
renameSync(candidate, dest);
@@ -1310,9 +1315,75 @@ export class BotManager {
}
}
logger.info({ botId, dest }, 'Bot delivered a final artifact');
+ // The deliverable moment is the event the owner reacts to: broadcast it
+ // on the activity bus so the CLI bot-thread region, the /bots roster and
+ // the web SSE feed all announce the artifact live.
+ this.emitBotActivity({
+ botId,
+ jobId: '',
+ kind: 'tool',
+ label: `Delivered ${basename(dest, extname(dest))}${extname(dest)}`,
+ detail: dest,
+ stepIndex: 0,
+ elapsedMs: 0,
+ status: 'done',
+ });
return { accepted: true, path: dest };
}
+ /**
+ * Owner-curated deliverables (bot_deliver → outputs/<botId>/). Read-only
+ * views for the web cockpit: list with newest first; read (text preview,
+ * 64KB cap) and deletes are containment-guarded — nothing outside the
+ * bot's own outputs zone is addressable.
+ */
+ listDeliverables(botId?: string): Array<{ botId: string; name: string; bytes: number; mtimeMs: number }> {
+ const root = this.store.outputsDir();
+ if (!existsSync(root)) return [];
+ const bots = botId
+ ? [botId]
+ : readdirSync(root, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name);
+ const out: Array<{ botId: string; name: string; bytes: number; mtimeMs: number }> = [];
+ for (const bot of bots) {
+ const dir = join(root, bot);
+ if (!existsSync(dir)) continue;
+ for (const name of readdirSync(dir, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name)) {
+ try {
+ const stat = statSync(join(dir, name));
+ out.push({ botId: bot, name, bytes: stat.size, mtimeMs: stat.mtimeMs });
+ } catch { /* raced a concurrent delete — skip */ }
+ }
+ }
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
+ }
+
+ /** Contained path resolution for deliverable access; null when it escapes. Public for the web API's byte-exact download route. */
+ deliverableFile(botId: string, name: string): string | null {
+ const dir = join(this.store.outputsDir(), botId);
+ const candidate = resolve(dir, name);
+ const rel = relative(dir, candidate);
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null;
+ return candidate;
+ }
+
+ readDeliverable(botId: string, name: string, maxBytes = 64 * 1024): { found: boolean; preview?: string; truncated?: boolean } {
+ const file = this.deliverableFile(botId, name);
+ if (!file || !existsSync(file)) return { found: false };
+ const buf = readFileSync(file);
+ return {
+ found: true,
+ preview: buf.subarray(0, maxBytes).toString('utf-8'),
+ truncated: buf.length > maxBytes,
+ };
+ }
+
+ deleteDeliverable(botId: string, name: string): { ok: boolean } {
+ const file = this.deliverableFile(botId, name);
+ if (!file || !existsSync(file)) return { ok: false };
+ unlinkSync(file);
+ return { ok: true };
+ }
+
/**
* Retention janitor sweep: files in the fleet-shared folder cool down into
* `_shared/.archive/<yyyy-mm>/` past the hot window, and the archive
diff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.ts
new file mode 100644
index 00000000..63867455
--- /dev/null
+++ b/src/web/api/bots.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { getDefaultConfig } from '../../utils/config.js';
+import { BotManager } from '../../bots/bot-manager.js';
+import { BotStore } from '../../bots/store.js';
+import { PERMISSION_TIERS } from '../../bots/permission-tiers.js';
+import app, { setBotManager } from './bots.js';
+
+/**
+ * Web cockpit API — handlers tested directly via the module's own Hono app
+ * (server.ts mounts it behind authGuard; the guard itself is covered by its
+ * own suite). Covers the deliverables inbox, tier-executing onboarding, the
+ * persona/permissions editors, and bundle round-trips.
+ */
+
+let root: string;
+let store: BotStore;
+let manager: BotManager;
+
+const stubProviders = {
+ get: () => undefined,
+ getDefault: () => ({
+ name: 'stub', model: 'stub-model',
+ generateText: async () => ({ text: 'ok', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub-model', provider: 'stub' }),
+ streamText: async function* () { yield { text: 'ok', done: true }; },
+ isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub-model',
+ } as never),
+} as never;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-web-bots-'));
+ store = new BotStore(join(root, 'bots'));
+ const config = getDefaultConfig() as never;
+ (config as any).bots.maxConcurrent = 4;
+ manager = new BotManager({
+ config,
+ providers: stubProviders,
+ tokenBudget: { recordUsage: () => {}, getRemaining: () => 100000, getStatusText: () => '', getUsagePercentage: () => 0 } as never,
+ store,
+ userMemoryFactory: () => null,
+ } as never);
+ setBotManager(manager);
+});
+
+afterEach(() => {
+ manager.dispose(); // Windows: release the SQLite handle before rm
+ setBotManager(undefined);
+ rmSync(root, { recursive: true, force: true });
+});
+
+const jreq = (res: Response) => res.json() as Promise<any>;
+
+describe('web bots API — cockpit', () => {
+ it('GET tiers returns the executable tier catalog', async () => {
+ const res = await app.request('/api/bots/tiers');
+ expect(res.status).toBe(200);
+ const { tiers } = await jreq(res);
+ expect(tiers.map((t: any) => t.id).sort()).toEqual(Object.keys(PERMISSION_TIERS).sort());
+ expect(tiers.find((t: any) => t.id === 'full').deny).toEqual(PERMISSION_TIERS.full.deny);
+ });
+
+ it('onboarding with a tier EXECUTES it — permissions.yaml gets the tier wholesale', async () => {
+ const res = await app.request('/api/bots', { method: 'POST', body: JSON.stringify({ id: 'researcher', name: 'Research', tier: 'builder' }), headers: { 'Content-Type': 'application/json' } });
+ expect(res.status).toBe(201);
+ const perms = manager.store.readPermissions('researcher');
+ expect(perms.tools?.deny).toEqual(PERMISSION_TIERS.builder.deny);
+ expect(readFileSync(join(root, 'bots', 'researcher', 'permissions.yaml'), 'utf-8')).toBeTruthy();
+ });
+
+ it('onboarding with an unknown tier is rejected 400 — no silent default', async () => {
+ const res = await app.request('/api/bots', { method: 'POST', body: JSON.stringify({ id: 'x', name: 'X', tier: 'godmode' }), headers: { 'Content-Type': 'application/json' } });
+ expect(res.status).toBe(400);
+ });
+
+ it('persona editor round-trips and flags invalid bots', async () => {
+ await app.request('/api/bots', { method: 'POST', body: JSON.stringify({ id: 'writer', name: 'Writer', tier: 'readonly' }), headers: { 'Content-Type': 'application/json' } });
+ const put = await app.request('/api/bots/writer/persona', { method: 'PUT', body: JSON.stringify({ persona: '# You are terse.\nWrite only numbers.' }), headers: { 'Content-Type': 'application/json' } });
+ expect(put.status).toBe(200);
+ const got = await jreq(await app.request('/api/bots/writer/persona'));
+ expect(got.persona).toContain('Write only numbers.');
+ expect((await app.request('/api/bots/ghost/persona')).status).toBe(404);
+ });
+
+ it('permissions editor: GET reflects the file; PUT tier applies; PUT custom persists', async () => {
+ store.create({ id: 'solo', name: 'Solo' });
+ let got = await jreq(await app.request('/api/bots/solo/permissions'));
+ expect(got.permissions).toEqual(store.readPermissions('solo'));
+
+ await app.request('/api/bots/solo/permissions', { method: 'PUT', body: JSON.stringify({ tier: 'operator' }), headers: { 'Content-Type': 'application/json' } });
+ expect(store.readPermissions('solo').tools?.deny).toEqual(PERMISSION_TIERS.operator.deny);
+
+ const custom = { tools: { deny: ['run_command'] }, paths: [{ scope: '~/workspace', mode: 'rw' }] };
+ const put = await app.request('/api/bots/solo/permissions', { method: 'PUT', body: JSON.stringify({ permissions: custom }), headers: { 'Content-Type': 'application/json' } });
+ expect(put.status).toBe(200);
+ expect(store.readPermissions('solo').tools?.deny).toEqual(['run_command']);
+ });
+
+ it('deliverables: deliver → list → preview → download → remove, with traversal and unknown rejected', async () => {
+ store.create({ id: 'publisher', name: 'Publisher' });
+ const sandboxFile = join(manager.store.sandboxDir('publisher'), 'final-report.md');
+ mkdirSync(manager.store.sandboxDir('publisher'), { recursive: true });
+ writeFileSync(sandboxFile, '# The final report');
+ const delivered = manager.deliver('publisher', sandboxFile);
+ expect(delivered.accepted).toBe(true);
+
+ // Fleet inbox lists it
+ let list = await jreq(await app.request('/api/bots/outputs'));
+ expect(list.outputs).toEqual([expect.objectContaining({ botId: 'publisher', name: 'final-report.md' })]);
+
+ // Per-bot list
+ list = await jreq(await app.request('/api/bots/publisher/outputs'));
+ expect(list.outputs).toHaveLength(1);
+
+ // Preview
+ const preview = await jreq(await app.request('/api/bots/publisher/outputs/final-report.md/preview'));
+ expect(preview.preview).toContain('# The final report');
+
+ // Download — raw bytes + content type
+ const dl = await app.request('/api/bots/publisher/outputs/final-report.md/download');
+ expect(dl.status).toBe(200);
+ expect(dl.headers.get('content-type')).toBe('text/markdown');
+ expect(await dl.text()).toContain('# The final report');
+
+ // Traversal names resolve outside the bot's outputs dir → 404, never a file
+ expect((await app.request(`/api/bots/publisher/outputs/${encodeURIComponent('..%2F..%2Fbot.yaml')}/preview`)).status).toBe(404);
+ expect((await app.request('/api/bots/publisher/outputs/ghost.md/preview')).status).toBe(404);
+
+ // Remove
+ const del = await app.request('/api/bots/publisher/outputs/final-report.md', { method: 'DELETE' });
+ expect(del.status).toBe(200);
+ expect((await app.request('/api/bots/publisher/outputs')).status ?? 0).toBeLessThan(500);
+ const after = await jreq(await app.request('/api/bots/publisher/outputs'));
+ expect(after.outputs).toHaveLength(0);
+ });
+
+ it('bundle export → import round-trip recreates the bot (disabled) and skips duplicates', async () => {
+ await app.request('/api/bots', { method: 'POST', body: JSON.stringify({ id: 'crewbot', name: 'Crew', persona: '# persona', tier: 'builder' }), headers: { 'Content-Type': 'application/json' } });
+
+ const bundleRes = await app.request('/api/bots/crewbot/bundle');
+ expect(bundleRes.status).toBe(200);
+ expect(bundleRes.headers.get('content-disposition')).toContain('crewbot-bundle.json');
+ const bundle = await bundleRes.json();
+
+ // Import into an EMPTY store — the bot comes back disabled per bundle semantics.
+ const store2 = manager.store; // same store: import with the same id skips
+ const report = await jreq(await app.request('/api/bots/import', { method: 'POST', body: JSON.stringify(bundle), headers: { 'Content-Type': 'application/json' } }));
+ expect(report.report.skipped.length + report.report.created.length).toBeGreaterThan(0);
+ expect(existsSync(join(root, 'bots', 'crewbot'))).toBe(true);
+ void store2;
+
+ // Malformed bundle → 400
+ expect((await app.request('/api/bots/import', { method: 'POST', body: JSON.stringify({ nope: true }), headers: { 'Content-Type': 'application/json' } })).status).toBe(400);
+ });
+});
\ No newline at end of file
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
index 22dc3126..3f009c50 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -1,6 +1,9 @@
import { Hono } from 'hono';
+import { readFileSync } from 'node:fs';
import type { BotManager } from '../../bots/bot-manager.js';
import type { BotManifest } from '../../bots/types.js';
+import { PERMISSION_TIERS, tierPermissionsFile, isPermissionTier, type PermissionTier } from '../../bots/permission-tiers.js';
+import { buildBotBundle, importBotBundle } from '../../bots/bundle.js';
const app = new Hono();
@@ -30,10 +33,13 @@ app.post('/api/bots', async (c: any) => {
return c.json({ error: 'Bots not available' }, 400);
}
const body = await c.req.json().catch(() => null) as
- { id?: string; name?: string; description?: string; persona?: string; manifest?: Partial<BotManifest> } | null;
+ { id?: string; name?: string; description?: string; persona?: string; tier?: string; manifest?: Partial<BotManifest> } | null;
if (!body?.id || !body?.name) {
return c.json({ error: 'id and name are required' }, 400);
}
+ if (body.tier !== undefined && !isPermissionTier(body.tier)) {
+ return c.json({ error: `Unknown permission tier: ${body.tier}` }, 400);
+ }
try {
const manifest = botManager.store.create({
id: body.id,
@@ -42,6 +48,12 @@ app.post('/api/bots', async (c: any) => {
persona: body.persona,
manifest: body.manifest,
});
+ // Tiers execute (§2.5): the chosen tier writes the full permissions.yaml
+ // — tool gate AND path scopes. A tier choice that only flipped the tool
+ // gate left bots unable to act.
+ if (body.tier) {
+ botManager.store.writePermissions(manifest.id, tierPermissionsFile(body.tier as PermissionTier));
+ }
botManager.invalidateRuntime(manifest.id);
return c.json({ bot: manifest }, 201);
} catch (err: any) {
@@ -49,6 +61,76 @@ app.post('/api/bots', async (c: any) => {
}
});
+// ── Real-time fleet feed (SSE) ──────────────────────────────────────────────
+// Mirrors the Kanban events route: one connection per browser tab, roster
+// snapshot on connect, live bot_activity + bot_deliverable events from the
+// in-process activity bus, keepalive, cleanup on abort. The web dashboard
+// rides the same bus as the CLI's bot-thread live region.
+app.get('/api/bots/events', (c: any) => {
+ const bm = botManager;
+ if (!bm) return c.json({ error: 'Bots not available' }, 400);
+ const stream = new ReadableStream({
+ start(controller) {
+ const encoder = new TextEncoder();
+ const controllerRef = controller;
+ const send = (event: string, data: unknown) => {
+ try {
+ controllerRef.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
+ } catch {
+ // client disconnected — abort handler cleans up
+ }
+ };
+
+ // Snapshot on connect so the UI paints immediately (no first-event wait).
+ send('bot_roster', { bots: bm.getStatusSummaries(), queue: bm.queue.counts() });
+
+ const unsubscribe = bm.onBotActivity((ev) => send('bot_activity', ev));
+
+ const keepalive = setInterval(() => {
+ try { controller.enqueue(encoder.encode(': keepalive\n\n')); } catch { clearInterval(keepalive); }
+ }, 15000);
+
+ c.req.raw.signal?.addEventListener('abort', () => {
+ clearInterval(keepalive);
+ unsubscribe();
+ });
+ },
+ cancel() {},
+ });
+ return new Response(stream, {
+ headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' },
+ });
+});
+
+// ── Deliverables (owner-curated outputs zone — bot_deliver) ────────────────
+// Fleet-wide inbox, newest first.
+app.get('/api/bots/outputs', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ return c.json({ outputs: botManager.listDeliverables() });
+});
+
+// ── Tier catalog for the onboarding wizard ──────────────────────────────────
+app.get('/api/bots/tiers', (c: any) => {
+ const tiers = Object.entries(PERMISSION_TIERS).map(([id, t]) => ({
+ id, label: t.label, description: t.description, deny: t.deny,
+ }));
+ return c.json({ tiers });
+});
+
+// Import a shared bundle (bots start disabled — review before enabling).
+app.post('/api/bots/import', async (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const bundle = await c.req.json().catch(() => null) as any;
+ if (!bundle) return c.json({ error: 'Invalid JSON body' }, 400);
+ try {
+ const report = importBotBundle(botManager.store, bundle, c.req.query('overwrite') === '1' ? { overwrite: true } : {});
+ for (const created of report.created) botManager.invalidateRuntime(created);
+ return c.json({ report });
+ } catch (err: any) {
+ return c.json({ error: err?.message ?? 'Invalid bundle' }, 400);
+ }
+});
+
// Single bot detail (manifest + live state + journal tail)
app.get('/api/bots/:id', (c: any) => {
if (!botManager) return c.json({ error: 'Bots not available' }, 400);
@@ -195,13 +277,141 @@ app.get('/api/bots/:id/crew', (c: any) => {
app.post('/api/bots/:id/crew', async (c: any) => {
if (!botManager) return c.json({ error: 'Bots not available' }, 400);
const id = c.req.param('id');
- const body = await c.req.json().catch(() => null) as { id?: string; name?: string; description?: string; persona?: string } | null;
+ const body = await c.req.json().catch(() => null) as { id?: string; name?: string; description?: string; persona?: string; tier?: string } | null;
if (!body?.id || !body?.name) return c.json({ error: 'id and name are required' }, 400);
+ if (body.tier !== undefined && !isPermissionTier(body.tier)) {
+ return c.json({ error: `Unknown permission tier: ${body.tier}` }, 400);
+ }
const result = botManager.addCrew(id, { id: body.id, name: body.name, description: body.description, persona: body.persona });
if (!result.ok) return c.json({ error: result.error }, 400);
+ // A tier choice overrides the crew's verbatim lead inheritance (§2.5:
+ // inherit-unless-edited — an explicit tier IS an edit).
+ if (body.tier) {
+ botManager.store.writePermissions(result.manifest.id, tierPermissionsFile(body.tier as PermissionTier));
+ }
return c.json({ bot: result.manifest }, 201);
});
+// Persona (character file) — read + write
+app.get('/api/bots/:id/persona', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);
+ return c.json({ persona: botManager.store.readPersona(id) });
+});
+
+app.put('/api/bots/:id/persona', async (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const body = await c.req.json().catch(() => null) as { persona?: string } | null;
+ if (typeof body?.persona !== 'string' || !body.persona.trim()) {
+ return c.json({ error: 'persona (non-empty string) is required' }, 400);
+ }
+ try {
+ botManager.store.writePersona(c.req.param('id'), body.persona);
+ botManager.invalidateRuntime(c.req.param('id'));
+ return c.json({ ok: true });
+ } catch (err: any) {
+ return c.json({ error: err?.message ?? 'Bot not found' }, 404);
+ }
+});
+
+// Permissions.yaml — the single source of truth (tool gate, path scopes,
+// shell lists). PUT with a tier applies the tier wholesale; PUT with a
+// full document is the "custom" path. Fleet inheritance: a crew bot shows
+// its inherited file; writing creates its own explicit copy.
+app.get('/api/bots/:id/permissions', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);
+ return c.json({ permissions: botManager.store.readPermissions(id) });
+});
+
+app.put('/api/bots/:id/permissions', async (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);
+ const body = await c.req.json().catch(() => null) as { tier?: string; permissions?: any } | null;
+ if (!body) return c.json({ error: 'Invalid JSON body' }, 400);
+ try {
+ if (body.tier !== undefined) {
+ if (!isPermissionTier(body.tier)) return c.json({ error: `Unknown permission tier: ${body.tier}` }, 400);
+ botManager.store.writePermissions(id, tierPermissionsFile(body.tier as PermissionTier));
+ } else if (body.permissions !== undefined) {
+ botManager.store.writePermissions(id, body.permissions);
+ } else {
+ return c.json({ error: 'Supply tier or permissions' }, 400);
+ }
+ botManager.invalidateRuntime(id);
+ return c.json({ permissions: botManager.store.readPermissions(id) });
+ } catch (err: any) {
+ return c.json({ error: err?.message ?? 'Invalid permissions document' }, 400);
+ }
+});
+
+// Shareable bundle (identity + persona + permissions + skills; a lead's
+// bundle carries its whole crew). Delivered as an attachment download.
+app.get('/api/bots/:id/bundle', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ try {
+ const bundle = buildBotBundle(botManager.store, id, { withSkills: true });
+ const json = JSON.stringify(bundle, null, 2);
+ return new Response(json, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Content-Disposition': `attachment; filename="${id}-bundle.json"`,
+ },
+ });
+ } catch (err: any) {
+ return c.json({ error: err?.message ?? 'Failed to build bundle' }, 400);
+ }
+});
+
+// This bot's deliverables
+app.get('/api/bots/:id/outputs', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ if (!botManager.store.exists(c.req.param('id'))) return c.json({ error: 'Bot not found' }, 404);
+ return c.json({ outputs: botManager.listDeliverables(c.req.param('id')) });
+});
+
+// Text preview of a deliverable (≤64KB)
+app.get('/api/bots/:id/outputs/:name/preview', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const result = botManager.readDeliverable(c.req.param('id'), c.req.param('name'));
+ if (!result.found) return c.json({ error: 'Deliverable not found' }, 404);
+ return c.json({ preview: result.preview ?? '', truncated: !!result.truncated });
+});
+
+// Byte-exact download of a deliverable (content-type guessed from ext).
+app.get('/api/bots/:id/outputs/:name/download', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ const name = c.req.param('name');
+ const file = botManager.deliverableFile(id, name);
+ if (!file) return c.json({ error: 'Deliverable not found' }, 404);
+ try {
+ const buf = readFileSync(file);
+ const ext = (name.split('.').pop() ?? '').toLowerCase();
+ const mime = MIME_BY_EXT[ext] ?? 'application/octet-stream';
+ return new Response(new Uint8Array(buf), {
+ headers: {
+ 'Content-Type': mime,
+ 'Content-Disposition': `attachment; filename="${name}"`,
+ },
+ });
+ } catch {
+ return c.json({ error: 'Deliverable not found' }, 404);
+ }
+});
+
+// Owner curation: remove a deliverable
+app.delete('/api/bots/:id/outputs/:name', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const result = botManager.deleteDeliverable(c.req.param('id'), c.req.param('name'));
+ if (!result.ok) return c.json({ error: 'Deliverable not found' }, 404);
+ return c.json({ ok: true });
+});
+
function haltedMessage(result: { halted: boolean; heldJobs: number }): string {
const base = result.halted ? 'Halt signal sent' : 'Nothing running';
return result.heldJobs > 0 ? `${base}; ${result.heldJobs} queued job(s) held` : base;
@@ -265,4 +475,11 @@ function contentTypeIsJson(value: string | undefined): boolean {
return (value ?? '').split(';')[0].trim().toLowerCase() === 'application/json';
}
+const MIME_BY_EXT: Record<string, string> = {
+ txt: 'text/plain', md: 'text/markdown', json: 'application/json', yaml: 'application/yaml', yml: 'application/yaml',
+ csv: 'text/csv', pdf: 'application/pdf', html: 'text/html', svg: 'image/svg+xml',
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp',
+ zip: 'application/zip', tar: 'application/x-tar', gz: 'application/gzip',
+};
+
export default app;
\ No newline at end of file
diff --git a/ui/src/components/bots/BotDetail.tsx b/ui/src/components/bots/BotDetail.tsx
new file mode 100644
index 00000000..a9fec4d0
--- /dev/null
+++ b/ui/src/components/bots/BotDetail.tsx
@@ -0,0 +1,305 @@
+import { useCallback, useEffect, useState } from "react";
+import {
+ Bot, Send, Pause, Play, Square, RotateCw, AlertTriangle, Crown, Shield,
+ Download, Package, Clock, Save, RefreshCw,
+} from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import {
+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription,
+} from "@/components/ui/dialog";
+import { cn } from "@/lib/utils";
+import api, { type BotManifest, type BotStatus, type BotRunRecord, type BotDlqEntry, type BotTierInfo, type BotPermissionsFile } from "@/lib/api";
+import { DeliverablesList } from "./DeliverablesList";
+import type { BotEventState } from "./useBotEvents";
+
+const RUN_STYLES: Record<string, string> = {
+ completed: "bg-emerald-500/15 text-emerald-500",
+ failed: "bg-red-500/15 text-red-500",
+ halted: "bg-yellow-500/15 text-yellow-500",
+ paused: "bg-yellow-500/15 text-yellow-500",
+};
+
+/**
+ * The full bot panel: live feed + send, configuration (persona + permissions
+ * editors), deliverables, and ops (DLQ/controls/bundle). One dialog, tabs.
+ */
+export function BotDetail({
+ bot,
+ live,
+ open,
+ onOpenChange,
+ onChanged,
+}: {
+ bot: { bot: BotManifest; state: BotStatus | null; journal: BotRunRecord[]; inbox: unknown[] } | null;
+ live: BotEventState;
+ open: boolean;
+ onOpenChange: (o: boolean) => void;
+ onChanged: () => void;
+}) {
+ const id = bot?.bot.id;
+ const [detail, setDetail] = useState(bot);
+ const [journal, setJournal] = useState<BotRunRecord[]>(bot?.journal ?? []);
+ const [dlq, setDlq] = useState<BotDlqEntry[]>([]);
+ const [message, setMessage] = useState("");
+ const [tiers, setTiers] = useState<BotTierInfo[]>([]);
+ const [persona, setPersona] = useState("");
+ const [personaState, setPersonaState] = useState<"clean" | "dirty" | "saved" | "error">("clean");
+ const [perms, setPerms] = useState<BotPermissionsFile | null>(null);
+ const [permText, setPermText] = useState("");
+ const [permState, setPermState] = useState<"clean" | "dirty" | "saved" | "error">("clean");
+
+ const loadJournal = useCallback(async () => {
+ if (!id) return;
+ try {
+ const [j, d] = await Promise.all([api.bots.get(id).then((r) => r.journal), api.bots.dlq(id)]);
+ setJournal(j);
+ setDlq(d.dlq);
+ } catch {}
+ }, [id]);
+
+ const loadConfig = useCallback(async () => {
+ if (!id) return;
+ try {
+ const [p, permsRes, tiersRes] = await Promise.all([
+ api.bots.persona(id), api.bots.permissions(id), api.bots.tiers(),
+ ]);
+ setPersona(p.persona);
+ setPersonaState("clean");
+ setPerms(permsRes.permissions);
+ setPermText(JSON.stringify(permsRes.permissions, null, 2));
+ setPermState("clean");
+ setTiers(tiersRes.tiers);
+ } catch (e) {
+ setPermText(String(e));
+ }
+ }, [id]);
+
+ useEffect(() => {
+ setDetail(bot);
+ setJournal(bot?.journal ?? []);
+ if (bot?.bot.id) {
+ void loadConfig();
+ void loadJournal();
+ void api.bots.dlq(bot.bot.id).then(({ dlq }) => setDlq(dlq)).catch(() => {});
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [bot?.bot.id, open]);
+
+ useEffect(() => {
+ // Live runs append to the journal — refresh the feed while the dialog is open.
+ if (!open || !id) return;
+ const t = setInterval(() => void loadJournal(), 5000);
+ return () => clearInterval(t);
+ }, [open, id, loadJournal]);
+
+ if (!bot || !id) return null;
+ const m = bot.bot;
+
+ const sendMessage = async () => {
+ if (!message.trim()) return;
+ const result = await api.bots.message(id, message.trim()).catch((e) => ({ accepted: false, reasonCode: (e as Error).message } as const));
+ if (result.accepted) setMessage("");
+ void loadJournal();
+ onChanged();
+ };
+
+ const savePersona = async () => {
+ await api.bots.setPersona(id, persona).then(() => {
+ setPersonaState("saved");
+ onChanged();
+ }).catch(() => setPersonaState("error"));
+ };
+
+ const applyTier = async (tier: string) => {
+ await api.bots.setPermissions(id, { tier });
+ await loadConfig();
+ onChanged();
+ };
+
+ const savePermissions = async () => {
+ try {
+ const parsed = JSON.parse(permText) as BotPermissionsFile;
+ await api.bots.setPermissions(id, { permissions: parsed });
+ setPermState("saved");
+ onChanged();
+ } catch (e) {
+ setPermText(`${e}\n\n${permText}`);
+ setPermState("error");
+ }
+ };
+
+ // Match the current deny-set tier like the CLI does — empty deny sets
+ // (allow-lists present) report as "custom".
+ const deniedSet = new Set(perms?.tools?.deny ?? []);
+ const activeTier = tiers.find((t) => t.deny?.length === deniedSet.size && t.deny.every((d) => deniedSet.has(d)) && deniedSet.size > 0);
+
+ const liveLabel = live.activity[id] ?? bot.state?.activity;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-4xl max-h-[85vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Bot className="h-5 w-5" /> {m.name}
+ <span className="text-muted-foreground text-sm">({id})</span>
+ {m.fleetRole === "lead" && <Badge variant="secondary" className="text-yellow-500"><Crown className="h-3 w-3" /> fleet lead</Badge>}
+ {m.fleetRole === "crew" && <Badge variant="secondary">crew of {m.parent}</Badge>}
+ </DialogTitle>
+ <DialogDescription className="flex flex-wrap items-center gap-2">
+ <Badge variant="secondary">model: {m.model?.provider ?? "inherit"}{m.model?.model ? `:${m.model.model}` : ""}</Badge>
+ <Badge variant="secondary">memory: {m.memory?.scope ?? "own"}</Badge>
+ {m.autonomy?.dailyTokenBudget && <Badge variant="secondary">budget {m.autonomy.dailyTokenBudget}/day</Badge>}
+ {(m.comms?.canMessage?.length ?? 0) > 0 && <Badge variant="secondary">→ {(m.comms!.canMessage ?? []).join(", ")}</Badge>}
+ {(m.schedules?.length ?? 0) > 0 && m.schedules!.map((s) => <Badge key={s.name} variant="secondary">⏰ {s.name} <code className="text-[10px]">{s.cron}</code></Badge>)}
+ </DialogDescription>
+ </DialogHeader>
+
+ <Tabs defaultValue="live" className="mt-2">
+ <TabsList>
+ <TabsTrigger value="live">Live</TabsTrigger>
+ <TabsTrigger value="configure">Configure</TabsTrigger>
+ <TabsTrigger value="deliverables">Deliverables</TabsTrigger>
+ <TabsTrigger value="ops">Ops</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="live" className="space-y-3 mt-3">
+ <Card>
+ <CardContent className="pt-4 space-y-3">
+ {(liveLabel || live.activity[id]) && (
+ <p className="text-sm flex items-center gap-2 text-muted-foreground">
+ <RefreshCw className="h-3.5 w-3.5 animate-spin" /> {liveLabel}
+ </p>
+ )}
+ <Textarea
+ placeholder={`Task ${m.name}… (runs outside the main conversation; durable)`}
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ rows={2}
+ />
+ <div className="flex gap-2">
+ <Button size="sm" onClick={() => void sendMessage()} disabled={!message.trim()}>
+ <Send className="h-3.5 w-3.5" /> Send
+ </Button>
+ <Button size="sm" variant="outline" onClick={async () => { await api.bots.run(id); void loadJournal(); }}>
+ <Clock className="h-3.5 w-3.5" /> Wake now
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ <div>
+ <p className="font-medium text-sm mb-2">Runs</p>
+ {journal.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No runs yet.</p>
+ ) : (
+ <div className="space-y-1.5">
+ {[...journal].reverse().map((r) => (
+ <div key={r.runId} className="rounded-lg border px-3 py-2 space-y-1">
+ <div className="flex items-center gap-2 text-sm">
+ <Badge variant="secondary" className={RUN_STYLES[r.state] ?? ""}>{r.state}</Badge>
+ <span className="text-muted-foreground">{r.trigger}</span>
+ <span className="text-muted-foreground ml-auto">{(r.durationMs / 1000).toFixed(1)}s · {(r.tokensIn + r.tokensOut).toLocaleString()} tok</span>
+ {r.reasonCode && <Badge variant="destructive">{r.reasonCode}</Badge>}
+ </div>
+ {(r.summary || r.error) && (
+ <p className="text-xs text-muted-foreground whitespace-pre-wrap">{r.error ?? r.summary}</p>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </TabsContent>
+
+ <TabsContent value="configure" className="space-y-4 mt-3">
+ <div className="space-y-1.5">
+ <p className="font-medium text-sm flex items-center gap-1"><Bot className="h-4 w-4" /> Persona</p>
+ <Textarea value={persona} onChange={(e) => { setPersona(e.target.value); setPersonaState("dirty"); }} rows={8} />
+ <div className="flex items-center gap-2">
+ <Button size="sm" onClick={() => void savePersona()} disabled={personaState === "clean"}>
+ <Save className="h-3.5 w-3.5" /> Save persona
+ </Button>
+ {personaState === "saved" && <span className="text-xs text-emerald-500">Saved — applies on the bot's next turn</span>}
+ {personaState === "error" && <span className="text-xs text-destructive">Save failed</span>}
+ </div>
+ </div>
+ <div className="space-y-1.5">
+ <p className="font-medium text-sm flex items-center gap-1"><Shield className="h-4 w-4" /> Permissions — the single source of truth (tool gate, path scopes, shell lists)</p>
+ <div className="flex flex-wrap gap-2">
+ {tiers.map((t) => (
+ <Button
+ key={t.id}
+ size="sm"
+ variant={activeTier?.id === t.id ? "default" : "outline"}
+ title={`${t.description} — denied: ${t.deny.join(", ") || "nothing"}`}
+ onClick={() => void applyTier(t.id)}
+ >
+ {t.label}
+ </Button>
+ ))}
+ </div>
+ <Textarea
+ className="font-mono text-xs"
+ rows={8}
+ value={permText}
+ onChange={(e) => { setPermText(e.target.value); setPermState("dirty"); }}
+ />
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" onClick={() => void savePermissions()} disabled={permState !== "dirty"}>
+ <Save className="h-3.5 w-3.5" /> Save custom permissions (JSON)
+ </Button>
+ {permState === "saved" && <span className="text-xs text-emerald-500">Saved — applies on the next turn</span>}
+ {permState === "error" && <span className="text-xs text-destructive">Invalid JSON</span>}
+ </div>
+ </div>
+ </TabsContent>
+
+ <TabsContent value="deliverables" className="mt-3">
+ <DeliverablesList botId={id} lastDelivery={live.lastDelivery} />
+ </TabsContent>
+
+ <TabsContent value="ops" className="space-y-4 mt-3">
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="outline" onClick={async () => { await (m.enabled ? api.bots.disable(id) : api.bots.enable(id)); onChanged(); }}>
+ {m.enabled ? <><Pause className="h-3.5 w-3.5" /> Disable</> : <><Play className="h-3.5 w-3.5" /> Enable</>}
+ </Button>
+ <Button size="sm" variant="outline" onClick={async () => { await api.bots.stop(id); onChanged(); }}>
+ <Square className="h-3.5 w-3.5" /> Stop
+ </Button>
+ <Button size="sm" variant="outline" onClick={async () => { await api.bots.start(id); onChanged(); }}>
+ <Play className="h-3.5 w-3.5" /> Start (resume held jobs)
+ </Button>
+ <Button size="sm" variant="outline" asChild>
+ <a href={api.bots.bundleUrl(id)} download={`${id}-bundle.json`}>
+ <Download className="h-3.5 w-3.5" /> Export bundle
+ </a>
+ </Button>
+ </div>
+
+ {dlq.length > 0 && (
+ <div>
+ <p className="font-medium text-sm mb-2 flex items-center gap-1"><AlertTriangle className="h-4 w-4 text-yellow-500" /> Dead-lettered jobs</p>
+ <div className="space-y-1.5">
+ {dlq.map((e) => (
+ <div key={e.id} className="flex items-center gap-2 text-sm">
+ <span className="text-muted-foreground font-mono">{e.id}</span>
+ <span className="text-red-500">[{e.reasonCode ?? "unknown"}]</span>
+ <span className="text-muted-foreground truncate flex-1" title={e.prompt}>{e.prompt.slice(0, 60)}</span>
+ <Button size="sm" variant="ghost" onClick={async () => { await api.bots.replay(id, e.id); void loadJournal(); onChanged(); }}>
+ <RotateCw className="h-3.5 w-3.5" /> Replay
+ </Button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </TabsContent>
+ </Tabs>
+ </DialogContent>
+ </Dialog>
+ );
+}
\ No newline at end of file
diff --git a/ui/src/components/bots/DeliverablesList.tsx b/ui/src/components/bots/DeliverablesList.tsx
new file mode 100644
index 00000000..75df374b
--- /dev/null
+++ b/ui/src/components/bots/DeliverablesList.tsx
@@ -0,0 +1,154 @@
+import { useCallback, useEffect, useState } from "react";
+import { Package, Download, Trash2, Eye } from "lucide-react";
+import { Card, CardContent } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription,
+} from "@/components/ui/dialog";
+import api, { type DeliverableInfo } from "@/lib/api";
+import { cn, formatDate } from "@/lib/utils";
+
+/**
+ * The deliverables inbox — finished artifacts a bot moved via bot_deliver
+ * into its owner-curated outputs zone. Exempt from the retention janitor:
+ * nothing here disappears automatically; removal is an explicit owner action.
+ */
+export function DeliverablesList({
+ botId,
+ botNames,
+ lastDelivery,
+ compact = false,
+}: {
+ /** undefined = fleet-wide inbox (all bots). */
+ botId?: string;
+ botNames?: Record<string, string>;
+ lastDelivery?: { botId: string; name: string; at: number } | null;
+ compact?: boolean;
+}) {
+ const [outputs, setOutputs] = useState<DeliverableInfo[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [preview, setPreview] = useState<{ d: DeliverableInfo; content: string; truncated: boolean } | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const refresh = useCallback(async () => {
+ try {
+ const data = botId ? await api.bots.botOutputs(botId) : await api.bots.outputs();
+ setOutputs(data.outputs);
+ setError(null);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, [botId]);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh, lastDelivery?.name, lastDelivery?.at]);
+
+ const openPreview = async (d: DeliverableInfo) => {
+ try {
+ const { preview, truncated } = await api.bots.outputPreview(d.botId, d.name);
+ setPreview({ d, content: preview, truncated });
+ } catch (e) {
+ setError((e as Error).message);
+ }
+ };
+
+ const remove = async (d: DeliverableInfo) => {
+ try {
+ await api.bots.deleteOutput(d.botId, d.name);
+ void refresh();
+ } catch (e) {
+ setError((e as Error).message);
+ }
+ };
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <p className="text-sm text-muted-foreground flex items-center gap-2">
+ <Package className="h-4 w-4" />
+ {botId ? "Delivered artifacts" : "Deliverables across the whole fleet"}
+ <span className="text-xs">— protected from auto-cleanup; removed only by you</span>
+ </p>
+ {error && <Badge variant="destructive" className="text-xs">{error}</Badge>}
+ </div>
+
+ {loading ? (
+ <p className="text-sm text-muted-foreground">Loading…</p>
+ ) : outputs.length === 0 ? (
+ <Card>
+ <CardContent className={cn("py-6 text-center text-sm text-muted-foreground")}>
+ No deliverables yet. Bots deliver finished artifacts with their <code>bot_deliver</code> tool
+ (a report, export, dataset — anything final). They appear here the moment they land.
+ </CardContent>
+ </Card>
+ ) : (
+ <Card className={compact ? "max-h-72" : ""}>
+ <CardContent className="pt-4 space-y-1.5">
+ {outputs.map((d) => (
+ <div key={`${d.botId}/${d.name}`} className="flex items-center gap-2 text-sm group">
+ {!botId && (
+ <Badge variant="secondary" className="shrink-0 max-w-40 truncate">
+ {botNames?.[d.botId] ?? d.botId}
+ </Badge>
+ )}
+ <span className="truncate flex-1" title={d.name}>{d.name}</span>
+ <span className="text-muted-foreground text-xs shrink-0">
+ {formatBytes(d.bytes)} · {formatDate(d.mtimeMs)}
+ </span>
+ <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
+ <Button size="icon" variant="ghost" className="h-7 w-7" title="Preview" onClick={() => void openPreview(d)}>
+ <Eye className="h-3.5 w-3.5" />
+ </Button>
+ <Button size="icon" variant="ghost" className="h-7 w-7" title="Download" asChild>
+ <a href={api.bots.outputDownloadUrl(d.botId, d.name)} download>
+ <Download className="h-3.5 w-3.5" />
+ </a>
+ </Button>
+ <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" title="Remove" onClick={() => void remove(d)}>
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ </CardContent>
+ </Card>
+ )}
+
+ {preview && (
+ <Dialog open onOpenChange={(o) => { if (!o) setPreview(null); }}>
+ <DialogContent className="max-w-3xl">
+ <DialogHeader>
+ <DialogTitle className="truncate flex items-center gap-2">
+ <Package className="h-4 w-4" /> {preview.d.name}
+ </DialogTitle>
+ <DialogDescription>
+ {botNames?.[preview.d.botId] ?? preview.d.botId} · {formatBytes(preview.d.bytes)}
+ {preview.truncated ? " · showing the first 64KB" : ""}
+ </DialogDescription>
+ </DialogHeader>
+ <pre className="max-h-[60vh] overflow-auto rounded-lg bg-muted/50 p-4 text-xs whitespace-pre-wrap">
+ {preview.content}
+ </pre>
+ <div className="flex justify-end gap-2">
+ <Button size="sm" asChild>
+ <a href={api.bots.outputDownloadUrl(preview.d.botId, preview.d.name)} download>
+ <Download className="h-4 w-4" /> Download
+ </a>
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )}
+ </div>
+ );
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
\ No newline at end of file
diff --git a/ui/src/components/bots/OnboardWizard.tsx b/ui/src/components/bots/OnboardWizard.tsx
new file mode 100644
index 00000000..55e43e45
--- /dev/null
+++ b/ui/src/components/bots/OnboardWizard.tsx
@@ -0,0 +1,216 @@
+import { useEffect, useState } from "react";
+import { Bot, Crown, Users, ChevronLeft, ChevronRight, Shield, Cpu, Network } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import {
+ Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
+} from "@/components/ui/dialog";
+import { cn } from "@/lib/utils";
+import api, { type BotTierInfo, type BotManifest } from "@/lib/api";
+
+const STEPS = ["Identity", "Permissions tier", "Model & budget", "Fleet"] as const;
+
+/**
+ * Guided onboarding — mirrors the CLI's tier question (§2.5: tiers EXECUTE;
+ * the chosen round-trips into permissions.yaml, never a silent default).
+ */
+export function OnboardWizard({
+ open,
+ onOpenChange,
+ leads,
+ crewAsLeadId,
+ onCreated,
+}: {
+ open: boolean;
+ onOpenChange: (o: boolean) => void;
+ /** Existing fleet leads (for the "crew of" step). */
+ leads: BotManifest[];
+ /** Set = onboard INTO this lead's crew (crew step skipped). */
+ crewAsLeadId?: string;
+ onCreated: (bot: BotManifest) => void;
+}) {
+ const [step, setStep] = useState(0);
+ const [id, setId] = useState("");
+ const [name, setName] = useState("");
+ const [description, setDescription] = useState("");
+ const [persona, setPersona] = useState("");
+ const [tiers, setTiers] = useState<BotTierInfo[]>([]);
+ const [tier, setTier] = useState<string>("readonly");
+ const [provider, setProvider] = useState<string>("inherit");
+ const [model, setModel] = useState<string>("");
+ const [budget, setBudget] = useState<string>("");
+ const [crewOf, setCrewOf] = useState<string>(crewAsLeadId ?? "solo");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setStep(0); setId(""); setName(""); setDescription(""); setPersona("");
+ setTier("readonly"); setProvider("inherit"); setModel(""); setBudget("");
+ setCrewOf(crewAsLeadId ?? "solo"); setError(null);
+ api.bots.tiers().then(({ tiers }) => setTiers(tiers)).catch(() => setTiers([]));
+ }, [open, crewAsLeadId]);
+
+ const create = async () => {
+ setBusy(true); setError(null);
+ try {
+ const manifestPatch: Record<string, unknown> = {};
+ if (provider !== "inherit" || model) manifestPatch.model = { provider: provider === "inherit" ? undefined : provider, model: model || undefined };
+ if (budget) manifestPatch.autonomy = { dailyTokenBudget: parseInt(budget, 10) };
+ let bot: BotManifest;
+ if (crewOf !== "solo" && !crewAsLeadId) {
+ bot = (await api.bots.addCrewFull(crewOf.replace(/^lead:/, ""), {
+ id: id.toLowerCase(), name, description: description || undefined, persona: persona || undefined, tier,
+ })).bot;
+ } else {
+ const res = await api.bots.createFull({
+ id: id.toLowerCase(), name, description: description || undefined, persona: persona || undefined,
+ tier, manifest: manifestPatch as never,
+ });
+ bot = res.bot;
+ }
+ onCreated(bot);
+ onOpenChange(false);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const canNext = step === 0 ? !!id && !!name : step === 3 ? true : true;
+ const targetCrewLead = crewAsLeadId
+ ? crewAsLeadId
+ : crewOf !== "solo" ? crewOf.replace(/^lead:/, "") : null;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Bot className="h-5 w-5" />
+ {targetCrewLead ? `Add crew member — ${targetCrewLead}` : "Onboard a bot"}
+ </DialogTitle>
+ <DialogDescription>
+ Fail-closed by design: explicit grants only, no mid-run prompts, no allow-all.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex items-center gap-1 text-xs text-muted-foreground mb-2">
+ {STEPS.map((s, i) => (
+ <span key={s} className={cn("flex items-center gap-1", i === step && "text-foreground font-medium")}>
+ <span className={cn("inline-flex h-5 w-5 items-center justify-center rounded-full border",
+ i < step ? "bg-primary text-primary-foreground border-primary" : "border-muted")}>
+ {i < step ? "✓" : i + 1}
+ </span>
+ {s}
+ {i < STEPS.length - 1 && <span className="mx-1">→</span>}
+ </span>
+ ))}
+ </div>
+
+ {step === 0 && (
+ <div className="space-y-3">
+ <Input placeholder="id (lowercase, e.g. researcher)" value={id} onChange={(e) => setId(e.target.value)} />
+ <Input placeholder="Name (e.g. Research)" value={name} onChange={(e) => setName(e.target.value)} />
+ <Input placeholder="Description (optional)" value={description} onChange={(e) => setDescription(e.target.value)} />
+ <Textarea
+ placeholder="Persona (optional — who this bot is and how it writes; you can edit it later in Configure)"
+ value={persona} onChange={(e) => setPersona(e.target.value)} rows={4}
+ />
+ </div>
+ )}
+
+ {step === 1 && (
+ <div className="grid gap-3 sm:grid-cols-2">
+ {tiers.map((t) => (
+ <Card
+ key={t.id}
+ className={cn("cursor-pointer transition-colors", tier === t.id ? "border-primary" : "hover:border-primary/50")}
+ onClick={() => setTier(t.id)}
+ >
+ <CardHeader className="pb-1">
+ <CardTitle className="flex items-center gap-2 text-sm">
+ <Shield className="h-4 w-4" /> {t.label}
+ {t.id === "readonly" && <Badge variant="secondary" className="text-[10px]">safest</Badge>}
+ {t.id === "full" && <Badge variant="destructive" className="text-[10px]">broad</Badge>}
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-1 text-xs text-muted-foreground">
+ <p>{t.description}</p>
+ <p className="text-[11px]">Denied: {t.deny.length > 0 ? t.deny.join(", ") : "nothing"}</p>
+ {tier === t.id && <p className="text-[11px] text-primary">✓ written to permissions.yaml on create</p>}
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+
+ {step === 2 && (
+ <div className="space-y-3">
+ <p className="text-xs text-muted-foreground flex items-center gap-1"><Cpu className="h-3.5 w-3.5" /> Optional — leave empty to inherit the instance model.</p>
+ <div className="grid grid-cols-2 gap-3">
+ <Input placeholder="Provider (e.g. deepseek; empty = inherit)" value={provider === "inherit" ? "" : provider} onChange={(e) => { setProvider(e.target.value || "inherit"); }} />
+ <Input placeholder="Model (e.g. deepseek-chat)" value={model} onChange={(e) => setModel(e.target.value)} />
+ </div>
+ <Input placeholder="Daily token budget (optional, e.g. 500000)" value={budget} onChange={(e) => setBudget(e.target.value.replace(/[^0-9]/g, ""))} />
+ </div>
+ )}
+
+ {step === 3 && (
+ <div className="space-y-3">
+ {crewAsLeadId ? (
+ <p className="text-sm text-muted-foreground flex items-center gap-1">
+ <Users className="h-4 w-4" /> Joining <Badge variant="secondary">{crewAsLeadId}</Badge> as crew — it inherits the lead's permissions unless you picked a tier.
+ </p>
+ ) : (
+ <>
+ <Card
+ className={cn("cursor-pointer", crewOf === "solo" ? "border-primary" : "hover:border-primary/50")}
+ onClick={() => setCrewOf("solo")}
+ >
+ <CardContent className="py-3 flex items-center gap-2 text-sm">
+ <Network className="h-4 w-4" /> Solo bot — independent
+ </CardContent>
+ </Card>
+ {leads.length > 0 && (
+ <div className="space-y-1.5">
+ {leads.map((lead) => (
+ <Card
+ key={lead.id}
+ className={cn("cursor-pointer", crewOf === `lead:${lead.id}` ? "border-primary" : "hover:border-primary/50")}
+ onClick={() => setCrewOf(`lead:${lead.id}`)}
+ >
+ <CardContent className="py-3 flex items-center gap-2 text-sm">
+ <Crown className="h-4 w-4 text-yellow-500" /> Crew of <Badge variant="secondary">{lead.name}</Badge> ({lead.id})
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+ </>
+ )}
+ {error && <p className="text-sm text-destructive">{error}</p>}
+ </div>
+ )}
+
+ <DialogFooter>
+ {step > 0 && (
+ <Button variant="outline" onClick={() => setStep((s) => s - 1)}><ChevronLeft className="h-4 w-4" /> Back</Button>
+ )}
+ {step < 3 ? (
+ <Button onClick={() => setStep((s) => s + 1)} disabled={!canNext}>Next <ChevronRight className="h-4 w-4" /></Button>
+ ) : (
+ <Button onClick={() => void create()} disabled={busy}>
+ {busy ? "Creating…" : targetCrewLead ? "Add to fleet" : "Create bot"}
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
\ No newline at end of file
diff --git a/ui/src/components/bots/useBotEvents.ts b/ui/src/components/bots/useBotEvents.ts
new file mode 100644
index 00000000..33750bc2
--- /dev/null
+++ b/ui/src/components/bots/useBotEvents.ts
@@ -0,0 +1,69 @@
+import { useEffect, useState, useRef } from "react";
+
+/**
+ * Live fleet feed — one EventSource per mounted cockpit. Rides the same
+ * in-process activity bus as the CLI's bot-thread live region, so what the
+ * dashboard shows is what the bot is doing right now. EventSource reconnects
+ * natively; components keep their periodic roster poll as the fallback.
+ */
+export interface BotEventState {
+ /** botId → current activity label ("read_file …","fetch_url …"). */
+ activity: Record<string, string>;
+ /** Newest delivered artifact — the deliverables inbox banners + refreshes live on this. */
+ lastDelivery: { botId: string; name: string; at: number } | null;
+ connected: boolean;
+}
+
+export function useBotEvents(): BotEventState {
+ const [state, setState] = useState<BotEventState>({
+ activity: {},
+ lastDelivery: null,
+ connected: false,
+ });
+ const esRef = useRef<EventSource | null>(null);
+
+ useEffect(() => {
+ const es = new EventSource(`${window.location.origin}/api/bots/events`);
+ esRef.current = es;
+
+ es.addEventListener("bot_activity", (e) => {
+ try {
+ const ev = JSON.parse((e as MessageEvent).data) as {
+ botId: string;
+ kind: "turn-start" | "step" | "tool" | "turn-end";
+ label: string;
+ };
+ // A delivered artifact is the moment the owner reacts to — it banners
+ // the inbox AND refreshes its list. Otherwise it's a roster activity label.
+ if (ev.kind === "tool" && ev.label.startsWith("Delivered ")) {
+ const name = ev.label.replace(/^Delivered /, "");
+ setState((prev) => ({
+ ...prev,
+ activity: { ...prev.activity, [ev.botId]: ev.label },
+ lastDelivery: { botId: ev.botId, name, at: Date.now() },
+ }));
+ return;
+ }
+ setState((prev) => {
+ const activity = { ...prev.activity };
+ if (ev.kind === "turn-end") {
+ delete activity[ev.botId];
+ } else {
+ activity[ev.botId] = ev.label;
+ }
+ return { ...prev, activity };
+ });
+ } catch {}
+ });
+
+ es.onopen = () => setState((p) => ({ ...p, connected: true }));
+ es.onerror = () => setState((p) => ({ ...p, connected: false }));
+
+ return () => {
+ es.close();
+ esRef.current = null;
+ };
+ }, []);
+
+ return state;
+}
\ No newline at end of file
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index 198fcbf5..6f5ab3eb 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -652,6 +652,9 @@ export interface BotStatus {
lastRunAt?: number;
lastRunState?: string;
needsYou: boolean;
+ fleetRole?: "lead" | "crew";
+ parent?: string;
+ crewWorking?: number;
}
export interface BotManifest {
@@ -659,6 +662,8 @@ export interface BotManifest {
name: string;
description?: string;
enabled: boolean;
+ fleetRole?: "lead" | "crew";
+ parent?: string;
model?: { provider?: string; model?: string };
memory?: { scope: string };
comms?: { canMessage?: string[] };
@@ -676,6 +681,7 @@ export interface BotRunRecord {
tokensIn: number;
tokensOut: number;
summary?: string;
+ error?: string;
reasonCode?: string;
}
@@ -688,6 +694,39 @@ export interface BotDlqEntry {
reasonCode?: string;
}
+export interface BotActivityEvent {
+ botId: string;
+ jobId: string;
+ kind: "turn-start" | "step" | "tool" | "turn-end";
+ label: string;
+ detail?: string;
+ stepIndex: number;
+ elapsedMs: number;
+ status?: "running" | "done" | "error";
+}
+
+export interface DeliverableInfo {
+ botId: string;
+ name: string;
+ bytes: number;
+ mtimeMs: number;
+}
+
+export interface BotTierInfo {
+ id: string;
+ label: string;
+ description: string;
+ deny: string[];
+}
+
+export interface BotPermissionsFile {
+ paths?: Array<{ scope: string; mode?: string; note?: string }>;
+ tools?: { allow?: string[]; deny?: string[] };
+ autoApproveCommands?: string[];
+ blockedCommands?: string[];
+ [key: string]: unknown;
+}
+
export interface Skill {
name: string;
path: string;
@@ -857,6 +896,29 @@ const api = {
replay: (id: string, jobId: string) => post<{ accepted: boolean }>(`/api/bots/${id}/replay/${jobId}`),
storage: () =>
get<{ usage: Array<{ id: string; bytes: number; journalBytes: number }>; queue: { pending: number; claimed: number; dlq: number } }>("/api/bots-storage"),
+ // ── Cockpit additions ──
+ tiers: () => get<{ tiers: BotTierInfo[] }>("/api/bots/tiers"),
+ createFull: (body: { id: string; name: string; description?: string; persona?: string; tier: string; manifest?: Partial<BotManifest> }) =>
+ post<{ bot: BotManifest }>("/api/bots", body),
+ addCrewFull: (leadId: string, body: { id: string; name: string; description?: string; persona?: string; tier?: string }) =>
+ post<{ bot: BotManifest }>(`/api/bots/${leadId}/crew`, body),
+ crew: (id: string) =>
+ get<{ lead: BotManifest; crew: BotManifest[]; maxCrew: number }>(`/api/bots/${id}/crew`),
+ persona: (id: string) => get<{ persona: string }>(`/api/bots/${id}/persona`),
+ setPersona: (id: string, persona: string) => put<{ ok: boolean }>(`/api/bots/${id}/persona`, { persona }),
+ permissions: (id: string) => get<{ permissions: BotPermissionsFile }>(`/api/bots/${id}/permissions`),
+ setPermissions: (id: string, body: { tier?: string; permissions?: BotPermissionsFile }) =>
+ put<{ permissions: BotPermissionsFile }>(`/api/bots/${id}/permissions`, body),
+ start: (id: string) => post<{ ok: boolean; resumed: number; message: string }>(`/api/bots/${id}/start`),
+ run: (id: string, routine?: string) => post<{ accepted: boolean; jobId?: string; reasonCode?: string }>(`/api/bots/${id}/run`, { routine }),
+ outputs: () => get<{ outputs: DeliverableInfo[] }>("/api/bots/outputs"),
+ botOutputs: (id: string) => get<{ outputs: DeliverableInfo[] }>(`/api/bots/${id}/outputs`),
+ outputPreview: (id: string, name: string) =>
+ get<{ preview: string; truncated: boolean }>(`/api/bots/${id}/outputs/${encodeURIComponent(name)}/preview`),
+ outputDownloadUrl: (id: string, name: string) => `/api/bots/${id}/outputs/${encodeURIComponent(name)}/download`,
+ deleteOutput: (id: string, name: string) => del<{ ok: boolean }>(`/api/bots/${id}/outputs/${encodeURIComponent(name)}`),
+ bundleUrl: (id: string) => `/api/bots/${id}/bundle`,
+ importBundle: (bundle: unknown) => post<{ report: { created: string[]; skipped: string[] } }>("/api/bots/import?overwrite=0", bundle),
},
};
diff --git a/ui/src/pages/Bots.tsx b/ui/src/pages/Bots.tsx
index 56809b97..13f76a3b 100644
--- a/ui/src/pages/Bots.tsx
+++ b/ui/src/pages/Bots.tsx
@@ -1,16 +1,16 @@
-import { useEffect, useState, useCallback } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
-import { Bot, Plus, Send, RefreshCw, Trash2, Play, Pause, RotateCcw, RotateCw, AlertTriangle } from "lucide-react";
+import { Bot, Plus, RefreshCw, AlertTriangle, Crown, Users, Package } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Textarea } from "@/components/ui/textarea";
-import {
- Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
-} from "@/components/ui/dialog";
+import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { cn, formatDate } from "@/lib/utils";
-import api, { type BotStatus, type BotManifest, type BotRunRecord, type BotDlqEntry } from "@/lib/api";
+import api, { type BotStatus, type BotRunRecord, type BotDlqEntry, type BotManifest } from "@/lib/api";
+import { useBotEvents } from "@/components/bots/useBotEvents";
+import { BotDetail } from "@/components/bots/BotDetail";
+import { OnboardWizard } from "@/components/bots/OnboardWizard";
+import { DeliverablesList } from "@/components/bots/DeliverablesList";
const fadeUp = {
hidden: { opacity: 0, y: 12 },
@@ -28,23 +28,20 @@ const STATE_STYLES: Record<string, { label: string; className: string }> = {
idle: { label: "⚪ Idle", className: "bg-muted text-muted-foreground" },
};
-function Skeleton({ className }: { className?: string }) {
- return <div className={cn("animate-pulse rounded-lg bg-muted", className)} />;
-}
-
+/**
+ * "Mercury Bots" — the full fleet cockpit: live roster (fleet nesting), bot
+ * panels, the deliverables inbox, and onboarding with executable tiers.
+ */
export function BotsPage() {
const [botsList, setBotsList] = useState<BotStatus[]>([]);
const [loading, setLoading] = useState(true);
const [available, setAvailable] = useState(true);
- const [selected, setSelected] = useState<string | null>(null);
- const [detail, setDetail] = useState<{ bot: BotManifest; journal: BotRunRecord[]; inbox: unknown[] } | null>(null);
- const [dlq, setDlq] = useState<BotDlqEntry[]>([]);
- const [message, setMessage] = useState("");
- const [creating, setCreating] = useState(false);
- const [newId, setNewId] = useState("");
- const [newName, setNewName] = useState("");
- const [newDescription, setNewDescription] = useState("");
- const [error, setError] = useState<string | null>(null);
+ const [detail, setDetail] = useState<{ bot: BotManifest; state: BotStatus | null; journal: BotRunRecord[]; inbox: unknown[] } | null>(null);
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const [wizardOpen, setWizardOpen] = useState(false);
+ const [newInFleet, setNewInFleet] = useState<"solo" | { leadId: string }>("solo");
+ const [liveBanner, setLiveBanner] = useState<string | null>(null);
+ const live = useBotEvents();
const refresh = useCallback(async () => {
try {
@@ -58,80 +55,131 @@ export function BotsPage() {
}
}, []);
- const openDetail = useCallback(async (id: string) => {
- setSelected(id);
+ const openBot = useCallback(async (id: string) => {
+ setSelectedId(id);
try {
- const [detail, dlqData] = await Promise.all([api.bots.get(id), api.bots.dlq(id)]);
- setDetail(detail);
- setDlq(dlqData.dlq);
- } catch (err) {
- setError(String(err));
- }
+ const d = await api.bots.get(id);
+ setDetail(d);
+ } catch {}
}, []);
useEffect(() => {
void refresh();
- const t = setInterval(() => void refresh(), 4000); // live roster states
+ const t = setInterval(() => void refresh(), 4000); // fallback: SSE rides live activity
return () => clearInterval(t);
}, [refresh]);
- const sendMessage = async () => {
- if (!selected || !message.trim()) return;
- try {
- const result = await api.bots.message(selected, message.trim());
- if (result.accepted) {
- setMessage("");
- setTimeout(() => void openDetail(selected), 400);
- } else {
- setError(`Rejected: ${result.reasonCode}`);
- }
- } catch (err) {
- setError(String(err));
- }
- };
-
- const createBot = async () => {
- try {
- await api.bots.create({ id: newId.toLowerCase(), name: newName, description: newDescription || undefined });
- setCreating(false);
- setNewId(""); setNewName(""); setNewDescription("");
- void refresh();
- } catch (err) {
- setError(String(err));
+ // Live deliverable banner + inbox refresh
+ useEffect(() => {
+ if (live.lastDelivery) {
+ const name = live.lastDelivery.name;
+ setLiveBanner(`${live.lastDelivery.botId} delivered ${name}`);
+ const t = setTimeout(() => setLiveBanner(null), 6000);
+ return () => clearTimeout(t);
}
+ }, [live.lastDelivery?.at, live.lastDelivery?.name, live.lastDelivery?.botId]);
+
+ const botNames = useMemo(() => Object.fromEntries(botsList.map((b) => [b.id, b.name])), [botsList]);
+
+ // Fleet-first grouping: leads with nested crew, then solos, then crew orphans sorted after
+ const grouped = useMemo(() => {
+ const leads = botsList.filter((b) => b.fleetRole === "lead");
+ const crews = botsList.filter((b) => b.fleetRole === "crew");
+ const solos = botsList.filter((b) => !b.fleetRole);
+ return { leads, crews, solos };
+ }, [botsList]);
+
+ const BotCard = ({ id, idx }: { id: string; idx: number }) => {
+ const bot = botsList.find((b) => b.id === id);
+ if (!bot) return null;
+ const liveLabel = live.activity[bot.id];
+ // Crew members live inside their lead's card — render only on demand here.
+ if (bot.fleetRole === "crew") return null;
+ const crewCount = bot.fleetRole === "lead" ? grouped.crews.filter((c) => c.parent === bot.id).length : 0;
+ return (
+ <motion.div key={bot.id} custom={idx} variants={fadeUp} initial="hidden" animate="visible">
+ <Card className={cn("cursor-pointer transition-colors hover:border-primary/50", bot.needsYou && "border-yellow-500/40")}>
+ <CardHeader className="pb-2" onClick={() => void openBot(bot.id)}>
+ <div className="flex items-center justify-between">
+ <CardTitle className="flex items-center gap-2 text-base">
+ <Bot className="h-4 w-4" /> {bot.name}
+ {bot.fleetRole === "lead" && <Badge variant="secondary" className="text-yellow-500"><Crown className="h-3 w-3" /> lead</Badge>}
+ {crewCount > 0 && <Badge variant="secondary"><Users className="h-3 w-3" /> {crewCount}</Badge>}
+ </CardTitle>
+ <Badge variant="secondary" className={STATE_STYLES[bot.state]?.className}>
+ {STATE_STYLES[bot.state]?.label ?? bot.state}
+ </Badge>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-2 text-sm" onClick={() => void openBot(bot.id)}>
+ {liveLabel && (
+ <p className="flex items-center gap-1.5 text-emerald-400 truncate">
+ <span className="inline-block h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse" />
+ {liveLabel}
+ </p>
+ )}
+ {bot.fleetRole === "lead" && (
+ <p className="text-muted-foreground">
+ {grouped.crews.filter((c) => c.parent === bot.id).map((c) => {
+ const cl = live.activity[c.id];
+ return (
+ <span key={c.id} className="inline-flex items-center gap-1 mr-2">
+ ↳ {c.name}
+ {cl && <span className="text-emerald-400"> {cl.slice(0, 30)}</span>}
+ {c.needsYou && <AlertTriangle className="h-3 w-3 text-yellow-500" />}
+ </span>
+ );
+ })}
+ </p>
+ )}
+ {!liveLabel && bot.needsYou && (
+ <p className="flex items-center gap-1 text-yellow-500"><AlertTriangle className="h-3.5 w-3.5" /> Needs you — check Ops → DLQ</p>
+ )}
+ {!liveLabel && bot.lastRunAt && (
+ <p className="text-muted-foreground">Last run {formatDate(bot.lastRunAt)} · {bot.lastRunState}</p>
+ )}
+ </CardContent>
+ </Card>
+ </motion.div>
+ );
};
- const toggleEnabled = async (bot: BotStatus) => {
- await (bot.enabled ? api.bots.disable(bot.id) : api.bots.enable(bot.id));
- void refresh();
- };
-
- const replay = async (entry: BotDlqEntry) => {
- try {
- await api.bots.replay(entry.botId, entry.id);
- if (selected) void openDetail(selected);
- } catch (err) {
- setError(String(err));
- }
- };
+ const openBotDetail = detail && selectedId
+ ? botsList.find((b) => b.id === selectedId)
+ ? { ...detail, bot: detail.bot }
+ : null
+ : null;
return (
<div className="space-y-6 p-6">
<div className="flex items-center justify-between">
<div>
- <h1 className="text-2xl font-semibold flex items-center gap-2"><Bot className="h-6 w-6" /> Bots</h1>
+ <h1 className="text-2xl font-semibold flex items-center gap-2">
+ <Bot className="h-6 w-6" /> Mercury Bots
+ <span
+ className={cn(
+ "inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full border",
+ live.connected ? "text-emerald-500 border-emerald-500/40" : "text-muted-foreground border-muted",
+ )}
+ >
+ <span className={cn("inline-block h-1.5 w-1.5 rounded-full", live.connected ? "bg-emerald-400" : "bg-muted-foreground")} />
+ {live.connected ? "live" : "reconnecting…"}
+ </span>
+ </h1>
<p className="text-sm text-muted-foreground">
- Persistent persona-scoped agents — own model, memory, and permissions; run outside the main conversation.
+ Persistent persona-scoped agents — own model, memory, and permissions; run outside the main conversation. Deliverables land in their outputs zone.
</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => void refresh()}><RefreshCw className="h-4 w-4" /> Refresh</Button>
- <Button size="sm" onClick={() => setCreating(true)}><Plus className="h-4 w-4" /> Onboard bot</Button>
+ <Button size="sm" onClick={() => { setNewInFleet("solo"); setWizardOpen(true); }}><Plus className="h-4 w-4" /> Onboard bot</Button>
</div>
</div>
- {error && (
- <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive">{error}</div>
+ {liveBanner && (
+ <div className="rounded-lg border border-primary/40 bg-primary/10 px-4 py-2 text-sm flex items-center gap-2">
+ <Package className="h-4 w-4" /> <b>Delivered:</b> {liveBanner}
+ </div>
)}
{!available && (
@@ -140,162 +188,53 @@ export function BotsPage() {
</CardContent></Card>
)}
- {loading ? (
- <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
- {[0, 1, 2].map(i => <Skeleton key={i} className="h-28" />)}
- </div>
- ) : botsList.length === 0 ? (
- <Card><CardContent className="py-8 text-center text-muted-foreground">
- No bots configured yet. Onboard one to get started.
- </CardContent></Card>
- ) : (
- <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
- {botsList.map((bot, i) => (
- <motion.div key={bot.id} custom={i} variants={fadeUp} initial="hidden" animate="visible">
- <Card
- className="cursor-pointer transition-colors hover:border-primary/50"
- onClick={() => void openDetail(bot.id)}
- >
- <CardHeader className="pb-2">
- <div className="flex items-center justify-between">
- <CardTitle className="flex items-center gap-2 text-base">
- <Bot className="h-4 w-4" /> {bot.name}
- </CardTitle>
- <Badge variant="secondary" className={STATE_STYLES[bot.state]?.className}>
- {STATE_STYLES[bot.state]?.label ?? bot.state}
- </Badge>
- </div>
- </CardHeader>
- <CardContent className="space-y-2 text-sm">
- {bot.activity && <p className="text-muted-foreground truncate">↳ {bot.activity}</p>}
- {bot.needsYou && (
- <p className="flex items-center gap-1 text-yellow-500"><AlertTriangle className="h-3.5 w-3.5" /> Needs you — see DLQ</p>
- )}
- {bot.lastRunAt && (
- <p className="text-muted-foreground">Last run {formatDate(bot.lastRunAt)} · {bot.lastRunState}</p>
- )}
- </CardContent>
- </Card>
- </motion.div>
- ))}
- </div>
- )}
-
- {/* Detail dialog: config, send, journal, DLQ */}
- <Dialog open={!!selected} onOpenChange={(o) => { if (!o) { setSelected(null); setDetail(null); } }}>
- <DialogContent className="max-h-[80vh] max-w-2xl overflow-y-auto">
- {detail && (
- <>
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <Bot className="h-5 w-5" /> {detail.bot.name} <span className="text-muted-foreground text-sm">({detail.bot.id})</span>
- </DialogTitle>
- <DialogDescription>{detail.bot.description ?? "Mercury bot"}</DialogDescription>
- </DialogHeader>
- <div className="space-y-4">
- <div className="flex flex-wrap gap-2 text-sm">
- <Badge variant="secondary">model: {detail.bot.model?.provider ?? "inherit"}{detail.bot.model?.model ? `:${detail.bot.model.model}` : ""}</Badge>
- <Badge variant="secondary">memory: {detail.bot.memory?.scope ?? "own"}</Badge>
- {detail.bot.autonomy?.dailyTokenBudget && <Badge variant="secondary">budget: {detail.bot.autonomy.dailyTokenBudget}/day</Badge>}
- {(detail.bot.comms?.canMessage?.length ?? 0) > 0 && <Badge variant="secondary">→ {detail.bot.comms!.canMessage!.join(", ")}</Badge>}
- </div>
-
- {(detail.bot.schedules?.length ?? 0) > 0 && (
- <div className="text-sm">
- <p className="font-medium mb-1">Routines</p>
- {detail.bot.schedules!.map(s => (
- <p key={s.name} className="text-muted-foreground">⏰ {s.name} — <code>{s.cron}</code></p>
- ))}
- </div>
- )}
-
- <div className="space-y-2">
- <Textarea
- placeholder={`Message ${detail.bot.name}… (runs outside the main conversation)`}
- value={message}
- onChange={(e) => setMessage(e.target.value)}
- rows={3}
- />
- <div className="flex gap-2">
- <Button size="sm" onClick={() => void sendMessage()} disabled={!message.trim()}>
- <Send className="h-3.5 w-3.5" /> Send
- </Button>
- <Button
- size="sm" variant="outline"
- onClick={async () => { await (detail.bot.enabled ? api.bots.disable(detail.bot.id) : api.bots.enable(detail.bot.id)); void openDetail(detail.bot.id); void refresh(); }}
- >
- {detail.bot.enabled ? <><Pause className="h-3.5 w-3.5" /> Disable</> : <><Play className="h-3.5 w-3.5" /> Enable</>}
- </Button>
- <Button size="sm" variant="outline" onClick={async () => { await api.bots.stop(detail.bot.id); void openDetail(detail.bot.id); }}>
- Stop
- </Button>
- </div>
- </div>
-
- <div>
- <p className="font-medium text-sm mb-2">Recent runs</p>
- {detail.journal.length === 0 ? (
- <p className="text-sm text-muted-foreground">No runs yet.</p>
- ) : (
- <div className="space-y-1.5">
- {[...detail.journal].reverse().map(r => (
- <div key={r.runId} className="flex items-center gap-2 text-sm">
- <Badge variant="secondary" className={
- r.state === "completed" ? "bg-emerald-500/15 text-emerald-500"
- : r.state === "failed" ? "bg-red-500/15 text-red-500"
- : "bg-yellow-500/15 text-yellow-500"
- }>{r.state}</Badge>
- <span className="text-muted-foreground">{r.trigger}</span>
- <span>{(r.durationMs / 1000).toFixed(1)}s</span>
- <span className="text-muted-foreground">{r.tokensIn + r.tokensOut} tok</span>
- {r.reasonCode && <span className="text-red-500">[{r.reasonCode}]</span>}
- </div>
- ))}
- </div>
- )}
- </div>
-
- {dlq.length > 0 && (
- <div>
- <p className="font-medium text-sm mb-2 flex items-center gap-1"><AlertTriangle className="h-4 w-4 text-yellow-500" /> Dead-lettered jobs</p>
- <div className="space-y-1.5">
- {dlq.map(e => (
- <div key={e.id} className="flex items-center gap-2 text-sm">
- <span className="text-muted-foreground font-mono">{e.id}</span>
- <span className="text-red-500">[{e.reasonCode ?? "unknown"}]</span>
- <span className="text-muted-foreground truncate flex-1">{e.prompt.slice(0, 60)}</span>
- <Button size="sm" variant="ghost" onClick={() => void replay(e)}><RotateCw className="h-3.5 w-3.5" /> Replay</Button>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- </>
+ <Tabs defaultValue="fleet">
+ <TabsList>
+ <TabsTrigger value="fleet">Fleet</TabsTrigger>
+ <TabsTrigger value="outputs">
+ <Package className="h-3.5 w-3.5 mr-1" /> Deliverables
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="fleet" className="mt-4">
+ {loading ? (
+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
+ {[0, 1, 2].map((i) => <div key={i} className="animate-pulse rounded-lg bg-muted h-28" />)}
+ </div>
+ ) : !available || botsList.length === 0 ? (
+ <Card><CardContent className="py-8 text-center text-muted-foreground">
+ No bots configured yet. Onboard one to get started.
+ </CardContent></Card>
+ ) : (
+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
+ {grouped.leads.map((_, i) => <BotCard key={i} id={grouped.leads[i].id} idx={i} />)}
+ {grouped.solos.map((b, i) => <BotCard key={b.id} id={b.id} idx={i} />)}
+ </div>
)}
- </DialogContent>
- </Dialog>
+ </TabsContent>
+
+ <TabsContent value="outputs" className="mt-4">
+ <DeliverablesList botNames={botNames} lastDelivery={live.lastDelivery} />
+ </TabsContent>
+ </Tabs>
+
+ {openBotDetail && (
+ <BotDetail
+ bot={detail}
+ live={live}
+ open={!!selectedId}
+ onOpenChange={(o) => { if (!o) { setSelectedId(null); setDetail(null); } }}
+ onChanged={() => { void refresh(); if (selectedId) void openBot(selectedId); }}
+ />
+ )}
- {/* Onboard dialog */}
- <Dialog open={creating} onOpenChange={setCreating}>
- <DialogContent className="max-w-md">
- <DialogHeader>
- <DialogTitle>Onboard a bot</DialogTitle>
- <DialogDescription>
- Fail-closed defaults: dangerous tools denied, memory scope own, only its own directory writable. Refine in the profile files afterwards.
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-3">
- <Input placeholder="id (lowercase, e.g. researcher)" value={newId} onChange={e => setNewId(e.target.value)} />
- <Input placeholder="Name (e.g. Research)" value={newName} onChange={e => setNewName(e.target.value)} />
- <Input placeholder="Description (optional)" value={newDescription} onChange={e => setNewDescription(e.target.value)} />
- </div>
- <DialogFooter>
- <Button variant="outline" onClick={() => setCreating(false)}>Cancel</Button>
- <Button onClick={() => void createBot()} disabled={!newId || !newName}><Trash2 className="hidden" /> Create</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <OnboardWizard
+ open={wizardOpen}
+ onOpenChange={setWizardOpen}
+ leads={grouped.leads.map((l) => ({ id: l.id, name: l.name } as BotManifest))}
+ crewAsLeadId={newInFleet === "solo" ? undefined : newInFleet.leadId}
+ onCreated={() => void refresh()}
+ />
</div>
);
}
\ No newline at end of file