Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(bots): web fleet step mirrors the TUI — solo / lead auto-build / lead manual
Salman Qureshi6cf533c5e01d
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex adcfbacd..fd88566b 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -13,6 +13,7 @@ import { BotStore, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronEximport { BotJournal } from './journal.js';import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';import { sweepSharedSandbox } from './retention.js';+import { proposeCrew } from './fleet-onboarding.js';import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';import { createBotSendTool } from './tools/bot-send.js';import { createBotDeliverTool } from './tools/bot-deliver.js';@@ -817,6 +818,55 @@ export class BotManager {* Persona refinement (builder) is the caller's concern (async provider* call); addCrew writes the persona text it is given.*/+ /** Promote a bot to fleet lead (the cockpit's "lead a fleet" paths). Idempotent. */+ promoteLead(botId: string): { ok: boolean } {+ const manifest = this.store.get(botId);+ if (!manifest) return { ok: false };+ if (manifest.fleetRole !== 'lead') {+ this.store.update(botId, m => { m.fleetRole = 'lead'; });+ this.invalidateRuntime(botId);+ logger.info({ botId }, 'Bot promoted to fleet lead');+ }+ return { ok: true };+ }++ /**+ * Fleet auto-build (the TUI onboarding's "auto" path, shared with the web+ * cockpit): one LLM call proposes 3-5 matched specialists, each created+ * through the standard addCrew path. DETACHED — the caller hears 202+ * immediately; per-member progress rides `hooks`, and failures degrade to+ * "lead with an empty crew" guidance, never an error state.+ */+ autoCrew(botId: string, hooks: { onMember?: (name: string, id: string) => void; onError?: (msg: string) => void; onDone?: (created: number) => void } = {}): void {+ void (async () => {+ try {+ const manifest = this.store.get(botId);+ if (!manifest) return;+ if (manifest.fleetRole !== 'lead') this.promoteLead(botId);+ const persona = this.store.readPersona(botId);+ const leadDescription = manifest.description ?? '';+ const proposals = await proposeCrew(manifest.name, leadDescription, persona, resolveProvider(this.providers, manifest), this.maxCrew());+ if (proposals.length === 0) {+ hooks.onError?.("Crew proposal unavailable (provider) — the lead has an empty crew. Add specialists yourself, or give the lead a task and tell it to hire its own crew (bot_spawn).");+ return;+ }+ let created = 0;+ for (const p of proposals) {+ const result = this.addCrew(botId, p);+ if (result.ok) {+ created++;+ hooks.onMember?.(p.name, result.manifest.id);+ } else {+ hooks.onError?.(`Crew member ${p.name} (${p.id}): ${result.error}`);+ }+ }+ hooks.onDone?.(created);+ } catch (err: any) {+ hooks.onError?.(`Fleet auto-build failed: ${err?.message ?? err} — the lead has an empty crew; add specialists yourself later.`);+ }+ })();+ }+addCrew(leadId: string, spec: { id: string; name: string; description?: string; persona?: string }): { ok: true; manifest: BotManifest } | { ok: false; error: string } {const lead = this.store.get(leadId);if (!lead) return { ok: false, error: `No bot "${leadId}"` };diff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.tsindex 63867455..fb047b6e 100644--- a/src/web/api/bots.test.ts+++ b/src/web/api/bots.test.ts@@ -135,6 +135,25 @@ describe('web bots API — cockpit', () => {expect(after.outputs).toHaveLength(0);});+ it('promote makes the bot a fleet lead (TUI-parity fleet semantics)', async () => {+ store.create({ id: 'solo', name: 'Solo' });+ const res = await app.request('/api/bots/solo/promote', { method: 'POST' });+ expect(res.status).toBe(200);+ expect(store.get('solo')?.fleetRole).toBe('lead');+ // Idempotent — no error on a second promote+ expect((await app.request('/api/bots/solo/promote', { method: 'POST' })).status).toBe(200);+ expect((await app.request('/api/bots/ghost/promote', { method: 'POST' })).status).toBe(404);+ });++ it('autocrew accepts detached (202) and the degraded path leaves a lead with helpful guidance', async () => {+ await app.request('/api/bots', { method: 'POST', body: JSON.stringify({ id: 'leadish', name: 'Lead', persona: '# persona for the fleet' }), headers: { 'Content-Type': 'application/json' } });+ const res = await app.request('/api/bots/leadish/autocrew', { method: 'POST' });+ expect(res.status).toBe(202);+ // Detached — the proposal runs in the background; errors (unusable stub+ // provider output) must degrade to guidance, never throw.+ expect(store.get('leadish')?.fleetRole).toBe('lead');+ });+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' } });diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex 3f009c50..a87441c0 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -66,6 +66,17 @@ app.post('/api/bots', async (c: any) => {// 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.++/** Open fleet-feed clients — roster mutations (add crew, promote, delete) push fresh snapshots. */+const rosterSseClients = new Set<{ send: (event: string, data: unknown) => void }>();++function broadcastRoster(): void {+ if (!botManager) return;+ for (const client of rosterSseClients) {+ client.send('bot_roster', { bots: botManager.getStatusSummaries(), queue: botManager.queue.counts() });+ }+}+app.get('/api/bots/events', (c: any) => {const bm = botManager;if (!bm) return c.json({ error: 'Bots not available' }, 400);@@ -73,18 +84,19 @@ app.get('/api/bots/events', (c: any) => {start(controller) {const encoder = new TextEncoder();const controllerRef = controller;- const send = (event: string, data: unknown) => {+ const client = { 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() });+ client.send('bot_roster', { bots: bm.getStatusSummaries(), queue: bm.queue.counts() });+ rosterSseClients.add(client);- const unsubscribe = bm.onBotActivity((ev) => send('bot_activity', ev));+ const unsubscribe = bm.onBotActivity((ev) => client.send('bot_activity', ev));const keepalive = setInterval(() => {try { controller.enqueue(encoder.encode(': keepalive\n\n')); } catch { clearInterval(keepalive); }@@ -93,6 +105,7 @@ app.get('/api/bots/events', (c: any) => {c.req.raw.signal?.addEventListener('abort', () => {clearInterval(keepalive);unsubscribe();+ rosterSseClients.delete(client);});},cancel() {},@@ -253,6 +266,39 @@ app.post('/api/bots/:id/start', (c: any) => {}});+// Fleet semantics — the CLI parity paths (§2.5 / agent.ts offerFleetStep):+// promote → lead; auto-build the matched crew detached with live roster+// broadcasts (30-90s of LLM proposal — the dashboard shows crew cards the+// moment each is created).+app.post('/api/bots/:id/promote', (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 result = botManager.promoteLead(id);+ if (!result.ok) return c.json({ error: 'Bot not found' }, 404);+ broadcastRoster();+ return c.json({ ok: true, message: 'Bot is now a fleet lead — it can add/retire crew itself (bot_spawn), or you add specialists from its Ops panel.' });+});++app.post('/api/bots/:id/autocrew', (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 bm = botManager;+ bm.autoCrew(id, {+ onMember: (_name, _memberId) => broadcastRoster(),+ onError: (msg) => {+ for (const client of rosterSseClients) client.send('bot_notice', { message: msg });+ broadcastRoster();+ },+ onDone: () => {+ for (const client of rosterSseClients) client.send('bot_notice', { message: `Fleet ready — ${bm.getStatusSummaries().filter((s) => s.parent === id).length} crew member(s) created. Dispatch tasks to any crew bot.` });+ broadcastRoster();+ },+ });+ return c.json({ accepted: true, status: 'building' }, 202);+});+// Fire a routine now (body { routine }) or send a bare wake turnapp.post('/api/bots/:id/run', async (c: any) => {if (!botManager) return c.json({ error: 'Bots not available' }, 400);diff --git a/ui/src/components/bots/BotDetail.tsx b/ui/src/components/bots/BotDetail.tsxindex a9fec4d0..ac0869e1 100644--- a/ui/src/components/bots/BotDetail.tsx+++ b/ui/src/components/bots/BotDetail.tsx@@ -1,7 +1,7 @@import { useCallback, useEffect, useState } from "react";import {Bot, Send, Pause, Play, Square, RotateCw, AlertTriangle, Crown, Shield,- Download, Package, Clock, Save, RefreshCw,+ Download, Package, Clock, Save, RefreshCw, Users,} from "lucide-react";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";@@ -9,6 +9,7 @@ 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import {Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription,} from "@/components/ui/dialog";@@ -52,6 +53,10 @@ export function BotDetail({const [perms, setPerms] = useState<BotPermissionsFile | null>(null);const [permText, setPermText] = useState("");const [permState, setPermState] = useState<"clean" | "dirty" | "saved" | "error">("clean");+ const [crewId, setCrewId] = useState("");+ const [crewName, setCrewName] = useState("");+ const [crewPersona, setCrewPersona] = useState("");+ const [crewTier, setCrewTier] = useState("inherit");const loadJournal = useCallback(async () => {if (!id) return;@@ -263,6 +268,34 @@ export function BotDetail({</TabsContent><TabsContent value="ops" className="space-y-4 mt-3">+ {m.fleetRole === "lead" && (+ <div className="space-y-1.5">+ <p className="font-medium text-sm">Add crew member</p>+ <p className="text-xs text-muted-foreground">Fail-closed specialist under this lead (gets the lead's permissions unless tiered here).</p>+ <div className="grid grid-cols-2 gap-2">+ <Input placeholder="id (lowercase)" value={crewId} onChange={(e) => setCrewId(e.target.value)} />+ <Input placeholder="Name" value={crewName} onChange={(e) => setCrewName(e.target.value)} />+ </div>+ <Textarea className="text-xs" rows={2} placeholder="Persona (optional)" value={crewPersona} onChange={(e) => setCrewPersona(e.target.value)} />+ <div className="flex items-center gap-2">+ <Button size="sm" variant="outline" onClick={async () => {+ if (!crewId || !crewName) return;+ await api.bots.addCrewFull(id, { id: crewId.toLowerCase(), name: crewName, persona: crewPersona || undefined, tier: crewTier });+ setCrewId(""); setCrewName(""); setCrewPersona("");+ onChanged();+ }} disabled={!crewId || !crewName}>+ <Users className="h-3.5 w-3.5" /> Add to crew+ </Button>+ <Select value={crewTier} onValueChange={setCrewTier}>+ <SelectTrigger className="h-9 w-40 text-xs"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectItem value="inherit">inherit lead's permissions</SelectItem>+ {tiers.map((t) => <SelectItem key={t.id} value={t.id}>{t.label}</SelectItem>)}+ </SelectContent>+ </Select>+ </div>+ </div>+ )}<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</>}diff --git a/ui/src/components/bots/OnboardWizard.tsx b/ui/src/components/bots/OnboardWizard.tsxindex 55e43e45..3ad6d41a 100644--- a/ui/src/components/bots/OnboardWizard.tsx+++ b/ui/src/components/bots/OnboardWizard.tsx@@ -43,7 +43,7 @@ export function OnboardWizard({const [provider, setProvider] = useState<string>("inherit");const [model, setModel] = useState<string>("");const [budget, setBudget] = useState<string>("");- const [crewOf, setCrewOf] = useState<string>(crewAsLeadId ?? "solo");+ const [fleet, setFleet] = useState<string>("solo");const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);@@ -51,7 +51,7 @@ export function OnboardWizard({if (!open) return;setStep(0); setId(""); setName(""); setDescription(""); setPersona("");setTier("readonly"); setProvider("inherit"); setModel(""); setBudget("");- setCrewOf(crewAsLeadId ?? "solo"); setError(null);+ setFleet("solo"); setError(null);api.bots.tiers().then(({ tiers }) => setTiers(tiers)).catch(() => setTiers([]));}, [open, crewAsLeadId]);@@ -62,8 +62,8 @@ export function OnboardWizard({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:/, ""), {+ if (fleet === "crewman" && crewAsLeadId) {+ bot = (await api.bots.addCrewFull(crewAsLeadId, {id: id.toLowerCase(), name, description: description || undefined, persona: persona || undefined, tier,})).bot;} else {@@ -72,6 +72,13 @@ export function OnboardWizard({tier, manifest: manifestPatch as never,});bot = res.bot;+ if (fleet === "leadauto") {+ // TUI parity: auto-build runs detached (30-90s LLM proposal); the+ // roster broadcasts crew members live as they land.+ void api.bots.autocrew(bot.id);+ } else if (fleet === "leadman") {+ void api.bots.promote(bot.id);+ }}onCreated(bot);onOpenChange(false);@@ -83,9 +90,7 @@ export function OnboardWizard({};const canNext = step === 0 ? !!id && !!name : step === 3 ? true : true;- const targetCrewLead = crewAsLeadId- ? crewAsLeadId- : crewOf !== "solo" ? crewOf.replace(/^lead:/, "") : null;+ const targetCrewLead = crewAsLeadId ?? null;return (<Dialog open={open} onOpenChange={onOpenChange}>@@ -163,37 +168,28 @@ export function OnboardWizard({{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+ <p className="text-xs text-muted-foreground">Crew options match the TUI onboarding exactly.</p>+ {[+ { key: "solo", title: "Solo bot", desc: "Works independently — no sub-bots.", icon: Network },+ crewAsLeadId+ ? { key: "crewman", title: `Crew member of ${crewAsLeadId}`, desc: "Joins this lead; inherits the lead's permissions unless a tier above was picked.", icon: Users }+ : { key: "leadauto", title: "Lead a fleet — auto-build the crew", desc: "Mercury proposes 3-5 matched specialists (an LLM call) and creates them in the background; they appear live on the roster.", icon: Crown },+ { key: "leadman", title: "Lead a fleet — I'll add crew myself", desc: "Becomes a lead now (gets bot_spawn) — add specialists later from its Ops panel, or tell it to hire its own crew.", icon: Crown },+ ].map((opt) => {+ const Icon = opt.icon;+ const active = fleet === opt.key;+ return (+ <Card key={opt.key} className={cn("cursor-pointer", active ? "border-primary" : "hover:border-primary/50")} onClick={() => setFleet(opt.key)}>+ <CardContent className="py-3 flex items-start gap-2 text-sm">+ <Icon className={cn("h-4 w-4 mt-0.5", opt.key.startsWith("lead") ? "text-yellow-500" : "")} />+ <span>+ <b>{opt.title}</b>+ <p className="text-xs text-muted-foreground">{opt.desc}</p>+ </span></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>)}@@ -206,7 +202,7 @@ export function OnboardWizard({<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"}+ {busy ? "Creating…" : fleet === "leadman" ? "Create lead (add crew later)" : fleet === "leadauto" ? "Create & auto-build crew" : "Create bot"}</Button>)}</DialogFooter>diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.tsindex 6f5ab3eb..b1ad77bc 100644--- a/ui/src/lib/api.ts+++ b/ui/src/lib/api.ts@@ -902,6 +902,8 @@ const api = {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),+ promote: (id: string) => post<{ ok: boolean; message: string }>(`/api/bots/${id}/promote`),+ autocrew: (id: string) => post<{ accepted: boolean; status: string }>(`/api/bots/${id}/autocrew`),crew: (id: string) =>get<{ lead: BotManifest; crew: BotManifest[]; maxCrew: number }>(`/api/bots/${id}/crew`),persona: (id: string) => get<{ persona: string }>(`/api/bots/${id}/persona`),