Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): the persona builder and "let Mercury decide" for the app
Salman Qureshib058eb7d5317
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex bff34ae6..27ecf090 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -18,7 +18,7 @@ import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FIimport { BotJournal, type BotTranscript, type BotUsage } 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 { planBotShape, proposeCrew, type BotShapePlan } from './fleet-onboarding.js';import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';import { createBotSendTool } from './tools/bot-send.js';import { BotTaskStore, renderTaskPrompt, renderBatchDigest, isTerminalTask, type BotTask, type BotTaskResult } from './tasks.js';@@ -1466,6 +1466,16 @@ export class BotManager {// ---- fleet management (shared by onboarding, lead tools, API) -----------/** Max crew per lead — CrewAI guidance: 3-6 for delegation accuracy. */+ /** The persona builder (no save): rough instructions → the structured persona format. Null when unavailable. */+ async buildPersona(text: string, name: string): Promise<string | null> {+ return refinePersona(text, name || 'Bot', this.providers.getDefault());+ }++ /** "Let Mercury decide": solo or fleet for what the owner described, with a proposed crew. Nothing is created. */+ async planShape(input: { name: string; description: string; persona: string }): Promise<BotShapePlan> {+ return planBotShape(input, this.providers.getDefault(), this.maxCrew());+ }+maxCrew(): number {return this.config.bots?.fleets?.maxCrew ?? 6;}diff --git a/src/bots/fleet-onboarding.test.ts b/src/bots/fleet-onboarding.test.tsindex 41cb8855..0c48ec29 100644--- a/src/bots/fleet-onboarding.test.ts+++ b/src/bots/fleet-onboarding.test.ts@@ -39,4 +39,28 @@ describe('proposeCrew (fleet auto-onboarding)', () => {const throwing = { ...providerReturning('[]'), generateText: async () => { throw new Error('500'); } } as any;expect(await proposeCrew('CEO', '', '', throwing)).toHaveLength(0);});-});\ No newline at end of file+});+describe('planBotShape — "let Mercury decide"', () => {+ const answer = (text: string) => ({ generateText: async () => ({ text }) }) as never;+ const input = { name: 'Newsroom', description: 'Researches, writes and checks articles', persona: 'Find stories, write them, check facts.' };++ it('a fleet comes back with its crew, ids cleaned and capped', async () => {+ const { planBotShape } = await import('./fleet-onboarding.js');+ const crew = Array.from({ length: 7 }, (_, i) => ({ id: `Bad Id ${i}`, name: `Specialist ${i}`, description: 'x', persona: 'A focused specialist who reports back to the lead clearly.' }));+ const plan = await planBotShape(input, answer(JSON.stringify({ shape: 'fleet', reason: 'Three separate stages.', crew })));+ expect(plan.shape).toBe('fleet');+ expect(plan.reason).toBe('Three separate stages.');+ expect(plan.crew).toHaveLength(5);+ for (const c of plan.crew) expect(c.id).toMatch(/^[a-z0-9][a-z0-9-]*$/);+ });++ it('solo when the model says so, when a "fleet" has fewer than two crew, or when the answer is unusable', async () => {+ const { planBotShape } = await import('./fleet-onboarding.js');+ expect((await planBotShape(input, answer('{"shape":"solo","reason":"One focused job.","crew":[]}')))).toEqual({ shape: 'solo', reason: 'One focused job.', crew: [] });+ const one = await planBotShape(input, answer(JSON.stringify({ shape: 'fleet', reason: 'x', crew: [{ id: 'a', name: 'A', description: '', persona: 'A specialist with a long enough persona.' }] })));+ expect(one.shape).toBe('solo');+ expect((await planBotShape(input, answer('I think a fleet would be lovely'))).shape).toBe('solo');+ const failing = { generateText: async () => { throw new Error('no provider'); } } as never;+ expect((await planBotShape(input, failing)).shape).toBe('solo');+ });+});diff --git a/src/bots/fleet-onboarding.ts b/src/bots/fleet-onboarding.tsindex 435d82fc..12ed77d0 100644--- a/src/bots/fleet-onboarding.ts+++ b/src/bots/fleet-onboarding.ts@@ -72,4 +72,74 @@ Propose ${Math.min(5, maxCrew)} sub-bots (2-5, no more) that this lead should cologger.warn({ leadName, err: err?.message }, 'Fleet crew proposal failed — falling back to manual');return [];}-}\ No newline at end of file+}+export interface BotShapePlan {+ shape: 'solo' | 'fleet';+ /** One plain sentence: why this shape. */+ reason: string;+ /** The lead's crew, when shape is fleet (2-5). */+ crew: CrewProposal[];+}++/**+ * "Let Mercury decide": one call looks at what the owner wants a bot for and+ * says whether one bot does it (solo) or it needs a small team (a lead with+ * crew), and if so, proposes the crew. A fleet costs a turn per hand-off, so+ * it's only right when the work has genuinely separate stages or specialties.+ * The plan is a proposal: the owner sees it, edits it, and only then is+ * anything created. Unusable output falls back to solo with no crew.+ */+export async function planBotShape(+ input: { name: string; description: string; persona: string },+ provider: BaseProvider,+ maxCrew = 6,+): Promise<BotShapePlan> {+ const solo = (reason: string): BotShapePlan => ({ shape: 'solo', reason, crew: [] });+ try {+ const result = await provider.generateText(+ `An owner is creating an autonomous bot. Decide whether ONE bot should do this job, or a small FLEET: a lead bot that delegates to 2-5 specialist crew bots.++Bot: "${input.name}" — ${input.description || 'no description'}+What it should do:+"""+${input.persona.slice(0, 4000) || '(not written yet)'}+"""++Choose "fleet" ONLY when the job has clearly separate stages or specialties that each need their own focus (e.g. research → write → fact-check → publish, or monitoring several unrelated sources). Every hand-off costs a full extra run, so a single focused job, a monitor, a digest, a researcher or a writer is "solo". When in doubt, choose solo.++Output ONLY JSON, no preamble, no code fences:+{+ "shape": "solo" | "fleet",+ "reason": "One plain sentence for the owner: why this shape.",+ "crew": [+ { "id": "short-lowercase-id", "name": "Display Name", "description": "One-line specialty", "persona": "80-200 words: who it is, how it works, what it hands back to the lead (as a bot_report)." }+ ]+}+crew is [] for solo; 2-${Math.min(5, maxCrew)} distinct, non-overlapping specialists for fleet.`,+ 'You design lean agent setups. Prefer the simplest setup that does the job. Return ONLY the JSON object.',+ );+ const text = (result.text ?? '').trim().replace(/^```(?:json)?\n?|\n?```$/g, '');+ const start = text.indexOf('{');+ const end = text.lastIndexOf('}');+ if (start === -1 || end === -1) return solo('Mercury couldn\'t plan this one, so it starts as a single bot.');+ const raw = JSON.parse(text.slice(start, end + 1)) as { shape?: string; reason?: string; crew?: CrewProposal[] };+ const reason = typeof raw.reason === 'string' && raw.reason.trim() ? raw.reason.trim().slice(0, 300) : '';+ if (raw.shape !== 'fleet') return solo(reason || 'One bot can do this job.');+ const seen = new Set<string>();+ const crew = (Array.isArray(raw.crew) ? raw.crew : [])+ .filter((p) => p && typeof p.name === 'string' && typeof p.persona === 'string' && p.persona.length >= 20)+ .map((p) => ({+ id: (typeof p.id === 'string' && /^[a-z0-9][a-z0-9-]{0,47}$/.test(p.id) ? p.id : p.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')).slice(0, 48),+ name: p.name.slice(0, 48),+ description: (p.description ?? '').slice(0, 200),+ persona: p.persona,+ }))+ .filter((p) => p.id && !seen.has(p.id) && (seen.add(p.id), true))+ .slice(0, Math.min(5, maxCrew));+ if (crew.length < 2) return solo(reason || 'One bot can do this job.');+ return { shape: 'fleet', reason: reason || `This job has ${crew.length} separate parts.`, crew };+ } catch (err) {+ logger.warn({ name: input.name, err: (err as Error)?.message }, 'Bot shape planning failed — suggesting solo');+ return solo('Mercury couldn\'t plan this one, so it starts as a single bot.');+ }+}diff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.tsindex 4f2a3155..22adaa31 100644--- a/src/web/api/bots.test.ts+++ b/src/web/api/bots.test.ts@@ -466,3 +466,24 @@ describe('web bots API — editing routines and the inbox', () => {expect(roster.bots.find((b: { id: string }) => b.id === 'scout')).toMatchObject({ unread: 1, tier: expect.any(String) });});});++describe('web bots API — persona builder and plan', () => {+ const post = (path: string, body: unknown) =>+ app.request(path, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } });++ it('the persona builder needs some text, and says so plainly when no model can build', async () => {+ expect((await post('/api/bots/persona-builder', { text: 'hi' })).status).toBe(400);+ // The stub provider answers "ok": not a persona, so nothing is replaced.+ const res = await post('/api/bots/persona-builder', { text: 'Watch Hacker News for Rust posts and report new ones.', name: 'Rust Watch' });+ expect(res.status).toBe(503);+ expect((await jreq(res)).error).toMatch(/unchanged/);+ });++ it('the plan falls back to one bot when the model gives no usable plan, and creates nothing', async () => {+ const before = store.list().length;+ const body = await jreq(await post('/api/bots/plan', { name: 'Newsroom', description: 'News', persona: 'Write the news' }));+ expect(body.plan).toMatchObject({ shape: 'solo', crew: [] });+ expect(typeof body.maxCrew).toBe('number');+ expect(store.list().length).toBe(before);+ });+});diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex 16d298d5..8153a022 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -42,6 +42,27 @@ app.get('/api/bots/inbox', (c: Context) => {return c.json({ entries, unread: botManager.inbox.unread(botId), available: true });});+// The persona builder, for the app's editors: rough instructions in, the+// structured persona out. Nothing is saved; the owner reviews it first.+app.post('/api/bots/persona-builder', async (c: Context) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ const body = (await c.req.json().catch(() => ({}))) as { text?: unknown; name?: unknown };+ const text = typeof body.text === 'string' ? body.text.trim() : '';+ if (text.length < 10) return c.json({ error: 'Write a few words about what the bot should do first.' }, 400);+ const persona = await botManager.buildPersona(text, typeof body.name === 'string' ? body.name.slice(0, 60) : 'Bot');+ if (!persona) return c.json({ error: 'The persona builder isn\'t available right now (no model answered). Your text is unchanged.' }, 503);+ return c.json({ persona });+});++// "Let Mercury decide": one bot or a fleet for this job, and the proposed crew. Nothing is created.+app.post('/api/bots/plan', async (c: Context) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ const body = (await c.req.json().catch(() => ({}))) as { name?: unknown; description?: unknown; persona?: unknown };+ const str = (v: unknown, n: number) => (typeof v === 'string' ? v.slice(0, n) : '');+ const plan = await botManager.planShape({ name: str(body.name, 60) || 'Bot', description: str(body.description, 300), persona: str(body.persona, 8000) });+ return c.json({ plan, maxCrew: botManager.maxCrew() });+});+// Bots asking the owner mid-run: what's waiting, and the answer.app.get('/api/bots/approvals', (c: Context) => {if (!botManager) return c.json({ approvals: [], available: false });