Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): stream bot thinking into its thread + fleet speed fixes
Salman Qureshica8fc39949f0
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex 3f8fd562..d1b804c4 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -10,10 +10,11 @@ vi.mock('ai', async (importOriginal) => {return {...actual,generateText: vi.fn(),+ streamText: vi.fn(),};});-import { generateText } from 'ai';+import { generateText, streamText } from 'ai';import { BotManager } from './bot-manager.js';import { BotStore } from './store.js';import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';@@ -23,6 +24,39 @@ import type { BotManifest } from './types.js';const mockedGenerateText = vi.mocked(generateText);+const mockedStreamText = vi.mocked(streamText);+// Bot turns run on streamText (live thinking deltas). Tests script+// generateText; this shim feeds THAT script through the streaming shape the+// turn loop consumes: the (async, mocked) generateText call fires the same+// step callbacks inside fullStream consumption, and its final result shows+// up as the text/finishReason promises runBotTurn awaits.+mockedStreamText.mockImplementation(((opts: any) => {+ let final = { text: '', finishReason: 'stop', usage: {} };+ let failed: unknown = null;+ let resolveSettled: () => void = () => { };+ const settled = new Promise<void>((r) => { resolveSettled = r; });+ const gen: any = (generateText as any)(opts) || Promise.resolve(final);+ const fullStream = (async function* () {+ try {+ final = await gen;+ } catch (err) {+ failed = err; // rethrown by the text/finishReason promises below+ }+ resolveSettled();+ })();+ // Resolve only after the underlying generateText settles; its promises+ // must never reject unhandled (the fullStream consumer owns the error).+ const once = async (pick: () => any) => { await settled; if (failed !== null) throw failed; return pick(); };+ return {+ fullStream,+ text: once(() => final.text),+ finishReason: once(() => final.finishReason),+ // runBotTurn reads usage from onStepFinish — usage must never reject+ // unhandled (Promise.all only consumes text/finishReason).+ usage: once(() => final.usage).catch(() => ({})),+ };+}) as any);+function scriptedProvider(name = 'stub') {return {name,@@ -67,7 +101,8 @@ function seedBot(store: BotStore, id: string, manifestOverrides: Partial<BotMani}beforeEach(() => {- mockedGenerateText.mockReset();+ mockedStreamText.mockClear();+ mockedGenerateText.mockReset();});// Windows EBUSY guard: every BotManager owns an open SQLite queue handle;@@ -844,6 +879,26 @@ describe('Bot fleets (lead + crew)', () => {expect(await retire.execute({ id: 'guard' }, {} as any)).toContain('is not crew');});+ it('bot_spawn does not block on persona refinement (refines in background)', async () => {+ mockedStreamText.mockClear();+ mockedGenerateText.mockReset();+ // refinePersona runs provider.generateText (the scripted stub, 'ok') —+ // the OBSERVABLE contract: the tool resolves to a created crew member+ // even while the background refinement is still pending, and the raw+ // persona is what lands at creation.+ const refineSpy = vi.spyOn(manager as unknown as { schedulePersonaRefinement: (id: string, name: string, raw: string) => void }, 'schedulePersonaRefinement');+ setupFleet();+ const tools = runtimeFor('ceo').tools;+ const spawn = tools.bot_spawn as any;+ const out = await spawn.execute({ id: 'bgqa', name: 'BGQA', description: 'Background-checks spawn latency', persona: 'A meticulous background QA reviewer persona, checked for spawn latency.' }, {} as any);+ expect(out).toContain('bgqa');+ expect(refineSpy).toHaveBeenCalledWith('bgqa', 'BGQA', expect.stringContaining('QA reviewer'));+ refineSpy.mockRestore();+ // The raw persona was stored at creation; background refinement (later+ // turns) overwrites via writePersona — buildTurn re-reads it each turn.+ expect(store.readPersona('bgqa')).toContain('QA');+ });+it('multi-level fleets: a crew member can lead its own nested crew', () => {setupFleet();// Promote researcher to a mid-level lead (crew of ceo AND lead of scouts).diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 9d2f2437..ee4ce82d 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1,4 +1,4 @@-import { cpus } from 'node:os';+import { refinePersona } from './persona-template.js';import { randomUUID } from 'node:crypto';import { basename, extname, isAbsolute, relative, resolve, join } from 'node:path';import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from 'node:fs';@@ -246,8 +246,10 @@ export class BotManager {}private emitBotActivity(ev: BotActivityEvent): void {// Live roster label: keep the static job description until the first- // step arrives, then follow the actual work.- if (ev.kind !== 'turn-end') this.activity.set(ev.botId, ev.label);+ // step arrives, then follow the actual work. 'thinking' events are a+ // stream preview for threads, not a roster label — the label must stay+ // semantic (step/tool names), not the last 80 chars of reasoning.+ if (ev.kind !== 'turn-end' && ev.kind !== 'thinking') this.activity.set(ev.botId, ev.label);for (const listener of this.activityListeners) {try { listener(ev); } catch (err: any) {logger.warn({ botId: ev.botId, err: err?.message }, 'Bot activity listener failed');@@ -274,11 +276,18 @@ export class BotManager {}}- /** Fleet-wide concurrency cap: config override or clamp(2, cpus-1). */+ /**+ * Fleet-wide concurrency cap: config override or a fixed default of 8.+ * NOT cpu-derived: a bot turn is a network-bound LLM call plus small tool+ * subprocesses — a cpus()-1 cap serialized whole fleets on small VMs+ * (4 vCPU → 3 concurrent turns) while doing nothing to protect a 16-core+ * box any more than a 1-core one. Providers' own rate limits and the+ * transient-retry machinery handle 429 pressure.+ */private fleetCap(): number {const configured = this.config.bots?.maxConcurrent ?? 0;if (configured > 0) return configured;- return Math.max(2, Math.min(cpus().length - 1, 8));+ return 8;}private journalFor(botId: string): BotJournal {@@ -933,6 +942,32 @@ export class BotManager {return { ok: true, manifest };}+ /**+ * Background persona refinement — bot_spawn used to await refinePersona+ * (up to two serial LLM calls) inside the lead's TOOL EXECUTION, stalling+ * the lead's turn once per spawned crew member. The member starts on the+ * lead-written persona immediately and the refined file overwrites it+ * whenever it lands; every later turn picks it up (buildTurn re-reads the+ * persona file, so no runtime invalidation is required). Failure keeps the+ * raw persona — refinePersona's own contract.+ */+ schedulePersonaRefinement(botId: string, name: string, rawPersona: string): void {+ const manifest = this.store.get(botId);+ if (!manifest) return;+ const provider = resolveProvider(this.providers, manifest);+ void refinePersona(rawPersona, name, provider)+ .then((refined) => {+ if (!refined) return;+ try {+ this.store.writePersona(botId, refined);+ logger.info({ botId }, 'Background persona refinement landed');+ } catch (err: any) {+ logger.warn({ botId, err: err?.message }, 'Background persona write failed');+ }+ })+ .catch((err) => logger.warn({ botId, err: err?.message }, 'Background persona refinement failed'));+ }+/** 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);diff --git a/src/bots/bot-turn.test.ts b/src/bots/bot-turn.test.tsindex 1c088524..1fd5a9d1 100644--- a/src/bots/bot-turn.test.ts+++ b/src/bots/bot-turn.test.ts@@ -1,21 +1,41 @@import { describe, it, expect, beforeEach, vi } from 'vitest';-// Mock only generateText; stepCountIs must stay real so the turn loop's+// Mock only streamText; stepCountIs must stay real so the turn loop's// per-round step budget still applies. The mock must drive onStepFinish-// itself — that is the AI-SDK callback that decrements the budget.+// itself (that is the AI-SDK callback that decrements the budget) and+// return the streamText result shape: fullStream + final text/finishReason+// promises. runBotTurn consumes the deltas as live 'thinking' activity.vi.mock('ai', async (importOriginal) => {const actual = await importOriginal<typeof import('ai')>();return {...actual,- generateText: vi.fn(),+ streamText: vi.fn(),};});-import { generateText } from 'ai';-import { runBotTurn, classifyFailure, type BotTurnInput } from './bot-turn.js';+import { streamText } from 'ai';+import { runBotTurn, classifyFailure, type BotActivityEvent, type BotTurnInput } from './bot-turn.js';import { MAX_AUTOMATIC_CONTINUATIONS } from '../core/execution-limits.js';-const mockedGenerateText = vi.mocked(generateText);+const mockedStreamText = vi.mocked(streamText);++/** streamText-shaped result: async fullStream + final promise fields. */+function streamedResult(opts: { fullStream?: any[]; text: string; finishReason: string; stream?: (opts: any) => any } = { text: '', finishReason: 'stop' }) {+ return {+ fullStream: (async function* () {+ for (const part of opts.fullStream ?? []) {+ if (part.type === '__sleep__') {+ await new Promise((resolve) => setTimeout(resolve, part.ms ?? 350));+ continue;+ }+ yield part;+ }+ })(),+ text: Promise.resolve(opts.text),+ finishReason: Promise.resolve(opts.finishReason),+ usage: Promise.resolve({ inputTokens: 0, outputTokens: 0 }),+ } as any;+}function turnInput(overrides: Record<string, unknown> = {}): Parameters<typeof runBotTurn>[0] {return {@@ -46,45 +66,45 @@ function turnInput(overrides: Record<string, unknown> = {}): Parameters<typeof r}beforeEach(() => {- mockedGenerateText.mockReset();+ mockedStreamText.mockReset();});describe('runBotTurn step-budget continuation', () => {it('continues in-process with a fresh budget instead of pausing, preserving the conversation', async () => {// Round 1: burns the 2-step budget with tool calls still pending.// Round 2: finishes with text.- mockedGenerateText- .mockImplementationOnce(async (opts: any) => {+ mockedStreamText+ .mockImplementationOnce((opts: any) => {opts.onStepFinish?.({ usage: { inputTokens: 5, outputTokens: 2 }, toolCalls: [{ toolName: 'fs_write' }] });opts.onStepFinish?.({ usage: { inputTokens: 5, outputTokens: 2 }, toolCalls: [{ toolName: 'fs_write' }] });- return { text: '', finishReason: 'tool-calls', usage: { inputTokens: 10, outputTokens: 4 } } as any;+ return streamedResult({ text: '', finishReason: 'tool-calls', usage: { inputTokens: 10, outputTokens: 4 } } as any);})- .mockImplementationOnce(async (opts: any) => {+ .mockImplementationOnce((opts: any) => {opts.onStepFinish?.({ usage: { inputTokens: 5, outputTokens: 2 }, toolCalls: [] });- return { text: 'all done', finishReason: 'stop', usage: { inputTokens: 5, outputTokens: 2 } } as any;+ return streamedResult({ text: 'all done', finishReason: 'stop', usage: { inputTokens: 5, outputTokens: 2 } } as any);});const output = await runBotTurn(turnInput());expect(output.status).toBe('completed');expect(output.output).toBe('all done');- expect(mockedGenerateText).toHaveBeenCalledTimes(2);+ expect(mockedStreamText).toHaveBeenCalledTimes(2);// Tool usage from the pre-refill round is still attributed.expect(output.toolsUsed).toEqual(['fs_write']);expect(output.tokensIn).toBe(15);// The resume nudge carries the SAME conversation forward (messages grow,// not rebuild) and tells the model not to re-wrap the task.- const secondCall = mockedGenerateText.mock.calls[1][0] as any;+ const secondCall = mockedStreamText.mock.calls[1][0] as any;const nudges = secondCall.messages.filter((m: any) => String(m.content).includes('[SYSTEM: STEP BUDGET]'));expect(nudges).toHaveLength(1);});it('stays bounded: past the continuation bound it returns paused with step_budget', async () => {- mockedGenerateText.mockImplementation(async (opts: any) => {+ mockedStreamText.mockImplementation((opts: any) => {opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'fs_write' }] });opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'fs_write' }] });- return { text: '', finishReason: 'tool-calls', usage: { inputTokens: 2, outputTokens: 2 } } as any;+ return streamedResult({ text: '', finishReason: 'tool-calls', usage: { inputTokens: 2, outputTokens: 2 } } as any);});const output = await runBotTurn(turnInput());@@ -92,7 +112,7 @@ describe('runBotTurn step-budget continuation', () => {expect(output.status).toBe('paused');expect(output.reasonCode).toBe('step_budget');// Initial budget + one refill per continuation round.- expect(mockedGenerateText).toHaveBeenCalledTimes(MAX_AUTOMATIC_CONTINUATIONS + 1);+ expect(mockedStreamText).toHaveBeenCalledTimes(MAX_AUTOMATIC_CONTINUATIONS + 1);});it('network blips classify as transient (retryable), not unknown_error', () => {@@ -114,13 +134,13 @@ describe('runBotTurn step-budget continuation', () => {it('an aborted turn during continuation still reports halted, not paused', async () => {const controller = new AbortController();- mockedGenerateText- .mockImplementationOnce(async (opts: any) => {+ mockedStreamText+ .mockImplementationOnce((opts: any) => {opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [] });opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [] });- return { text: '', finishReason: 'tool-calls' } as any;+ return streamedResult({ text: '', finishReason: 'tool-calls' } as any);})- .mockImplementationOnce(async () => {+ .mockImplementationOnce(() => {controller.abort();throw new Error('Request was aborted');});@@ -129,4 +149,99 @@ describe('runBotTurn step-budget continuation', () => {expect(output.status).toBe('halted');});-});\ No newline at end of file+});+describe('runBotTurn live thinking events', () => {+ const activityEvents: any[] = [];+ function inputWithActivity(overrides: Record<string, unknown> = {}): Parameters<typeof runBotTurn>[0] {+ activityEvents.length = 0;+ return turnInput({ onActivity: (ev: BotActivityEvent) => activityEvents.push(ev), ...overrides });+ }++ it('emits cumulative reasoning/text tails at throttle boundaries and a final flush', async () => {+ mockedStreamText.mockImplementationOnce((opts: any) =>+ streamedResult({+ text: 'final reply text',+ finishReason: 'stop',+ fullStream: [+ { type: 'start-step', request: {}, warnings: [] },+ { type: 'reasoning-delta', id: 'r', text: 'I should check the prices' },+ { type: 'reasoning-delta', id: 'r', text: ' then plan the write' },+ { type: '__sleep__', ms: 350 }, // crosses the 300ms throttle boundary+ { type: 'reasoning-delta', id: 'r', text: ' and now act' },+ { type: 'text-delta', id: 't', text: 'partial reply' },+ { type: 'text-delta', id: 't', text: ' more' },+ ],+ }),+ );+ const output = await runBotTurn(inputWithActivity());++ expect(output.status).toBe('completed');+ const thinking = activityEvents.filter((e) => e.kind === 'thinking');+ // At least the crossed-throttle boundary emission + the final flush.+ expect(thinking.length).toBeGreaterThanOrEqual(2);+ const last = thinking.at(-1);+ expect(last.reasoningTail).toContain('I should check the prices');+ expect(last.reasoningTail).toContain('and now act');+ expect(last.textTail).toBe('partial reply more');+ });++ it('inserts a paragraph break at step boundaries so step narrations do not run together', async () => {+ mockedStreamText.mockImplementationOnce((opts: any) =>+ streamedResult({+ text: 'done',+ finishReason: 'stop',+ fullStream: [+ { type: 'start-step', request: {}, warnings: [] },+ { type: 'text-delta', id: 't', text: 'first step narration' },+ { type: 'start-step', request: {}, warnings: [] },+ { type: 'text-delta', id: 't', text: 'second step narration' },+ ],+ }),+ );+ const output = await runBotTurn(inputWithActivity());+ expect(output.status).toBe('completed');+ const thinking = activityEvents.filter((e) => e.kind === 'thinking');+ const lastTextTail = thinking.at(-1).textTail;+ expect(lastTextTail).toContain('first step narration');+ expect(lastTextTail).toContain('second step narration');+ expect(lastTextTail).toContain('\n\n');+ });++ it('providers without reasoning produce text tails only', async () => {+ mockedStreamText.mockImplementationOnce((opts: any) =>+ streamedResult({+ text: 'reply',+ finishReason: 'stop',+ fullStream: [+ { type: 'text-delta', id: 't', text: 'reply streaming' },+ ],+ }),+ );+ const output = await runBotTurn(inputWithActivity());+ expect(output.status).toBe('completed');+ const thinking = activityEvents.filter((e) => e.kind === 'thinking');+ expect(thinking.length).toBeGreaterThanOrEqual(1);+ expect(thinking.at(-1).textTail).toBe('reply streaming');+ expect(thinking.at(-1).reasoningTail).toBe('');+ });++ it('tails restart with each turn round (a new generation thinks anew)', async () => {+ let round = 0;+ mockedStreamText.mockImplementation((opts: any) => {+ round++;+ if (round === 1) {+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'fs_write' }] });+ return streamedResult({ text: '', finishReason: 'tool-calls', fullStream: [{ type: 'text-delta', id: 't', text: 'round one thoughts' }] });+ }+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [] });+ return streamedResult({ text: 'ok', finishReason: 'stop', fullStream: [{ type: 'text-delta', id: 't', text: 'round two thoughts' }] });+ });+ const output = await runBotTurn(inputWithActivity({ manifest: { id: 't', name: 'T', enabled: true, autonomy: { maxSteps: 1 } } as any }));+ expect(output.output).toBe('ok');+ const thinking = activityEvents.filter((e) => e.kind === 'thinking');+ const firstRound = thinking.filter((e) => e.textTail.includes('round one'));+ const secondRound = thinking.filter((e) => e.textTail.includes('round two') && !e.textTail.includes('round one'));+ expect(firstRound.length).toBeGreaterThan(0);+ expect(secondRound.length).toBeGreaterThan(0);+ });+});diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex 049a0565..c5317650 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -1,4 +1,4 @@-import { generateText, stepCountIs } from 'ai';+import { streamText, stepCountIs } from 'ai';import type { Tool } from 'ai';import type { CapabilityRegistry } from '../capabilities/registry.js';import type { UserMemoryStore } from '../memory/user-memory.js';@@ -25,13 +25,17 @@ export interface BotTurnMail {export type BotActivityEvent = {botId: string;jobId: string;- kind: 'turn-start' | 'step' | 'tool' | 'turn-end';+ kind: 'turn-start' | 'step' | 'tool' | 'turn-end' | 'thinking';/** Human-readable: "read_file ~/cookies" / "step 4 · 12.3k tok in". */label: string;detail?: string;stepIndex: number;elapsedMs: number;status?: 'running' | 'done' | 'error';+ /** kind 'thinking' only: cumulative rolling tails (raw deltas would force+ * every consumer to reassemble state — tails render stateless instead). */+ reasoningTail?: string;+ textTail?: string;};export interface BotTurnInput {@@ -79,6 +83,11 @@ export interface BotTurnOutput {const MAX_STEPS_DEFAULT = 25;+/** 'thinking' tail emission cadence — a live preview, not a firehose. */+const THINKING_EMIT_INTERVAL_MS = 300;+/** Rolling tail cap per field; surfaces render the tail bottom-anchored. */+const THINKING_TAIL_CHARS = 600;+/*** One run of one bot: a fresh-context tool loop over the bot's own provider,* persona, toolset, memory namespace, and fail-closed permission manager.@@ -111,7 +120,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {const turnStartedAt = Date.now();const toolsUsed = new Set<string>();const onActivity = input.onActivity;- const emit = (ev: { kind: BotActivityEvent['kind']; label: string; detail?: string; stepIndex: number; status?: BotActivityEvent['status']; elapsedMs?: number }): void => {+ const emit = (ev: { kind: BotActivityEvent['kind']; label: string; detail?: string; stepIndex: number; status?: BotActivityEvent['status']; elapsedMs?: number; reasoningTail?: string; textTail?: string }): void => {if (!onActivity) return;try {onActivity({@@ -123,6 +132,8 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {detail: ev.detail,stepIndex: ev.stepIndex,status: ev.status,+ reasoningTail: ev.reasoningTail,+ textTail: ev.textTail,});} catch { /* activity feedback must never break a turn */ }};@@ -130,14 +141,19 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {try {emit({ kind: 'turn-start', stepIndex: 0, label: input.prompt ? input.prompt.slice(0, 80) : 'Checking inbox' });while (stepsRemaining > 0 && !abortSignal.aborted) {- const result = await generateText({+ // streamText, not generateText: the deltas are the real-time feedback+ // inside the bot's thread (reasoning + reply tails). Same options and+ // step-count semantics; the result's final promises preserve the old+ // result shape exactly (text/finishReason), so all classification below+ // is unchanged.+ const stream = streamText({model: provider.getModelInstance(),system,messages,tools,stopWhen: stepCountIs(stepsRemaining),abortSignal,- experimental_include: { requestBody: false, responseBody: false },+ experimental_include: { requestBody: false },experimental_onStepStart: () => {stepIndex++;emit({ kind: 'step', stepIndex, label: `step ${stepIndex}` });@@ -171,6 +187,37 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {emit({ kind: 'step', stepIndex, label: `step ${stepIndex} · ${kIn}k tok in` });},});++ // Live thinking feedback: consume the full stream, accumulate rolling+ // tails, emit at most every THINKING_EMIT_INTERVAL_MS (a TUI re-render+ // per delta would thrash ink). Tails are per-round: a new generation+ // round starts thinking anew. Step boundaries insert a paragraph break+ // so multi-step narrations don't run together (same fix as the main+ // chat's stepAwareTextStream).+ let reasoningTail = '';+ let textTail = '';+ let lastEmit = 0;+ const flushThinking = (): void => {+ if (!onActivity) return;+ if (!reasoningTail && !textTail) return;+ lastEmit = Date.now();+ emit({ kind: 'thinking', stepIndex, label: 'thinking', reasoningTail, textTail });+ };+ for await (const part of stream.fullStream) {+ if (part.type === 'reasoning-delta' && part.text) {+ reasoningTail = (reasoningTail + part.text).slice(-THINKING_TAIL_CHARS);+ } else if (part.type === 'text-delta' && part.text) {+ textTail = (textTail + part.text).slice(-THINKING_TAIL_CHARS);+ } else if (part.type === 'start-step' && (reasoningTail || textTail)) {+ reasoningTail += '\n\n';+ textTail += '\n\n';+ }+ if (Date.now() - lastEmit >= THINKING_EMIT_INTERVAL_MS) flushThinking();+ }+ flushThinking();++ const [finalText, finishReason] = await Promise.all([stream.text, stream.finishReason]);+ const result = { text: finalText, finishReason };lastResult = result;const completion = classifyStreamCompletion({diff --git a/src/bots/fleet-delegation.test.ts b/src/bots/fleet-delegation.test.tsindex baeb9740..c624c353 100644--- a/src/bots/fleet-delegation.test.ts+++ b/src/bots/fleet-delegation.test.ts@@ -7,16 +7,49 @@ import { join } from 'node:path';// bot_send / fleet tools construct through the real registry factories.vi.mock('ai', async (importOriginal) => {const actual = await importOriginal<typeof import('ai')>();- return { ...actual, generateText: vi.fn() };+ return { ...actual, generateText: vi.fn(), streamText: vi.fn() };});-import { generateText } from 'ai';+import { generateText, streamText } from 'ai';import { BotManager } from './bot-manager.js';import { BotStore } from './store.js';import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';const mockedGenerateText = vi.mocked(generateText);+const mockedStreamText = vi.mocked(streamText);+// Bot turns run on streamText (live thinking deltas). Tests script+// generateText; this shim feeds THAT script through the streaming shape the+// turn loop consumes: the (async, mocked) generateText call fires the same+// step callbacks inside fullStream consumption, and its final result shows+// up as the text/finishReason promises runBotTurn awaits.+mockedStreamText.mockImplementation(((opts: any) => {+ let final = { text: '', finishReason: 'stop', usage: {} };+ let failed: unknown = null;+ let resolveSettled: () => void = () => { };+ const settled = new Promise<void>((r) => { resolveSettled = r; });+ const gen: any = (generateText as any)(opts) || Promise.resolve(final);+ const fullStream = (async function* () {+ try {+ final = await gen;+ } catch (err) {+ failed = err; // rethrown by the text/finishReason promises below+ }+ resolveSettled();+ })();+ // Resolve only after the underlying generateText settles; its promises+ // must never reject unhandled (the fullStream consumer owns the error).+ const once = async (pick: () => any) => { await settled; if (failed !== null) throw failed; return pick(); };+ return {+ fullStream,+ text: once(() => final.text),+ finishReason: once(() => final.finishReason),+ // runBotTurn reads usage from onStepFinish — usage must never reject+ // unhandled (Promise.all only consumes text/finishReason).+ usage: once(() => final.usage).catch(() => ({})),+ };+}) as any);+function makeManager(root: string): BotManager {const config = getDefaultConfig() as MercuryConfig;config.bots.maxConcurrent = 4;@@ -40,7 +73,8 @@ function makeManager(root: string): BotManager {}beforeEach(() => {- mockedGenerateText.mockReset();+ mockedStreamText.mockClear();+ mockedGenerateText.mockReset();});// Windows EBUSY guard: every BotManager owns an open SQLite queue handle;diff --git a/src/bots/fleet-stop-start.test.ts b/src/bots/fleet-stop-start.test.tsindex 2d87c651..1e544619 100644--- a/src/bots/fleet-stop-start.test.ts+++ b/src/bots/fleet-stop-start.test.ts@@ -6,16 +6,49 @@ import { join } from 'node:path';// Mock only generateText; tool()/zodSchema/stepCountIs stay real.vi.mock('ai', async (importOriginal) => {const actual = await importOriginal<typeof import('ai')>();- return { ...actual, generateText: vi.fn() };+ return { ...actual, generateText: vi.fn(), streamText: vi.fn() };});-import { generateText } from 'ai';+import { generateText, streamText } from 'ai';import { BotManager } from './bot-manager.js';import { BotStore } from './store.js';import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';const mockedGenerateText = vi.mocked(generateText);+const mockedStreamText = vi.mocked(streamText);+// Bot turns run on streamText (live thinking deltas). Tests script+// generateText; this shim feeds THAT script through the streaming shape the+// turn loop consumes: the (async, mocked) generateText call fires the same+// step callbacks inside fullStream consumption, and its final result shows+// up as the text/finishReason promises runBotTurn awaits.+mockedStreamText.mockImplementation(((opts: any) => {+ let final = { text: '', finishReason: 'stop', usage: {} };+ let failed: unknown = null;+ let resolveSettled: () => void = () => { };+ const settled = new Promise<void>((r) => { resolveSettled = r; });+ const gen: any = (generateText as any)(opts) || Promise.resolve(final);+ const fullStream = (async function* () {+ try {+ final = await gen;+ } catch (err) {+ failed = err; // rethrown by the text/finishReason promises below+ }+ resolveSettled();+ })();+ // Resolve only after the underlying generateText settles; its promises+ // must never reject unhandled (the fullStream consumer owns the error).+ const once = async (pick: () => any) => { await settled; if (failed !== null) throw failed; return pick(); };+ return {+ fullStream,+ text: once(() => final.text),+ finishReason: once(() => final.finishReason),+ // runBotTurn reads usage from onStepFinish — usage must never reject+ // unhandled (Promise.all only consumes text/finishReason).+ usage: once(() => final.usage).catch(() => ({})),+ };+}) as any);+function makeManager(root: string): BotManager {const config = getDefaultConfig() as MercuryConfig;config.bots.maxConcurrent = 4;@@ -39,7 +72,8 @@ function makeManager(root: string): BotManager {}beforeEach(() => {- mockedGenerateText.mockReset();+ mockedStreamText.mockClear();+ mockedGenerateText.mockReset();});// Windows EBUSY guard: every BotManager owns an open SQLite queue handle;diff --git a/src/bots/queue.test.ts b/src/bots/queue.test.tsindex 6fc53bec..97a32343 100644--- a/src/bots/queue.test.ts+++ b/src/bots/queue.test.ts@@ -6,11 +6,44 @@ import { join } from 'node:path';// Mock generateText; keep the rest of the ai module real for tool factories.vi.mock('ai', async (importOriginal) => {const actual = await importOriginal<typeof import('ai')>();- return { ...actual, generateText: vi.fn() };+ return { ...actual, generateText: vi.fn(), streamText: vi.fn() };});-import { generateText } from 'ai';+import { generateText, streamText } from 'ai';const mockedGenerateText = vi.mocked(generateText);++const mockedStreamText = vi.mocked(streamText);+// Bot turns run on streamText (live thinking deltas). Tests script+// generateText; this shim feeds THAT script through the streaming shape the+// turn loop consumes: the (async, mocked) generateText call fires the same+// step callbacks inside fullStream consumption, and its final result shows+// up as the text/finishReason promises runBotTurn awaits.+mockedStreamText.mockImplementation(((opts: any) => {+ let final = { text: '', finishReason: 'stop', usage: {} };+ let failed: unknown = null;+ let resolveSettled: () => void = () => { };+ const settled = new Promise<void>((r) => { resolveSettled = r; });+ const gen: any = (generateText as any)(opts) || Promise.resolve(final);+ const fullStream = (async function* () {+ try {+ final = await gen;+ } catch (err) {+ failed = err; // rethrown by the text/finishReason promises below+ }+ resolveSettled();+ })();+ // Resolve only after the underlying generateText settles; its promises+ // must never reject unhandled (the fullStream consumer owns the error).+ const once = async (pick: () => any) => { await settled; if (failed !== null) throw failed; return pick(); };+ return {+ fullStream,+ text: once(() => final.text),+ finishReason: once(() => final.finishReason),+ // runBotTurn reads usage from onStepFinish — usage must never reject+ // unhandled (Promise.all only consumes text/finishReason).+ usage: once(() => final.usage).catch(() => ({})),+ };+}) as any);import { BotQueue, JsonFileQueueBackend, SqliteQueueBackend, idempotencyKeyFor, LEASE_SECONDS } from './queue.js';import type { DurableBotJob } from './queue.js';@@ -255,6 +288,7 @@ describe('BotManager durable queue integration', () => {});it('persists jobs before ack and dedupes identical pending sends', async () => {+ mockedStreamText.mockClear();mockedGenerateText.mockReset();mockedGenerateText.mockResolvedValue({ text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any);store.create({ id: 'alpha', name: 'Alpha' });@@ -272,6 +306,7 @@ describe('BotManager durable queue integration', () => {});it('permanent failures land in the DLQ and are replayable', async () => {+ mockedStreamText.mockClear();mockedGenerateText.mockReset();mockedGenerateText.mockRejectedValue(new Error('permission denied: workspace'));store.create({ id: 'alpha', name: 'Alpha' });@@ -290,6 +325,7 @@ describe('BotManager durable queue integration', () => {it('replaying a job under the WRONG bot id does not destroy the DLQ entry', async () => {// The old replayDlq removed the entry BEFORE checking the bot — a// mismatch permanently deleted real work and still reported not_found.+ mockedStreamText.mockClear();mockedGenerateText.mockReset();mockedGenerateText.mockRejectedValue(new Error('permission denied: workspace'));store.create({ id: 'alpha', name: 'Alpha' });diff --git a/src/bots/tools/bot-spawn.ts b/src/bots/tools/bot-spawn.tsindex d7331cdc..9dee914d 100644--- a/src/bots/tools/bot-spawn.ts+++ b/src/bots/tools/bot-spawn.ts@@ -1,8 +1,6 @@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>;@@ -38,16 +36,19 @@ function createSpawnTool(manager: BotManager, leadId: string, maxCrew: number) {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 });+ // No await on refinePersona: it is 1-2 serial LLM calls and used to+ // run INSIDE this tool, stalling the lead's turn once per spawned+ // crew member. The member starts on the lead-written persona right+ // away; refinement lands in the background and overwrites the file.+ const result = manager.addCrew(leadId, { id, name, description, persona });if (!result.ok) {return `Error: ${result.error}`;}if (result.duplicate) {return `**${result.manifest.name}** (\`${result.manifest.id}\`) is already on your crew — no new bot created. Check your roster (fleet_status / bot list) before spawning replacements.`;}- 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.`;+ manager.schedulePersonaRefinement(result.manifest.id, name, persona);+ return `Crew member created: **${name}** (${result.manifest.id}) — fail-closed defaults, comms linked to you, persona being refined in the background. Dispatch tasks with bot_send (task: true); its results will arrive in your mailbox.`;},});}diff --git a/src/channels/cli-bot-live.test.ts b/src/channels/cli-bot-live.test.tsindex d25980a9..16200d67 100644--- a/src/channels/cli-bot-live.test.ts+++ b/src/channels/cli-bot-live.test.ts@@ -36,4 +36,36 @@ describe('CLIChannel per-bot live activity', () => {expect(ch.getTuiState().botLiveActivity['other']).toBeDefined();expect(ch.getTuiState().botLiveActivity['worker']).toBeUndefined();});-});\ No newline at end of file+});+describe('CLIChannel bot thinking stream tails', () => {+ const ch = new CLIChannel();++ ch.setBotLiveActivity('worker', { kind: 'turn-start', label: 'scrape the prices' });+ ch.setBotLiveActivity('worker', { kind: 'thinking', label: 'thinking', reasoningTail: 'I should scrape prices…', textTail: '' });+ it('stores the bot tail in botStreamTails', () => {+ expect(ch.getTuiState().botStreamTails?.['worker']).toEqual({ reasoning: 'I should scrape prices…', text: '' });+ });++ it('skips identical tail updates (no ink churn)', () => {+ ch.setBotLiveActivity('worker', { kind: 'thinking', label: 'thinking', reasoningTail: 'I should scrape prices…', textTail: '' });+ expect(ch.getTuiState().botStreamTails?.['worker']).toEqual({ reasoning: 'I should scrape prices…', text: '' });+ });++ it('updates the tail as the stream progresses', () => {+ ch.setBotLiveActivity('worker', { kind: 'thinking', label: 'thinking', reasoningTail: '…', textTail: 'partial reply' });+ expect(ch.getTuiState().botStreamTails?.['worker']).toEqual({ reasoning: '…', text: 'partial reply' });+ });++ it('a fresh turn discards the leftover tail', () => {+ ch.setBotLiveActivity('worker', { kind: 'turn-start', label: 'new task' });+ expect(ch.getTuiState().botStreamTails?.['worker']).toBeUndefined();+ expect(ch.getTuiState().botLiveActivity['worker']).toMatchObject({ phase: 'Working', detail: 'new task' });+ });++ it('turn-end clears both the live region and the tail', () => {+ ch.setBotLiveActivity('worker', { kind: 'thinking', label: 'thinking', reasoningTail: 'still thinking', textTail: '' });+ ch.setBotLiveActivity('worker', { kind: 'turn-end', label: 'completed' });+ expect(ch.getTuiState().botLiveActivity['worker']).toBeUndefined();+ expect(ch.getTuiState().botStreamTails?.['worker']).toBeUndefined();+ });+});diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 5b1c767c..966cce65 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -329,6 +329,9 @@ export interface TuiState {/** Per-bot real-time activity (what each bot is doing RIGHT NOW) — rendered* as a live region in an open bot thread, keyed by bot id. */botLiveActivity: Record<string, LiveActivityState>;+ /** Per-bot streaming tails (what each bot is THINKING / replying right now,+ * from the bot turn's reasoning/text deltas) — rendered live in its thread. */+ botStreamTails: Record<string, { reasoning: string; text: string }>;/** Live bot roster (drives `/bots` argument autocomplete and badges). */botRoster: Array<{ id: string; name: string; state: string; needsYou: boolean; fleetRole?: 'lead' | 'crew'; parent?: string }>;}@@ -367,6 +370,7 @@ const defaultState: TuiState = {updateAvailable: null,botChat: null,botLiveActivity: {},+ botStreamTails: {},botRoster: [],};@@ -1799,14 +1803,34 @@ export class CLIChannel extends BaseChannel {* gets). Events arrive from the bot activity bus (BotManager.onBotActivity).* Mapping: turn-start → "Working on: <task>"; step/tool labels follow the* actual work; tool finishes keep the last running label (less churn);- * turn-end clears the region.+ * 'thinking' carries the bot's live reasoning/reply tails and lands in+ * botStreamTails so the open thread renders what it is thinking;+ * turn-end clears the region (and the tails).*/- setBotLiveActivity(botId: string, ev: { kind: 'turn-start' | 'step' | 'tool' | 'turn-end'; label: string; detail?: string; status?: string }): void {+ setBotLiveActivity(botId: string, ev: { kind: 'turn-start' | 'step' | 'tool' | 'turn-end' | 'thinking'; label: string; detail?: string; status?: string; reasoningTail?: string; textTail?: string }): void {const map = { ...this.state.botLiveActivity };if (ev.kind === 'turn-end') {- if (!map[botId]) return;+ if (!map[botId]) {+ const tails = { ...this.state.botStreamTails };+ if (!tails[botId]) return;+ delete tails[botId];+ this.update({ botStreamTails: tails });+ return;+ }delete map[botId];- this.update({ botLiveActivity: map });+ const tails = { ...this.state.botStreamTails };+ delete tails[botId];+ this.update({ botLiveActivity: map, botStreamTails: tails });+ return;+ }+ if (ev.kind === 'thinking') {+ // Skip when the tail hasn't changed — ink re-renders every update and+ // the streaming cadence (300ms) must not paint identical frames.+ const tails = { ...this.state.botStreamTails };+ const prev = tails[botId];+ if (prev && prev.reasoning === (ev.reasoningTail ?? '') && prev.text === (ev.textTail ?? '')) return;+ tails[botId] = { reasoning: ev.reasoningTail ?? '', text: ev.textTail ?? '' };+ this.update({ botStreamTails: tails });return;}// A finished tool keeps its label until the next event — the region@@ -1823,6 +1847,15 @@ export class CLIChannel extends BaseChannel {stepsDone: ev.kind === 'step' ? (existing?.stepsDone ?? 0) + 1 : (existing?.stepsDone ?? 0),startedAt: existing?.startedAt ?? Date.now(),};+ // A fresh turn starts thinking anew — any leftover tail (missed turn-end,+ // restart) must not bleed into the new turn's preview.+ const staleTail = ev.kind === 'turn-start' && this.state.botStreamTails[botId];+ if (staleTail) {+ const tails = { ...this.state.botStreamTails };+ delete tails[botId];+ this.update({ botLiveActivity: map, botStreamTails: tails });+ return;+ }this.update({ botLiveActivity: map });}diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 7390a6eb..76274c11 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -1271,6 +1271,7 @@ function ChatBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLinesbotId={state.botChat.botId}botName={state.botChat.botName}botLiveActivity={state.botLiveActivity ?? {}}+ botStreamTails={state.botStreamTails ?? {}}botRoster={state.botRoster}/>)}@@ -1329,6 +1330,7 @@ function CodingBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLinbotId={state.botChat.botId}botName={state.botChat.botName}botLiveActivity={state.botLiveActivity ?? {}}+ botStreamTails={state.botStreamTails ?? {}}botRoster={state.botRoster}/>)}@@ -2104,16 +2106,18 @@ function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPrevi* (CEO → Eng Lead → Backend). One self-ticker drives all rows; the rows* also refresh on every activity event.*/-function BotFleetLiveRegion({ botId, botName, botLiveActivity, botRoster }: {+function BotFleetLiveRegion({ botId, botName, botLiveActivity, botStreamTails, botRoster }: {botId: string;botName: string;botLiveActivity: Record<string, LiveActivityState>;+ botStreamTails: Record<string, { reasoning: string; text: string }>;botRoster: Array<{ id: string; name: string; state: string; fleetRole?: 'lead' | 'crew'; parent?: string }>;}) {const own = botLiveActivity[botId];const crew = botRoster.filter(b => b.parent === botId);const crewLive = crew.filter(c => botLiveActivity[c.id]);- if (!own && crewLive.length === 0) return null;+ const ownTail = botStreamTails[botId];+ if (!own && crewLive.length === 0 && !ownTail) return null;const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];const [tick, setTick] = React.useState(0);@@ -2143,8 +2147,28 @@ function BotFleetLiveRegion({ botId, botName, botLiveActivity, botRoster }: {return out;};+ // What the open bot is THINKING — the streaming tails from its turn's+ // provider deltas (reasoning first, then any reply text being composed).+ const tailSegment = (text: string, kind: 'reasoning' | 'reply'): React.ReactNode[] => {+ const lines = text.replace(/\n+$/, '').split('\n').slice(-BOT_TAIL_MAX_ROWS);+ return lines.map((line, idx) => (+ <Box key={`${kind}:${idx}`} marginLeft={6}>+ <Text dimColor={kind === 'reasoning'}>{kind === 'reasoning' ? ` ${line}` : line}</Text>+ </Box>+ ));+ };+ const openTail = ownTail ? [+ ...tailSegment(ownTail.reasoning.trim(), 'reasoning'),+ ...tailSegment(ownTail.text.trim(), 'reply'),+ ] : [];+return (<Box marginTop={1} marginLeft={4} flexDirection="column">+ {openTail.length > 0 && (+ <Box flexDirection="column" marginBottom={1}>+ {openTail}+ </Box>+ )}{own && row(botId, botName, own.detail || own.phase, '')}{crewLive.length > 0 && <Text dimColor> └ crew working ({crewLive.length}):</Text>}{renderCrewTree(botId, 1)}@@ -2377,6 +2401,8 @@ function PlanProgressView({ steps }: { steps: PlanStep[] }): React.ReactNode {/** Live streaming tail budget: chars of the stream buffer rendered per frame. */const STREAM_TAIL_CHARS = 32 * 1024;+/** Live bot-thinking tail cap (rows) in an open bot thread. */+const BOT_TAIL_MAX_ROWS = 8;const STREAM_TAIL_MIN_LINES = 6;/** Absolute ceiling on live tail rows: bounds per-frame markdown + highlight* work regardless of terminal height. */diff --git a/ui/src/components/bots/useBotEvents.ts b/ui/src/components/bots/useBotEvents.tsindex 33750bc2..5054c846 100644--- a/ui/src/components/bots/useBotEvents.ts+++ b/ui/src/components/bots/useBotEvents.ts@@ -30,9 +30,12 @@ export function useBotEvents(): BotEventState {try {const ev = JSON.parse((e as MessageEvent).data) as {botId: string;- kind: "turn-start" | "step" | "tool" | "turn-end";+ kind: "turn-start" | "step" | "tool" | "turn-end" | "thinking";label: string;};+ // 'thinking' events carry the live stream tail for threads/chattier+ // surfaces; the dashboard roster wants semantic work labels only.+ if (ev.kind === "thinking") return;// 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 ")) {