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): fleets — lead bots + crew (hierarchy architecture)

Salman Qureshi82eb5a42b776
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.ts
index 7d056688..6dcd99f4 100644
--- a/src/bots/bot-manager.test.ts
+++ b/src/bots/bot-manager.test.ts
@@ -645,3 +645,99 @@ describe('Bot skill access (native + own library)', () => {
});
});
});
+
+describe('Bot fleets (lead + crew)', () => {
+ let root: string;
+ let store: BotStore;
+ let manager: BotManager;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-fleet-'));
+ store = new BotStore(join(root, 'bots'));
+ manager = makeManager(root);
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ function setupFleet() {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ manager.addCrew('ceo', { id: 'researcher', name: 'Researcher', description: 'Research', persona: '# Researcher\n\nStudies markets.' });
+ manager.addCrew('ceo', { id: 'writer', name: 'Writer', persona: '# Writer\n\nWrites copy.' });
+ }
+
+ function runtimeFor(id: string) {
+ return (manager as unknown as { getOrCreateRuntime(id: string, m: BotManifest): { tools: Record<string, any> } }).getOrCreateRuntime(id, store.get(id)!);
+ }
+
+ it('addCrew enforces the lead relationship, the crew cap, and fail-closed defaults', () => {
+ setupFleet();
+ expect(store.get('researcher')?.fleetRole).toBe('crew');
+ expect(store.get('researcher')?.parent).toBe('ceo');
+ expect(store.get('researcher')?.comms?.canMessage).toEqual(['ceo']);
+ for (let i = 0; i < 4; i++) manager.addCrew('ceo', { id: `extra${i}`, name: `Extra${i}` });
+ expect(manager.addCrew('ceo', { id: 'over-cap', name: 'Over' })).toMatchObject({ ok: false });
+ store.create({ id: 'solo-bot', name: 'Solo' });
+ expect(manager.addCrew('solo-bot', { id: 'x', name: 'X' })).toMatchObject({ ok: false }); // not a lead
+ expect(manager.addCrew('ceo', { id: 'researcher', name: 'Dup' })).toMatchObject({ ok: false }); // exists
+ });
+
+ it('delegated tasks return results to the lead mailbox (attributed)', async () => {
+ mockedGenerateText.mockResolvedValue({ text: 'MARKET REPORT: all clear', finishReason: 'stop', usage: { inputTokens: 5, outputTokens: 5 } } as any);
+ setupFleet();
+ // Spy on delivery: the lead's wake turn would drain the mailbox before we
+ // can peek — the sendToBot call itself is the observable contract.
+ const sendSpy = vi.spyOn(manager, 'sendToBot');
+ const dispatch = manager.dispatchTask('researcher', 'ceo', 'Study the market');
+ expect(dispatch.accepted).toBe(true);
+ await vi.waitFor(() => {
+ expect(sendSpy).toHaveBeenCalledWith('ceo', 'researcher', expect.stringContaining('MARKET REPORT'));
+ });
+ sendSpy.mockRestore();
+ });
+
+ it('plain mailbox mail never triggers a result reply (no ping-pong)', async () => {
+ mockedGenerateText.mockResolvedValue({ text: 'noted', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any);
+ setupFleet();
+ manager.sendToBot('researcher', 'ceo', 'fyi only, no action');
+ await vi.waitFor(() => expect(manager.getJournal('researcher').length).toBe(1));
+ await new Promise(r => setTimeout(r, 50)); // let any detached follow-up turns settle
+ expect(manager.peekMailbox('ceo')).toHaveLength(0);
+ });
+
+ it('leads get fleet tools; bot_spawn/bot_retire manage the crew within the cap', async () => {
+ mockedGenerateText.mockResolvedValue({ text: 'A meticulous QA reviewer persona.', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any);
+ setupFleet();
+ const tools = runtimeFor('ceo').tools;
+ expect(tools.fleet_status).toBeDefined();
+ expect(tools.bot_spawn).toBeDefined();
+ expect(tools.bot_retire).toBeDefined();
+
+ const spawn = tools.bot_spawn as any;
+ const out = await spawn.execute({ id: 'qa', name: 'QA', description: 'Reviews posts', persona: 'A meticulous QA reviewer who checks every claim.' }, {} as any);
+ expect(out).toContain('qa');
+ expect(store.get('qa')?.parent).toBe('ceo');
+
+ let last = '';
+ for (let i = 0; i < 5; i++) {
+ last = await spawn.execute({ id: `filler${i}`, name: `F${i}`, description: 'x', persona: 'Filler persona for capacity testing purposes.' }, {} as any);
+ }
+ expect(last).toContain('crew cap');
+
+ const retire = tools.bot_retire as any;
+ expect(await retire.execute({ id: 'writer' }, {} as any)).toContain('retired');
+ expect(store.get('writer')).toBeNull();
+ // Ownership: ceo cannot retire another lead's crew
+ store.create({ id: 'rival', name: 'Rival', manifest: { fleetRole: 'lead' } });
+ manager.addCrew('rival', { id: 'guard', name: 'Guard' });
+ expect(await retire.execute({ id: 'guard' }, {} as any)).toContain('is not crew');
+ });
+
+ it('solo bots never get fleet tools', () => {
+ store.create({ id: 'loner', name: 'Loner' });
+ const tools = runtimeFor('loner').tools;
+ expect(tools.fleet_status).toBeUndefined();
+ expect(tools.bot_spawn).toBeUndefined();
+ });
+});
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index ba7b603e..0aeef199 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -14,6 +14,8 @@ import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from '
import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';
import { createBotSendTool } from './tools/bot-send.js';
import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';
+import { createFleetStatusTool } from './tools/fleet-status.js';
+import { createBotSpawnTool } from './tools/bot-spawn.js';
import { runBotTurn, isTransientFailure, type BotTurnMail } from './bot-turn.js';
import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';
import { SkillLoader } from '../skills/loader.js';
@@ -39,6 +41,16 @@ export interface BotJob {
attempts: number;
}
+/**
+ * Fleet delegation rule: a mailbox job WITH a prompt (fromBot set) is a TASK
+ * dispatched by another bot — its result is returned to the sender's mailbox
+ * on completion. Plain mail wakes (prompt '') never reply — no ping-pong.
+ * Derived from the job itself, so it survives restarts with zero schema.
+ */
+function replyTargetFor(job: BotJob): string | undefined {
+ return job.trigger === 'mailbox' && job.fromBot && job.prompt ? job.fromBot : undefined;
+}
+
export interface BotSendResult {
accepted: boolean;
jobId?: string;
@@ -265,6 +277,18 @@ export class BotManager {
return { jobId: id, accepted: true };
}
+ /**
+ * Fleet task dispatch: a delegated TASK from one bot to another (lead →
+ * crew, crew → lead). Durable job with the task as the prompt — on
+ * completion the result is returned to the sender's mailbox
+ * (replyTargetFor), closing the delegation loop.
+ */
+ dispatchTask(targetBotId: string, fromBot: string, task: string): BotSendResult {
+ const result = this.enqueue(targetBotId, { trigger: 'mailbox', prompt: task, fromBot });
+ if (!result.accepted) return { accepted: false, reasonCode: result.reasonCode as BotSendResult['reasonCode'] };
+ return { accepted: true, jobId: result.jobId };
+ }
+
/** Fire-and-forget mailbox delivery from another bot. */
sendToBot(targetBotId: string, fromBot: string, content: string): BotSendResult {
const manifest = this.store.get(targetBotId);
@@ -478,6 +502,24 @@ export class BotManager {
logger.warn({ e, botId }, 'Bot remote-channel result notify failed'));
}
}
+
+ // Fleet delegation loop: a task dispatched by another bot reports its
+ // result back to the sender's mailbox (attributed, plain mail — never a
+ // task, so results can't ping-pong). Paused runs requeue and report
+ // later; the failure/retry machinery above owns transient states.
+ const replyTarget = replyTargetFor(job);
+ if (replyTarget && (output.status === 'completed' || output.status === 'failed' || output.status === 'halted')) {
+ const icon = output.status === 'completed' ? '✅' : output.status === 'failed' ? '❌' : '⏹';
+ const reply = output.status === 'completed'
+ ? `✅ Task complete (job ${job.id}):\n${output.output.slice(0, 4000)}`
+ : output.status === 'failed'
+ ? `❌ Task FAILED (job ${job.id})${output.reasonCode ? ` [reason: ${output.reasonCode}]` : ''}: ${(output.error ?? output.output).slice(0, 1000)}`
+ : `⏹ Task halted (job ${job.id}) — it was stopped; see /bots journal ${botId}.`;
+ const sent = this.sendToBot(replyTarget, botId, reply);
+ if (!sent.accepted) {
+ logger.warn({ botId, replyTarget, reason: sent.reasonCode }, 'Fleet result reply not delivered');
+ }
+ }
} catch (err: any) {
logger.error({ botId, jobId: job.id, err: err?.message }, 'Bot turn crashed');
this.queue.settle(job.id, 'dead', 'unknown_error');
@@ -539,6 +581,7 @@ export class BotManager {
pollMail: () => this.drainMailbox(botId),
sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },
skillsPrompt,
+ fleet: this.fleetContext(botId, manifest),
capabilities: registry,
tools,
userMemory,
@@ -550,6 +593,31 @@ export class BotManager {
};
}
+ /** Fleet context for the turn prompt (undefined for solo bots). */
+ private fleetContext(botId: string, manifest: BotManifest) {
+ if (manifest.fleetRole === 'lead') {
+ return {
+ role: 'lead' as const,
+ crew: this.store.crewOf(botId).map(c => ({
+ id: c.id,
+ name: c.name,
+ description: c.description,
+ state: this.getStatusSummaries().find(s => s.id === c.id)?.state ?? 'idle',
+ })),
+ maxCrew: this.maxCrew(),
+ };
+ }
+ if (manifest.fleetRole === 'crew' && manifest.parent) {
+ return {
+ role: 'crew' as const,
+ leadName: this.store.get(manifest.parent)?.name,
+ crew: [],
+ maxCrew: 0,
+ };
+ }
+ return undefined;
+ }
+
private getOrCreateRuntime(botId: string, manifest: BotManifest): { registry: CapabilityRegistry; tools: Record<string, Tool>; skillsPrompt: string } {
const cached = this.registries.get(botId);
if (cached) return cached as { registry: CapabilityRegistry; tools: Record<string, Tool>; skillsPrompt: string };
@@ -588,9 +656,21 @@ export class BotManager {
// Filter FIRST (strips interactive/global-mutation tools and applies the
// manifest allow/deny), THEN add the bot-specific tools — otherwise the
// filter would strip them again.
- const filtered = filterBotTools({ ...registry.getTools() }, manifest) as Record<string, Tool>;
- if ((manifest.comms?.canMessage ?? []).length > 0) {
- filtered.bot_send = createBotSendTool(this, botId, manifest.comms?.canMessage ?? []);
+ const filtered = filterBotTools({ ...registry.getTools() }, manifest);
+ // Fleet relations are implicit comms: a lead can message its crew and a
+ // crew bot its lead, without anyone hand-editing canMessage.
+ const effectiveRoster = this.effectiveRoster(botId, manifest);
+ if (effectiveRoster.length > 0) {
+ filtered.bot_send = createBotSendTool(this, botId, effectiveRoster) as Tool;
+ }
+ // Fleet tools for leads: monitor the crew, spawn/retire within caps.
+ if (manifest.fleetRole === 'lead') {
+ filtered.fleet_status = createFleetStatusTool(this, botId);
+ if (this.config.bots?.fleets?.allowLeadSpawn !== false) {
+ const fleet = createBotSpawnTool(this, botId);
+ filtered.bot_spawn = fleet.spawn;
+ filtered.bot_retire = fleet.retire;
+ }
}
// bot_schedule: bots can schedule their own future runs (durable,
// capped) when the main scheduler is wired.
@@ -601,6 +681,89 @@ export class BotManager {
return { registry, tools: filtered, skillsPrompt };
}
+ /**
+ * Comms roster = explicit canMessage ∪ fleet relations (lead ↔ own crew).
+ * Derived per registry build; excludes the bot itself.
+ */
+ private effectiveRoster(botId: string, manifest: BotManifest): string[] {
+ const roster = new Set(manifest.comms?.canMessage ?? []);
+ if (manifest.fleetRole === 'lead') {
+ for (const crew of this.store.crewOf(botId)) roster.add(crew.id);
+ }
+ if (manifest.fleetRole === 'crew' && manifest.parent) {
+ roster.add(manifest.parent);
+ }
+ roster.delete(botId);
+ return [...roster];
+ }
+
+ // ---- fleet management (shared by onboarding, lead tools, API) -----------
+
+ /** Max crew per lead — CrewAI guidance: 3-6 for delegation accuracy. */
+ maxCrew(): number {
+ return this.config.bots?.fleets?.maxCrew ?? 6;
+ }
+
+ /** The bot's provider (public for fleet tools — persona building on spawn). */
+ resolveProviderFor(botId: string): ReturnType<typeof resolveProvider> {
+ const manifest = this.store.get(botId);
+ return resolveProvider(this.providers, manifest ?? { id: botId, name: botId, enabled: true } as BotManifest);
+ }
+
+ /**
+ * Add a crew member to a lead: validates the relationship, enforces the
+ * crew cap, creates with fail-closed defaults + comms back to the lead.
+ * Persona refinement (builder) is the caller's concern (async provider
+ * call); addCrew writes the persona text it is given.
+ */
+ 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}"` };
+ if (lead.fleetRole !== 'lead') {
+ return { ok: false, error: `**${lead.name}** is not a fleet lead — promote it first with /bots create flow or add crew via onboarding` };
+ }
+ const crew = this.store.crewOf(leadId);
+ const cap = this.maxCrew();
+ if (crew.length >= cap) {
+ return { ok: false, error: `Fleet is at the crew cap (${crew.length}/${cap}) — retire a member first or raise BOTS_FLEET_MAX_CREW` };
+ }
+ if (this.store.exists(spec.id)) {
+ return { ok: false, error: `Bot "${spec.id}" already exists` };
+ }
+ const manifest = this.store.create({
+ id: spec.id.toLowerCase(),
+ name: spec.name,
+ description: spec.description,
+ persona: spec.persona,
+ manifest: { fleetRole: 'crew', parent: leadId, comms: { canMessage: [leadId] } },
+ });
+ this.invalidateRuntime(leadId); // lead's roster + fleet prompt change
+ logger.info({ leadId, crewId: spec.id }, 'Crew member added to fleet');
+ return { ok: true, manifest };
+ }
+
+ /** Remove a crew member (lead's own child only) and record it on the lead. */
+ async removeCrew(leadId: string, crewId: string): Promise<{ ok: true } | { ok: false; error: string }> {
+ const crew = this.store.get(crewId);
+ if (!crew) return { ok: false, error: `No bot "${crewId}"` };
+ if (crew.parent !== leadId) return { ok: false, error: `**${crewId}** is not crew of **${leadId}**` };
+ await this.delete(crewId);
+ this.invalidateRuntime(leadId);
+ this.journalFor(leadId).append({
+ runId: randomUUID().slice(0, 8),
+ botId: leadId,
+ trigger: 'chat',
+ state: 'completed',
+ startedAt: Date.now(),
+ durationMs: 0,
+ tokensIn: 0,
+ tokensOut: 0,
+ summary: `Retired crew member "${crew.name}" (${crewId})`,
+ });
+ logger.info({ leadId, crewId }, 'Crew member retired');
+ return { ok: true };
+ }
+
invalidateRuntime(botId: string): void {
this.registries.delete(botId);
}
@@ -613,6 +776,15 @@ export class BotManager {
*/
async delete(botId: string): Promise<void> {
await this.halt(botId);
+ // Fleet cleanup: a deleted LEAD's crew is detached (→ solo), never orphaned
+ // with a dangling parent. A deleted crew bot just leaves the roster.
+ if (this.store.isLead(botId)) {
+ for (const crew of this.store.crewOf(botId)) {
+ this.store.update(crew.id, m => { m.fleetRole = undefined; m.parent = undefined; });
+ this.invalidateRuntime(crew.id);
+ logger.info({ leadId: botId, crewId: crew.id }, 'Fleet lead deleted — crew member detached to solo');
+ }
+ }
// Scheduler routines (bot:<id>:*) — both bot.yaml routines and
// bot_schedule self-created ones; they must never fire again.
if (this.scheduler) {
@@ -792,6 +964,11 @@ export class BotManager {
lastRunAt: last?.at,
lastRunState: last?.state,
needsYou: this.needsYou.has(m.id),
+ fleetRole: m.fleetRole,
+ parent: m.parent,
+ crewWorking: m.fleetRole === 'lead'
+ ? this.store.crewOf(m.id).filter(c => (this.running.get(c.id)?.size ?? 0) > 0).length
+ : undefined,
};
});
}
@@ -853,7 +1030,8 @@ export class BotManager {
for (const m of summaries) {
const state = this.running.get(m.id)?.size ? 'running' : ((this.queues.get(m.id)?.length ?? 0) > 0 ? 'queued' : (m.enabled ? 'idle' : 'disabled'));
const desc = m.description ? ` — ${m.description}` : '';
- lines.push(`- **${m.name}** (\`${m.id}\`)${desc} [${state}]`);
+ const fleetTag = m.fleetRole === 'lead' ? ' [fleet lead 👑]' : m.fleetRole === 'crew' ? ` [crew of ${m.parent}]` : '';
+ lines.push(`- **${m.name}** (\`${m.id}\`)${desc}${fleetTag} [${state}]`);
}
lines.push(`Bot control (never route bot work through this main conversation):
- \`/bot <id> <message>\` or \`@<id> <message>\` — dispatch a task to a bot; the result lands ONLY in the bot's own thread (\`/bots open <id>\`), never in this chat.
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index 2015f539..5dcfefa9 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -27,6 +27,13 @@ export interface BotTurnInput {
sandbox: { workspace: string; shared: string };
/** Skill roster text (native + the bot's own library); empty when none. */
skillsPrompt?: string;
+ /** Fleet hierarchy context (lead crew roster / crew membership); absent for solos. */
+ fleet?: {
+ role: 'lead' | 'crew';
+ leadName?: string;
+ crew: Array<{ id: string; name: string; description?: string; state: string }>;
+ maxCrew: number;
+ };
capabilities: CapabilityRegistry;
tools: Record<string, Tool>;
userMemory: UserMemoryStore | null;
@@ -239,6 +246,24 @@ Anything outside these two areas and your declared Access grants is denied.`;
prompt += `\nSkill scripts are subject to your access grants: a skill whose scripts you cannot run from its own directory can be copied into your sandbox workspace and run from there.`;
}
+ // Fleet hierarchy: the lead orchestrates, the crew executes.
+ if (input.fleet?.role === 'lead') {
+ const roster = input.fleet.crew.length > 0
+ ? input.fleet.crew.map(c => `- ${c.name} (${c.id})${c.description ? ` — ${c.description}` : ''} [${c.state}]`).join('\n')
+ : '(empty — use bot_spawn to add specialists)';
+ prompt += `\n\nYou lead a fleet of crew bots:
+${roster}
+
+Fleet protocol:
+- DELEGATE with bot_send (task: true) — be concrete and self-contained; the result arrives in your mailbox when the bot finishes.
+- MONITOR with fleet_status — check who is running, idle, or blocked before and after delegating.
+- You may create specialists with bot_spawn (crew cap: ${input.fleet.maxCrew}) and retire your own crew with bot_retire.
+- Crew run CONCURRENTLY — dispatch independent work in parallel rather than sequentially.
+- You SYNTHESIZE: crew results arrive in your mailbox attributed by bot; combine them and report a single coherent outcome.`;
+ } else if (input.fleet?.role === 'crew') {
+ prompt += `\n\nYou are crew in **${input.fleet.leadName ?? 'your lead'}'s** fleet. Tasks delegated to you (mailbox messages with a task) return your result to the lead automatically when you finish — make your final output a complete, self-contained report. Use bot_send to ask the lead questions mid-task.`;
+ }
+
const remaining = input.tokenBudget.getRemaining();
prompt += `\n\nToken budget remaining: ${remaining}`;
diff --git a/src/bots/doctor.ts b/src/bots/doctor.ts
index 3d9a8eec..52e076d9 100644
--- a/src/bots/doctor.ts
+++ b/src/bots/doctor.ts
@@ -61,6 +61,17 @@ export function runBotDoctor(deps: DoctorDeps): DoctorReport {
});
}
+ // Fleet hierarchy integrity: a crew bot whose lead no longer exists is
+ // orphaned — it can never be dispatched to, monitored, or retired.
+ if (manifest.parent && !manifests.some(m => m.id === manifest.parent)) {
+ findings.push({
+ botId: manifest.id,
+ severity: 'error',
+ check: 'fleet',
+ detail: `Crew bot's lead "${manifest.parent}" no longer exists — detach with /bots edit or re-point the parent`,
+ });
+ }
+
const dlqDepth = dlqByBot.get(manifest.id) ?? 0;
if (dlqDepth > 0) {
findings.push({
diff --git a/src/bots/fleet-onboarding.test.ts b/src/bots/fleet-onboarding.test.ts
new file mode 100644
index 00000000..41cb8855
--- /dev/null
+++ b/src/bots/fleet-onboarding.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect } from 'vitest';
+import { proposeCrew } from './fleet-onboarding.js';
+
+function providerReturning(text: string) {
+ return {
+ name: 'stub', model: 'stub',
+ generateText: async () => ({ text, inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub', provider: 'stub' }),
+ streamText: async function* () { yield { text: '', done: true }; },
+ isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub',
+ } as any;
+}
+
+const validCrew = JSON.stringify([
+ { id: 'market-research', name: 'Market Researcher', description: 'Research', persona: 'A rigorous market researcher who verifies every claim and reports with sources.' },
+ { id: 'copywriter', name: 'Copywriter', persona: 'A punchy copywriter who drafts launch angles with concrete evidence and never invents numbers.' },
+]);
+
+describe('proposeCrew (fleet auto-onboarding)', () => {
+ it('parses a valid crew proposal and caps it at maxCrew', async () => {
+ const proposals = await proposeCrew('CEO', 'Runs the company', '# CEO persona', providerReturning(validCrew), 1);
+ expect(proposals).toHaveLength(1);
+ expect(proposals[0].id).toBe('market-research');
+ });
+
+ it('strips code fences and surrounding prose', async () => {
+ const wrapped = 'Sure! Here is the crew:\n```json\n' + validCrew + '\n```';
+ const proposals = await proposeCrew('CEO', '', '', providerReturning(wrapped));
+ expect(proposals).toHaveLength(2);
+ });
+
+ it('rejects malformed entries (bad ids, tiny personas, duplicates) and unusable output', async () => {
+ const bad = JSON.stringify([
+ { id: 'Bad Id', name: 'X', persona: 'ok persona that is long enough to pass the length gate here' },
+ { id: 'ok-id', name: 'Y', persona: 'valid persona long enough to pass the length gate' },
+ { id: 'ok-id', name: 'Dup', persona: 'duplicate id should be dropped from the proposal list here.' },
+ ]);
+ expect(await proposeCrew('CEO', '', '', providerReturning(bad)).then(p => p.map(x => x.id))).toEqual(['ok-id']);
+ expect(await proposeCrew('CEO', '', '', providerReturning('no json here at all'))).toHaveLength(0);
+ const throwing = { ...providerReturning('[]'), generateText: async () => { throw new Error('500'); } } as any;
+ expect(await proposeCrew('CEO', '', '', throwing)).toHaveLength(0);
+ });
+});
\ No newline at end of file
diff --git a/src/bots/fleet-onboarding.ts b/src/bots/fleet-onboarding.ts
new file mode 100644
index 00000000..435d82fc
--- /dev/null
+++ b/src/bots/fleet-onboarding.ts
@@ -0,0 +1,75 @@
+import type { BaseProvider } from '../providers/base.js';
+import { logger } from '../utils/logger.js';
+
+export interface CrewProposal {
+ id: string;
+ name: string;
+ description: string;
+ persona: string;
+}
+
+/**
+ * Fleet auto-onboarding: one LLM call proposes a crew of 3-5 specialists for
+ * a lead bot, matched to its domain. CrewAI guidance — small crews (3-6)
+ * keep delegation accuracy high; the proposal is only a SUGGESTION: every
+ * member still goes through the standard creation path (validation, cap,
+ * persona builder) before anything exists.
+ *
+ * Output is parsed from a strict JSON array; unusable output returns []
+ * (non-fatal — the user falls back to the manual path).
+ */
+export async function proposeCrew(
+ leadName: string,
+ leadDescription: string,
+ leadPersona: string,
+ provider: BaseProvider,
+ maxCrew = 6,
+): Promise<CrewProposal[]> {
+ try {
+ const result = await provider.generateText(
+ `Design the crew for a fleet lead bot. Lead: "${leadName}" — ${leadDescription || 'no description'}.
+
+Lead persona (context for what specialists it needs):
+"""
+${leadPersona.slice(0, 3000)}
+"""
+
+Propose ${Math.min(5, maxCrew)} sub-bots (2-5, no more) that this lead should command. Each must be a DISTINCT specialty the lead would genuinely delegate to (research, writing, monitoring, development, analysis...). Output ONLY a JSON array, no preamble, no code fences:
+[
+ {
+ "id": "short-lowercase-id-with-dashes",
+ "name": "Display Name",
+ "description": "One-line specialty",
+ "persona": "Full persona text (80-250 words): who it is, how it works, how it reports. Character, standing instructions, output expectations."
+ }
+]`,
+ 'You design focused, non-overlapping agent teams. Return ONLY the JSON array.',
+ );
+ const text = (result.text ?? '').trim().replace(/^```(?:json)?\n?|\n?```$/g, '');
+ const start = text.indexOf('[');
+ const end = text.lastIndexOf(']');
+ if (start === -1 || end === -1) return [];
+ const parsed = JSON.parse(text.slice(start, end + 1)) as CrewProposal[];
+ if (!Array.isArray(parsed)) return [];
+ const seen = new Set<string>();
+ return parsed
+ .filter(p => {
+ if (!p || typeof p.id !== 'string' || typeof p.name !== 'string') return false;
+ if (!/^[a-z0-9][a-z0-9-]{0,47}$/.test(p.id)) return false;
+ if (!p.persona || p.persona.length < 20) return false;
+ if (seen.has(p.id)) return false;
+ seen.add(p.id);
+ return true;
+ })
+ .slice(0, maxCrew)
+ .map(p => ({
+ id: p.id,
+ name: p.name.slice(0, 48),
+ description: (p.description ?? '').slice(0, 200),
+ persona: p.persona,
+ }));
+ } catch (err: any) {
+ logger.warn({ leadName, err: err?.message }, 'Fleet crew proposal failed — falling back to manual');
+ return [];
+ }
+}
\ No newline at end of file
diff --git a/src/bots/store.ts b/src/bots/store.ts
index 22bd0390..6bdc2dce 100644
--- a/src/bots/store.ts
+++ b/src/bots/store.ts
@@ -68,6 +68,20 @@ export function validateBotManifest(manifest: Partial<BotManifest>): string[] {
for (const other of canMessage) {
if (other === manifest.id) errors.push('canMessage cannot include the bot itself');
}
+ // Fleet hierarchy: crew requires a parent that is a lead; leads have no
+ // parent. Single-level fleets in v1 — a lead-of-lead is a config error
+ // (nesting would need a deeper cycle check, so it is rejected outright).
+ if (manifest.parent) {
+ if (manifest.fleetRole !== 'crew') {
+ errors.push('parent is only valid on fleetRole "crew" bots');
+ }
+ if (manifest.parent === manifest.id) {
+ errors.push('parent cannot be the bot itself');
+ }
+ }
+ if (manifest.fleetRole === 'crew' && !manifest.parent) {
+ errors.push('fleetRole "crew" requires a parent (the lead bot id)');
+ }
return errors;
}
@@ -165,6 +179,24 @@ export class BotStore {
return join(this.botDir(id), 'skills');
}
+ // ---- fleet hierarchy (derived — the child's `parent` is the only state) --
+
+ /** Crew of a lead, derived from manifests. Lead/solo → empty. */
+ crewOf(leadId: string): BotManifest[] {
+ return this.list().filter(m => m.parent === leadId);
+ }
+
+ /** The lead of a crew bot; solo/lead → null. */
+ leadOf(botId: string): BotManifest | null {
+ const m = this.get(botId);
+ if (!m?.parent) return null;
+ return this.get(m.parent);
+ }
+
+ isLead(id: string): boolean {
+ return this.get(id)?.fleetRole === 'lead';
+ }
+
/** The fleet-shared sandbox folder (one physical dir; every bot gets rw+x). */
sharedSandboxDir(): string {
return resolve(this.botsRoot, BOT_SHARED_SANDBOX_DIRNAME);
diff --git a/src/bots/tools/bot-send.ts b/src/bots/tools/bot-send.ts
index 40af69cd..12a7875c 100644
--- a/src/bots/tools/bot-send.ts
+++ b/src/bots/tools/bot-send.ts
@@ -5,25 +5,36 @@ import type { BotManager, BotSendResult } from '../bot-manager.js';
/**
* bot_send — fire-and-forget mailbox delivery to a linked bot (Hermes'
* message_agent semantics: attributed, queued behind the target's active
- * turn, never a blocking nested invocation).
+ * turn, never a blocking nested invocation). With task: true it becomes
+ * fleet DELEGATION: the bot executes and its result is returned to the
+ * sender's mailbox on completion.
*/
export function createBotSendTool(manager: BotManager, senderBotId: string, canMessage: string[]) {
const roster = canMessage.length > 0 ? canMessage.join(', ') : '(no bots linked)';
return tool({
description:
`Send a message to another Mercury bot. Delivery is queued — the target bot consumes it on its next turn. ` +
- `You may message: ${roster}. Use this to hand off findings, request research, or coordinate.`,
+ `You may message: ${roster}. Use this to hand off findings, request research, or coordinate. ` +
+ `With task: true you DELEGATE A TASK — the bot works on it and its result is delivered back to your mailbox on completion.`,
inputSchema: zodSchema(z.object({
target: z.string().describe('Bot id to message'),
message: z.string().min(1).max(20000).describe('Message content — be concrete and self-contained'),
+ task: z.boolean().optional().describe('true = delegate a TASK: the bot works on it and its result is delivered back to your mailbox when done. false/omit = fire-and-forget message.'),
})),
- execute: async ({ target, message }: { target: string; message: string }) => {
+ execute: async ({ target, message, task }: { target: string; message: string; task?: boolean }) => {
if (!canMessage.includes(target)) {
return `Error: you are not configured to message bot "${target}". Linked bots: ${roster}`;
}
if (target === senderBotId) {
return 'Error: you cannot message yourself.';
}
+ if (task) {
+ const result: BotSendResult = manager.dispatchTask(target, senderBotId, message);
+ if (!result.accepted) {
+ return `Error dispatching task to ${target}: [reason: ${result.reasonCode}]`;
+ }
+ return `Task dispatched to ${target} (job ${result.jobId}). It runs asynchronously — the result will arrive in your mailbox when done. Check fleet_status to monitor progress.`;
+ }
const result: BotSendResult = manager.sendToBot(target, senderBotId, message);
if (!result.accepted) {
return `Error delivering to ${target}: [reason: ${result.reasonCode}]`;
diff --git a/src/bots/tools/bot-spawn.ts b/src/bots/tools/bot-spawn.ts
new file mode 100644
index 00000000..e6c9be8b
--- /dev/null
+++ b/src/bots/tools/bot-spawn.ts
@@ -0,0 +1,67 @@
+import { tool, zodSchema } from 'ai';
+import { z } from 'zod';
+import type { BotManager } from '../bot-manager.js';
+import { refinePersona } from '../persona-template.js';
+import type { BaseProvider } from '../../providers/base.js';
+
+export interface BotSpawnTools {
+ spawn: ReturnType<typeof createSpawnTool>;
+ retire: ReturnType<typeof createRetireTool>;
+}
+
+/**
+ * bot_spawn / bot_retire — a lead bot's team management: create or retire
+ * its OWN crew members within the fleet cap. Every action is journaled on
+ * the lead (removeCrew) and logged. Created crew get standard fail-closed
+ * defaults (own sandbox + shared folder + comms back to the lead); personas
+ * run through the persona builder, which cannot invent grants.
+ */
+export function createBotSpawnTool(manager: BotManager, leadId: string): BotSpawnTools {
+ const maxCrew = manager.maxCrew();
+ return {
+ spawn: createSpawnTool(manager, leadId, maxCrew),
+ retire: createRetireTool(manager, leadId),
+ };
+}
+
+function createSpawnTool(manager: BotManager, leadId: string, maxCrew: number) {
+ return tool({
+ description:
+ `Create a new specialist crew member for your fleet (cap: ${maxCrew}). Give it a short id, a name, a one-line ` +
+ `specialty description, and a persona (who it is, how it works). The persona is refined into a structured ` +
+ `persona file automatically. The new bot starts with safe default permissions (its own sandbox + the fleet ` +
+ `shared folder) and can message you.`,
+ inputSchema: zodSchema(z.object({
+ id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/).describe('Short lowercase id for the new bot (e.g. "market-research")'),
+ name: z.string().min(1).max(48).describe('Display name, e.g. "Market Researcher"'),
+ description: z.string().max(200).describe('One-line specialty description'),
+ persona: z.string().min(20).max(8000).describe('The bot\'s persona: character, standing instructions, output style'),
+ })),
+ execute: async ({ id, name, description, persona }: { id: string; name: string; description: string; persona: string }) => {
+ const provider = manager.resolveProviderFor(leadId);
+ const refined = await refinePersona(persona, name, provider);
+ const result = manager.addCrew(leadId, { id, name, description, persona: refined ?? persona });
+ if (!result.ok) {
+ return `Error: ${result.error}`;
+ }
+ return `Crew member created: **${name}** (${result.manifest.id}) — fail-closed defaults, comms linked to you, persona ${refined ? 'refined through the persona builder' : 'saved as written'}. Dispatch tasks with bot_send (task: true); its results will arrive in your mailbox.`;
+ },
+ });
+}
+
+function createRetireTool(manager: BotManager, leadId: string) {
+ return tool({
+ description:
+ 'Retire one of your OWN crew members (you can only retire bots you lead). Its profile, sandbox, and queue are removed permanently.',
+ inputSchema: zodSchema(z.object({
+ id: z.string().describe('The crew bot id to retire'),
+ })),
+ execute: async ({ id }: { id: string }) => {
+ const result = await manager.removeCrew(leadId, id);
+ if (!result.ok) {
+ return `Error: ${result.error}`;
+ }
+ return `Crew member **${id}** retired. Fleet capacity freed.`;
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/bots/tools/fleet-status.ts b/src/bots/tools/fleet-status.ts
new file mode 100644
index 00000000..c70b7beb
--- /dev/null
+++ b/src/bots/tools/fleet-status.ts
@@ -0,0 +1,32 @@
+import { tool, zodSchema } from 'ai';
+import { z } from 'zod';
+import type { BotManager } from '../bot-manager.js';
+
+/**
+ * fleet_status — a lead bot's awareness loop: live state of every crew
+ * member (running/queued/idle/paused/disabled, current activity, last run,
+ * needs-you flags). Derived from the manager's in-memory + store state, so
+ * it is always current and never blocks.
+ */
+export function createFleetStatusTool(manager: BotManager, leadId: string) {
+ return tool({
+ description:
+ 'Check the live status of your fleet crew — who is running, queued, idle, or blocked, and what each is working on. ' +
+ 'Use this before delegating (pick an idle specialist) and to monitor delegated tasks.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ const crew = manager.getStatusSummaries().filter(s => s.parent === leadId);
+ if (crew.length === 0) {
+ return 'Your crew is empty. Use bot_spawn to add specialists, or ask the user to add crew members.';
+ }
+ const lines: string[] = [`Crew (${crew.length}):`];
+ for (const s of crew) {
+ const icon = s.state === 'running' ? '🟢' : s.state === 'queued' ? '🔵' : s.state === 'paused' ? '🟡' : s.state === 'disabled' ? '⛔' : '⚪';
+ const detail = s.activity ? ` — ${s.activity}` : '';
+ const attention = s.needsYou ? ' · ⚠ NEEDS YOU' : '';
+ lines.push(`- ${s.name} (${s.id}) [${s.state}]${attention}${detail}`);
+ }
+ return lines.join('\n');
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/bots/types.ts b/src/bots/types.ts
index c12490cc..d3f1f120 100644
--- a/src/bots/types.ts
+++ b/src/bots/types.ts
@@ -88,6 +88,13 @@ export interface BotManifest {
schedules?: BotScheduleConfig[];
autonomy?: BotAutonomyConfig;
retention?: BotRetentionConfig;
+ /**
+ * Fleet hierarchy (absent = solo bot, zero drift for existing bots).
+ * lead = orchestrates a crew; crew = member of a lead's fleet.
+ */
+ fleetRole?: 'lead' | 'crew';
+ /** Crew bots only: the lead's id. Leads and solos never set this. */
+ parent?: string;
createdAt?: string;
updatedAt?: string;
}
@@ -143,4 +150,10 @@ export interface BotStatusSummary {
lastRunAt?: number;
lastRunState?: BotRunState;
needsYou: boolean;
+ /** Fleet hierarchy: 'lead' | 'crew' | undefined (solo). */
+ fleetRole?: 'lead' | 'crew';
+ /** Crew bots: their lead's id. */
+ parent?: string;
+ /** Leads: how many crew are currently running a turn. */
+ crewWorking?: number;
}
\ No newline at end of file
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 8d493e40..88d7a287 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -327,7 +327,7 @@ export interface TuiState {
/** Active Mercury Bot chat — transcript is swapped to the bot's thread. */
botChat: { botId: string; botName: string } | null;
/** Live bot roster (drives `/bots` argument autocomplete and badges). */
- botRoster: Array<{ id: string; name: string; state: string; needsYou: boolean }>;
+ botRoster: Array<{ id: string; name: string; state: string; needsYou: boolean; fleetRole?: 'lead' | 'crew'; parent?: string }>;
}
const defaultState: TuiState = {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 25551cfc..2af23189 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -25,6 +25,7 @@ import { SkillBatcher } from '../skills/batcher.js';
import type { SkillLoader } from '../skills/loader.js';
import { logger } from '../utils/logger.js';
import { refinePersona } from '../bots/persona-template.js';
+import { proposeCrew } from '../bots/fleet-onboarding.js';
import { applyBotFieldPatch } from '../bots/edit.js';
import { CLIChannel } from '../channels/cli.js';
import { TelegramChannel } from '../channels/telegram.js';
@@ -505,6 +506,9 @@ export class Agent {
private botManager?: import('../bots/bot-manager.js').BotManager;
/** Bot awaiting a persona from the next message (post-create setup flow). */
private pendingPersonaFor: string | null = null;
+ /** True while the pending persona capture belongs to a JUST-created bot —
+ * gates the fleet (solo vs lead) onboarding step in finalizePersona. */
+ private pendingPersonaNewlyCreated = false;
/** Bot awaiting a daily token budget answer (final onboarding step). */
private pendingBudgetFor: string | null = null;
readonly programmingMode: ProgrammingMode;
@@ -1135,7 +1139,7 @@ export class Agent {
* as-is. TUI gets a real choice prompt; other channels default to
* template with graceful raw fallback on provider failure.
*/
- private async finalizePersona(bm: import('../bots/bot-manager.js').BotManager, botId: string, raw: string, msg: ChannelMessage): Promise<void> {
+ private async finalizePersona(bm: import('../bots/bot-manager.js').BotManager, botId: string, raw: string, msg: ChannelMessage, newlyCreated = false): Promise<void> {
const channel = this.channels.getChannelForMessage(msg);
const manifest = bm.store.get(botId);
if (!channel || !manifest) return;
@@ -1178,6 +1182,11 @@ export class Agent {
const mode = finalPersona === raw ? 'as-is' : 'as a structured template';
await channel.send(`✍️ Persona saved ${mode}.`, `bot:${botId}`).catch(() => {});
+ // New-bot onboarding: solo vs fleet step (personas edited later never ask).
+ if (newlyCreated) {
+ await this.offerFleetStep(bm, botId, manifest.name, msg, channel);
+ }
+
// Final onboarding step: the daily token budget — optional and OFF by
// default (no cap). "suggest" fills a generous number so heavy bots are
// protected from runaway spend without ever being strangled.
@@ -1193,6 +1202,60 @@ export class Agent {
).catch(() => {});
}
+ /**
+ * Fleet onboarding step (new bots only): solo vs lead. Auto-build asks one
+ * LLM call for a matched crew; manual points at `/bots add-crew`. The
+ * budget step follows either way.
+ */
+ private async offerFleetStep(bm: import('../bots/bot-manager.js').BotManager, botId: string, botName: string, msg: ChannelMessage, channel: any): Promise<void> {
+ let choice = 'Solo bot';
+ try {
+ choice = await this.presentChoice(
+ `Should **${botName}** work solo, or lead a fleet of sub-bots?`,
+ ['Solo bot', 'Lead a fleet — auto-build the crew', 'Lead a fleet — I\'ll add crew myself'],
+ msg.channelId,
+ msg.channelType as any,
+ );
+ } catch {
+ choice = 'Solo bot';
+ }
+ if (choice.startsWith('Solo')) return;
+
+ // Promote to lead before any crew exists.
+ bm.store.update(botId, m => { m.fleetRole = 'lead'; });
+ bm.invalidateRuntime(botId);
+
+ if (choice.startsWith('Lead a fleet — I\'ll')) {
+ await channel.send(
+ `👑 **${botName}** is now a fleet lead. Add specialists anytime:\n` +
+ `\`/bots add-crew ${botId} <id> "Name" "Description" "persona (optional)"\`\n` +
+ `Review the fleet with \`/bots crew ${botId}\` — or just tell **${botName}** to hire its own crew (it has bot_spawn).`,
+ `bot:${botId}`,
+ ).catch(() => {});
+ return;
+ }
+
+ // Auto-build: one LLM proposal, created through the standard path.
+ await channel.send(`👑 **${botName}** is now a fleet lead — proposing a crew…`, `bot:${botId}`).catch(() => {});
+ const persona = bm.store.readPersona(botId);
+ const proposals = await proposeCrew(botName, bm.store.get(botId)?.description ?? '', persona, this.providers.getDefault(), bm.maxCrew());
+ if (proposals.length === 0) {
+ await channel.send(`⚠ Crew proposal unavailable (provider) — **${botName}** is a lead with an empty crew. Add members with \`/bots add-crew ${botId} <id> "Name" "Description" "persona"\` or tell the lead to hire its own.`, `bot:${botId}`).catch(() => {});
+ return;
+ }
+ const lines: string[] = [`👑 **${botName}** fleet — ${proposals.length} crew member(s) created:`, ''];
+ for (const p of proposals) {
+ const result = bm.addCrew(botId, p);
+ if (result.ok) {
+ lines.push(`• **${p.name}** (\`${result.manifest.id}\`) — ${p.description || 'specialist'}`);
+ } else {
+ lines.push(`⚠ ${p.name} (${p.id}): ${result.error}`);
+ }
+ }
+ lines.push('', 'Dispatch tasks with `/bot <crewId> <task>` or tell the lead to delegate — it can also spawn more crew itself.');
+ await channel.send(lines.join('\n'), `bot:${botId}`).catch(() => {});
+ }
+
/** Apply the budget answer typed after the persona step (or a later task). */
private async applyBudgetAnswer(bm: import('../bots/bot-manager.js').BotManager, botId: string, message: string, msg: ChannelMessage): Promise<boolean> {
const value = message.trim().toLowerCase();
@@ -1255,7 +1318,7 @@ export class Agent {
return;
} else {
// Offer the "convert to template" step before anything hits disk.
- await this.finalizePersona(bm, botId, message.trim(), msg);
+ await this.finalizePersona(bm, botId, message.trim(), msg, this.pendingPersonaNewlyCreated);
return;
}
}
@@ -1310,7 +1373,7 @@ export class Agent {
const action = (parts[0] ?? '').toLowerCase();
// All bot-targeting actions accept id OR name — resolve to the id here.
- if (['open', 'send', 'journal', 'inbox', 'budget', 'edit', 'delete', 'enable', 'disable', 'stop', 'pause', 'start', 'run', 'persona'].includes(action) && parts[1]) {
+ if (['open', 'send', 'journal', 'inbox', 'budget', 'edit', 'delete', 'enable', 'disable', 'stop', 'pause', 'start', 'run', 'persona', 'crew', 'add-crew', 'remove-crew'].includes(action) && parts[1]) {
const resolved = bm.resolveBotId(parts[1]);
if (resolved) parts[1] = resolved;
}
@@ -1331,13 +1394,31 @@ export class Agent {
await channel.send('No bots configured. Use `/bots create <id> "Name" "Description"` to onboard one.', channelId);
return;
}
- const lines = [`**Bots** (${summaries.length})`, ''];
- for (const s of summaries) {
+ // Fleet tree: 👑 lead first with crew indented beneath; solos flat.
+ const leads = summaries.filter(s => s.fleetRole === 'lead');
+ const crews = summaries.filter(s => s.fleetRole === 'crew');
+ const solos = summaries.filter(s => !s.fleetRole);
+ const fmt = (s: typeof summaries[number], indent: string) => {
const icon = stateIcons[s.state] ?? '❓';
const lastRun = s.lastRunAt ? ` · last ${(s.lastRunState ?? '')} ${formatRelative(s.lastRunAt)}` : '';
- const activity = s.activity ? `\n ↳ ${s.activity}` : '';
+ const activity = s.activity ? `\n${indent} ↳ ${s.activity}` : '';
const attention = s.needsYou ? ' · ⚠ needs you' : '';
- lines.push(`${icon} **${s.name}** (${s.id}) — ${s.state}${attention}${lastRun}${activity}`);
+ return `${indent}${icon} **${s.name}** (${s.id}) — ${s.state}${attention}${lastRun}${activity}`;
+ };
+ const lines: string[] = [`**Bots** (${summaries.length})`, ''];
+ const rendered = new Set<string>();
+ for (const lead of leads) {
+ const crew = crews.filter(c => c.parent === lead.id);
+ lines.push(fmt(lead, ''));
+ rendered.add(lead.id);
+ for (const c of crew) {
+ lines.push(fmt(c, ' '));
+ rendered.add(c.id);
+ }
+ if (crew.length === 0) lines.push(' (empty crew — `/bots add-crew` or the lead can bot_spawn)');
+ }
+ for (const s of [...crews, ...solos]) {
+ if (!rendered.has(s.id)) lines.push(fmt(s, ''));
}
const running = summaries.filter(s => s.state === 'running').length;
lines.push('', `Running: ${running} | Queued: ${summaries.reduce((a, s) => a + (s.state === 'queued' ? 1 : 0), 0)}`);
@@ -1374,10 +1455,12 @@ export class Agent {
const personaText = quoted[2];
try {
const manifest = bm.store.create({ id, name, description });
+ this.pendingPersonaNewlyCreated = true;
if (personaText) {
bm.store.writePersona(id, personaText + '\n');
bm.invalidateRuntime(id);
await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded with your persona — enabled, fail-closed defaults.\nStart using it: \`/bot ${id} <task>\`, \`/bots open ${id}\`, or just \`@${id} <task>\`.`, channelId);
+ await this.offerFleetStep(bm, id, manifest.name, msg, channel);
return;
}
// No persona given — open its chat and prompt for one now (TUI only).
@@ -1516,7 +1599,8 @@ export class Agent {
return;
}
if (!confirmed && typeof (channel as any).askToContinue === 'function') {
- const proceed = await (channel as any).askToContinue(`Delete bot **${target}** and its profile (persona, memory links, journal)? This cannot be undone.`);
+ const crewCount = bm.store.crewOf(target).length;
+ const proceed = await (channel as any).askToContinue(`Delete bot **${target}** and its profile (persona, memory links, journal)? This cannot be undone.${crewCount > 0 ? ` Its ${crewCount} crew member(s) will be detached and become solo bots.` : ''}`);
if (!proceed) {
await channel.send('Deletion cancelled.', channelId);
return;
@@ -1663,6 +1747,93 @@ export class Agent {
return;
}
+ if (action === 'crew') {
+ // /bots crew <leadId> — the fleet tree + per-crew recent runs.
+ const leadId = parts[1]?.toLowerCase();
+ if (!leadId || !bm.store.exists(leadId)) {
+ await channel.send('Usage: `/bots crew <leadId>`', channelId);
+ return;
+ }
+ const lead = bm.store.get(leadId);
+ if (lead?.fleetRole !== 'lead') {
+ await channel.send(`**${lead?.name ?? leadId}** is not a fleet lead.`, channelId);
+ return;
+ }
+ const crew = bm.store.crewOf(leadId);
+ const lines = [`👑 **${lead.name}** fleet (${crew.length}/${bm.maxCrew()})`, ''];
+ if (crew.length === 0) {
+ lines.push('(empty — `/bots add-crew` or tell the lead to bot_spawn)');
+ }
+ const stateIcons2: Record<string, string> = { idle: '⚪', queued: '🔵', running: '🟢', paused: '🟡', disabled: '⛔' };
+ for (const c of crew) {
+ const summary = bm.getStatusSummaries().find(s => s.id === c.id);
+ const runs = bm.getJournal(c.id, 3);
+ const lastRun = runs.length > 0 ? `last: ${runs[runs.length - 1].state}` : 'no runs yet';
+ lines.push(`${stateIcons2[summary?.state ?? 'idle']} **${c.name}** (${c.id})${c.description ? ` — ${c.description}` : ''} · ${lastRun}`);
+ for (const r of runs.slice(-2).reverse()) {
+ lines.push(` ↳ ${r.state === 'completed' ? '✅' : r.state === 'failed' ? '❌' : '⛔'} ${r.summary?.slice(0, 90) ?? r.runId}`);
+ }
+ }
+ await channel.send(lines.join('\n'), channelId);
+ return;
+ }
+
+ if (action === 'add-crew') {
+ // /bots add-crew <leadId> <id> "Name" "Description" ["persona"]
+ const leadId = parts[1]?.toLowerCase();
+ const rest = parts.slice(2).join(' ');
+ const quoted = [...rest.matchAll(/"([^"]*)"/g)].map(m => m[1]);
+ const id = quoted[0] ?? parts[2];
+ if (!leadId || !id || !quoted[0]) {
+ await channel.send('Usage: `/bots add-crew <leadId> <id> "Name" "Description" "persona (optional)"`', channelId);
+ return;
+ }
+ if (!bm.store.exists(leadId) || bm.store.get(leadId)?.fleetRole !== 'lead') {
+ await channel.send(`**${leadId}** is not a fleet lead.`, channelId);
+ return;
+ }
+ try {
+ let persona: string | undefined;
+ if (quoted[2]) {
+ const refined = await refinePersona(quoted[2], quoted[0], this.providers.getDefault());
+ persona = refined ?? quoted[2];
+ }
+ const result = bm.addCrew(leadId, { id, name: quoted[0], description: quoted[1], persona });
+ if (!result.ok) {
+ await channel.send(`⚠ ${result.error}`, channelId);
+ return;
+ }
+ await channel.send(`👑 Crew member **${quoted[0]}** (\`${result.manifest.id}\`) added to **${leadId}** — fail-closed defaults, comms linked to the lead${persona ? ', persona refined' : ''}.`, channelId);
+ } catch (err: any) {
+ await channel.send(`Failed: ${err?.message}`, channelId);
+ }
+ return;
+ }
+
+ if (action === 'remove-crew') {
+ const leadId = parts[1]?.toLowerCase();
+ const crewId = parts[2]?.toLowerCase();
+ if (!leadId || !crewId) {
+ await channel.send('Usage: `/bots remove-crew <leadId> <crewId>`', channelId);
+ return;
+ }
+ const crew = bm.store.get(crewId);
+ if (!crew || crew.parent !== leadId) {
+ await channel.send(`**${crewId}** is not crew of **${leadId}**. See \`/bots crew ${leadId}\`.`, channelId);
+ return;
+ }
+ if (typeof (channel as any).askToContinue === 'function') {
+ const proceed = await (channel as any).askToContinue(`Retire crew member **${crew.name}** (${crewId})? Profile, sandbox, and queue are removed permanently.`);
+ if (!proceed) {
+ await channel.send('Retirement cancelled.', channelId);
+ return;
+ }
+ }
+ const result = await bm.removeCrew(leadId, crewId);
+ await channel.send(result.ok ? `👑 Crew member **${crewId}** retired from **${leadId}**.` : `⚠ ${result.error}`, channelId);
+ return;
+ }
+
if (action === 'storage') {
const usage = bm.getStorage();
if (usage.length === 0) {
@@ -1696,6 +1867,9 @@ export class Agent {
'`/bots storage` — disk usage\n' +
'`/bots enable|disable|stop|start <id>` — control (stop holds queued jobs; start resumes them)\n' +
'`/bots run <id> [routineName]` — fire a routine now, or a bare wake turn\n' +
+ '`/bots crew <leadId>` — fleet tree with per-crew runs\n' +
+ '`/bots add-crew <leadId> <id> "Name" "Desc" ["persona"]` — add a sub-bot to a fleet\n' +
+ '`/bots remove-crew <leadId> <crewId>` — retire a crew member\n' +
'`/bots delete <id> confirm` — permanently delete',
channelId,
);
diff --git a/src/index.ts b/src/index.ts
index 25ca3182..857afba8 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2566,6 +2566,8 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
name: b.name,
state: b.state,
needsYou: b.needsYou,
+ fleetRole: b.fleetRole,
+ parent: b.parent,
})) ?? [],
});
bootCli.startStatusPoller(2000);
diff --git a/src/utils/config.ts b/src/utils/config.ts
index 03295233..9d8c5e03 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -206,6 +206,13 @@ export interface MercuryConfig {
autoSkill?: {
enabled?: boolean;
};
+ /** Fleet hierarchies: lead bots managing a crew of sub-bots. */
+ fleets?: {
+ /** Hard cap on crew size per lead (CrewAI guidance: 3-6 for delegation accuracy). */
+ maxCrew?: number;
+ /** Lead bots may create/remove their own crew via bot_spawn/bot_retire. */
+ allowLeadSpawn?: boolean;
+ };
/** Suggested per-bot daily token budget offered during onboarding. */
suggestedDailyTokenBudget?: number;
retention: {
@@ -470,6 +477,10 @@ export function getDefaultConfig(): MercuryConfig {
autoSkill: {
enabled: getEnvBool('BOTS_AUTO_SKILL', false),
},
+ fleets: {
+ maxCrew: getEnvNum('BOTS_FLEET_MAX_CREW', 6),
+ allowLeadSpawn: getEnvBool('BOTS_FLEET_LEAD_SPAWN', true),
+ },
suggestedDailyTokenBudget: getEnvNum('BOTS_SUGGESTED_DAILY_TOKEN_BUDGET', 5_000_000),
retention: {
transcriptRuns: getEnvNum('BOTS_RETENTION_TRANSCRIPT_RUNS', 50),
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
index 4dae6a97..22dc3126 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -180,6 +180,28 @@ app.post('/api/bots/:id/run', async (c: any) => {
return c.json({ ...result, status: 'accepted' }, 202);
});
+// Fleet views: crew roster of a lead + add-crew
+app.get('/api/bots/:id/crew', (c: any) => {
+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);
+ const id = c.req.param('id');
+ if (!botManager.store.isLead(id)) return c.json({ error: 'Not a fleet lead' }, 400);
+ return c.json({
+ lead: botManager.store.get(id),
+ crew: botManager.store.crewOf(id),
+ maxCrew: botManager.maxCrew(),
+ });
+});
+
+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;
+ if (!body?.id || !body?.name) return c.json({ error: 'id and name are required' }, 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);
+ return c.json({ bot: result.manifest }, 201);
+});
+
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;