osborn 0.9.282 → 0.9.283

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1887 @@
1
+ /**
2
+ * Fast Brain — Central Orchestrator for the Voice AI System
3
+ *
4
+ * The sole intelligence layer between the user and all backend capabilities.
5
+ * The realtime voice model is a thin teleprompter — it speaks what this module returns.
6
+ *
7
+ * Capabilities:
8
+ * - Read/write session files (spec.md)
9
+ * - Web search for quick factual lookups
10
+ * - Record user decisions and preferences into spec.md
11
+ * - Trigger deep research (via callbacks to index.ts)
12
+ * - Generate teleprompter scripts for ALL voice output
13
+ * - Post-research: synthesize findings from JSONL into spec.md + voice scripts
14
+ * - Generate visual documents (comparison, diagram, analysis, summary)
15
+ *
16
+ * Central function: askFastBrain() — ALL user questions route here.
17
+ * It returns a FastBrainResponse with a teleprompter script the voice model reads verbatim.
18
+ *
19
+ * Auth chain (tried in order):
20
+ * 1. ANTHROPIC_API_KEY env var → Anthropic SDK (Haiku)
21
+ * 2. ANTHROPIC_AUTH_TOKEN env var → Anthropic SDK (Haiku)
22
+ * 3. GOOGLE_API_KEY env var → Gemini Flash fallback
23
+ */
24
+ import Anthropic from '@anthropic-ai/sdk';
25
+ import { query as sdkQuery, tool as sdkTool, createSdkMcpServer } from '@anthropic-ai/claude-agent-sdk';
26
+ import { GoogleGenAI } from '@google/genai';
27
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
28
+ import { dirname, basename } from 'path';
29
+ import { z } from 'zod';
30
+ import { getSessionWorkspace, readSessionSpec } from './config.js';
31
+ import { FAST_BRAIN_SYSTEM_PROMPT, CHUNK_PROCESS_SYSTEM, REFINEMENT_PROCESS_SYSTEM, AUGMENT_RESULT_SYSTEM, CONTEXTUALIZE_UPDATE_SYSTEM, PROACTIVE_PROMPT_SYSTEM, VISUAL_DOCUMENT_SYSTEM, RESEARCH_COMPLETION_SYSTEM, buildFastBrainSdkPrompt } from './prompts.js';
32
+ import { getRecentToolResults, readSessionHistory, getSubagentTranscripts, getConversationText, getSessionTranscripts, searchSessionJsonl, getSessionStats } from './session-access.js';
33
+ // ============================================================
34
+ // Content extraction — pulls useful snippets from tool responses
35
+ // ============================================================
36
+ /**
37
+ * Extract useful content snippets from tool responses, truncated by tool type.
38
+ * Returns null for tools with no useful content (Write confirmations, etc.)
39
+ */
40
+ export function extractToolContent(toolName, toolInput, toolResponse) {
41
+ if (!toolResponse)
42
+ return null;
43
+ const response = typeof toolResponse === 'string' ? toolResponse : JSON.stringify(toolResponse);
44
+ if (response.length < 20)
45
+ return null; // Skip trivial responses
46
+ switch (toolName) {
47
+ case 'Read':
48
+ return `[File: ${basename(toolInput?.file_path || 'unknown')}]\n${response.slice(0, 600)}`;
49
+ case 'Bash':
50
+ return `[Command: ${(toolInput?.command || '').slice(0, 80)}]\n${response.slice(0, 400)}`;
51
+ case 'Grep':
52
+ return `[Search: "${toolInput?.pattern}"]\n${response.slice(0, 600)}`;
53
+ case 'WebSearch':
54
+ return `[Web: "${toolInput?.query}"]\n${response.slice(0, 800)}`;
55
+ case 'WebFetch':
56
+ return `[Page: ${toolInput?.url}]\n${response.slice(0, 800)}`;
57
+ case 'Glob':
58
+ return `[Files matching: ${toolInput?.pattern}]\n${response.slice(0, 400)}`;
59
+ case 'Write':
60
+ case 'Edit':
61
+ return null; // Skip write confirmations
62
+ default:
63
+ if (toolName.startsWith('mcp__'))
64
+ return `[${toolName}]\n${response.slice(0, 500)}`;
65
+ return null;
66
+ }
67
+ }
68
+ let provider = 'none';
69
+ let anthropicClient = null;
70
+ let geminiClient = null;
71
+ let initialized = false;
72
+ // Model IDs — configurable per provider
73
+ const ANTHROPIC_FAST_MODEL = 'claude-haiku-4-5-20251001';
74
+ const GEMINI_FAST_MODEL = 'gemini-2.5-flash'; // 0.9.67: was gemini-2.0-flash — 404 deprecated by Google (verified against @livekit/agents-plugin-google test default)
75
+ // Agent SDK session tracking — resume across voice questions for context continuity
76
+ let fastBrainSessionId = null;
77
+ // Gemini Chat session — persists across voice questions for context continuity.
78
+ // The Chat object auto-manages full conversation history (messages + tool calls).
79
+ // Cleared on disconnect/reconnect/session switch via clearFastBrainSession().
80
+ let geminiChat = null;
81
+ const MAX_FAST_BRAIN_HISTORY = 30;
82
+ let fastBrainHistory = [];
83
+ /** Clear fast brain session state — call on disconnect/reconnect/session switch */
84
+ export function clearFastBrainSession() {
85
+ fastBrainSessionId = null;
86
+ geminiChat = null;
87
+ fastBrainHistory = [];
88
+ console.log('🧠 Fast brain: session cleared (SDK + Gemini chat + Anthropic history)');
89
+ }
90
+ /** @deprecated Use clearFastBrainSession() instead */
91
+ export function clearFastBrainHistory() {
92
+ clearFastBrainSession();
93
+ }
94
+ function initProvider() {
95
+ if (initialized)
96
+ return;
97
+ initialized = true;
98
+ // Initialize fallback clients (Gemini for fallback, Anthropic direct API if key available)
99
+ const googleKey = process.env.GOOGLE_API_KEY;
100
+ if (googleKey) {
101
+ geminiClient = new GoogleGenAI({ apiKey: googleKey });
102
+ }
103
+ const apiKey = process.env.ANTHROPIC_API_KEY;
104
+ if (apiKey) {
105
+ anthropicClient = new Anthropic({ apiKey });
106
+ }
107
+ else {
108
+ const authToken = process.env.ANTHROPIC_AUTH_TOKEN;
109
+ if (authToken) {
110
+ anthropicClient = new Anthropic({ authToken });
111
+ }
112
+ }
113
+ // PRIMARY: Gemini Flash — fastest (~1-2s), handles 1M tokens, no cold start.
114
+ // Agent SDK Haiku is too slow (~10-15s) due to CLI process spawn + session overhead.
115
+ if (geminiClient) {
116
+ provider = 'gemini';
117
+ console.log(`🧠 Fast brain: using Gemini Flash (primary) — fastest response time`);
118
+ if (anthropicClient) {
119
+ console.log(`🧠 Fast brain: Direct Anthropic API available as fallback`);
120
+ }
121
+ }
122
+ else if (anthropicClient) {
123
+ provider = 'anthropic';
124
+ console.log(`🧠 Fast brain: using Anthropic API (primary) — no Gemini key available`);
125
+ }
126
+ else {
127
+ // Last resort: Agent SDK is slow but functional
128
+ provider = 'agent-sdk';
129
+ console.log(`🧠 Fast brain: using Claude Agent SDK (fallback) — no API keys available`);
130
+ }
131
+ }
132
+ // ============================================================
133
+ // Tool execution (shared across providers)
134
+ // ============================================================
135
+ // Track whether send_to_chat was called during a fast brain conversation.
136
+ // If the LLM calls send_to_chat but returns no text, we use a fallback
137
+ // instead of "No answer found."
138
+ let sendToChatCalledThisTurn = false;
139
+ function executeTool(toolName, toolInput, workspace, sessionId, workingDir, sendToChat) {
140
+ try {
141
+ switch (toolName) {
142
+ case 'read_file': {
143
+ const relPath = toolInput.path;
144
+ if (relPath.includes('..'))
145
+ return 'Error: path traversal not allowed';
146
+ const ext = relPath.toLowerCase().split('.').pop() || '';
147
+ const BINARY_EXTS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'pdf', 'mp3', 'wav', 'mp4', 'mov'];
148
+ if (BINARY_EXTS.includes(ext))
149
+ return `Binary file (${ext}) — cannot read as text.`;
150
+ const fullPath = `${workspace}/${relPath}`;
151
+ if (!existsSync(fullPath))
152
+ return `File not found: ${relPath}`;
153
+ const content = readFileSync(fullPath, 'utf-8');
154
+ return content || '(empty file)';
155
+ }
156
+ case 'write_file': {
157
+ const relPath = toolInput.path;
158
+ const content = toolInput.content;
159
+ if (relPath.includes('..'))
160
+ return 'Error: path traversal not allowed';
161
+ const fullPath = `${workspace}/${relPath}`;
162
+ mkdirSync(dirname(fullPath), { recursive: true });
163
+ writeFileSync(fullPath, content, 'utf-8');
164
+ console.log(`📝 Fast brain wrote ${relPath} (${content.length} chars)`);
165
+ return `Written: ${relPath} (${content.length} chars)`;
166
+ }
167
+ case 'read_agent_results': {
168
+ if (!sessionId || !workingDir)
169
+ return 'Error: no active research session';
170
+ const lastN = toolInput.lastN || 40;
171
+ const toolFilter = toolInput.toolFilter;
172
+ const results = getRecentToolResults(sessionId, workingDir, lastN, { toolNameFilter: toolFilter });
173
+ if (results.length === 0)
174
+ return `No tool results found${toolFilter ? ` for tools: ${toolFilter.join(', ')}` : ''}.`;
175
+ return `[${results.length} results${toolFilter ? ` filtered by: ${toolFilter.join(', ')}` : ''}]\n\n` +
176
+ results.map(tr => {
177
+ const inputPreview = JSON.stringify(tr.toolInput).substring(0, 200);
178
+ return `[${tr.toolName}: ${inputPreview}]\n${tr.resultContent}`;
179
+ }).join('\n\n---\n\n');
180
+ }
181
+ case 'read_agent_text': {
182
+ if (!sessionId || !workingDir)
183
+ return 'Error: no active research session';
184
+ const lastN = toolInput.lastN || 60;
185
+ const opts = lastN === 0
186
+ ? { types: ['assistant'] }
187
+ : { lastN, types: ['assistant'] };
188
+ const messages = readSessionHistory(sessionId, workingDir, opts);
189
+ const texts = messages.filter(m => m.text && m.text.length > 20);
190
+ if (texts.length === 0)
191
+ return 'No agent reasoning text found in JSONL.';
192
+ return `[${texts.length} agent messages]\n\n` + texts.map(m => m.text).join('\n\n---\n\n');
193
+ }
194
+ case 'read_subagents': {
195
+ if (!sessionId || !workingDir)
196
+ return 'Error: no active research session';
197
+ const transcripts = getSubagentTranscripts(sessionId, workingDir);
198
+ if (transcripts.length === 0)
199
+ return 'No sub-agent transcripts found.';
200
+ return transcripts.map(sa => {
201
+ const texts = sa.messages
202
+ .filter(m => m.text && m.text.length > 20)
203
+ .map(m => `[${m.type}] ${m.text}`);
204
+ return `=== Sub-agent ${sa.taskId} (${sa.messages.length} msgs) ===\n${texts.join('\n')}`;
205
+ }).join('\n\n');
206
+ }
207
+ case 'search_jsonl': {
208
+ if (!sessionId || !workingDir)
209
+ return 'Error: no active research session';
210
+ const keyword = toolInput.keyword;
211
+ if (!keyword)
212
+ return 'Error: keyword is required';
213
+ const maxResults = toolInput.maxResults || 20;
214
+ const results = searchSessionJsonl(sessionId, workingDir, keyword, { maxResults });
215
+ if (results.length === 0)
216
+ return `No matches for "${keyword}" in agent JSONL.`;
217
+ return results.map(r => `[${r.type}${r.timestamp ? ` @ ${r.timestamp}` : ''}] ${r.text}`).join('\n\n---\n\n');
218
+ }
219
+ case 'read_conversation': {
220
+ if (!sessionId || !workingDir)
221
+ return 'Error: no active research session';
222
+ const lastN = toolInput.lastN || 30;
223
+ const exchanges = getConversationText(sessionId, workingDir, lastN, 2000);
224
+ if (exchanges.length === 0)
225
+ return 'No conversation history found.';
226
+ return exchanges.map(e => `${e.role}: ${e.text}`).join('\n\n');
227
+ }
228
+ case 'get_session_stats': {
229
+ if (!sessionId || !workingDir)
230
+ return 'Error: no active research session';
231
+ const stats = getSessionStats(sessionId, workingDir);
232
+ if (!stats)
233
+ return 'No session data found.';
234
+ const toolList = Object.entries(stats.toolBreakdown)
235
+ .sort(([, a], [, b]) => b - a)
236
+ .map(([name, count]) => ` ${name}: ${count}`)
237
+ .join('\n');
238
+ return `Session Stats:
239
+ Total messages: ${stats.totalMessages}
240
+ User messages: ${stats.userMessages}
241
+ Agent messages: ${stats.assistantMessages}
242
+ Tool calls: ${stats.toolUseCount}
243
+ Tool results: ${stats.toolResultCount}
244
+ Sub-agents: ${stats.subagentCount}
245
+ File size: ${(stats.fileSizeBytes / 1024).toFixed(1)} KB
246
+ Time range: ${stats.firstTimestamp || '?'} → ${stats.lastTimestamp || '?'}
247
+
248
+ Tool breakdown:
249
+ ${toolList}`;
250
+ }
251
+ case 'deep_read_results': {
252
+ if (!sessionId || !workingDir)
253
+ return 'Error: no active research session';
254
+ const toolFilter = toolInput.toolFilter;
255
+ const allResults = getRecentToolResults(sessionId, workingDir, 0, { toolNameFilter: toolFilter });
256
+ if (allResults.length === 0)
257
+ return `No tool results found${toolFilter ? ` for tools: ${toolFilter.join(', ')}` : ''}.`;
258
+ return `[${allResults.length} total results${toolFilter ? ` filtered by: ${toolFilter.join(', ')}` : ' (all tools)'}]\n\n` +
259
+ allResults.map(tr => {
260
+ const inputPreview = JSON.stringify(tr.toolInput).substring(0, 200);
261
+ return `[${tr.toolName}: ${inputPreview}]\n${tr.resultContent}`;
262
+ }).join('\n\n---\n\n');
263
+ }
264
+ case 'deep_read_text': {
265
+ if (!sessionId || !workingDir)
266
+ return 'Error: no active research session';
267
+ const allMessages = readSessionHistory(sessionId, workingDir, {
268
+ types: ['assistant']
269
+ });
270
+ const allTexts = allMessages.filter(m => m.text && m.text.length > 20);
271
+ if (allTexts.length === 0)
272
+ return 'No agent reasoning text found in JSONL.';
273
+ return `[${allTexts.length} total agent messages across entire session]\n\n` + allTexts.map(m => m.text).join('\n\n---\n\n');
274
+ }
275
+ case 'get_full_transcript': {
276
+ if (!sessionId || !workingDir)
277
+ return 'Error: no active research session';
278
+ const transcripts = getSessionTranscripts(sessionId, workingDir);
279
+ const agentTexts = transcripts.agent.messages
280
+ .filter(m => m.text && m.text.length > 20)
281
+ .map(m => `[${m.type}${m.toolName ? ': ' + m.toolName : ''}] ${m.text}`);
282
+ let output = `=== Agent Transcript (${transcripts.agent.messages.length} msgs, ${transcripts.agent.fileSize} bytes) ===\n${agentTexts.join('\n\n')}`;
283
+ if (transcripts.subagents.length > 0) {
284
+ const subTexts = transcripts.subagents.map(sa => {
285
+ const texts = sa.messages.filter(m => m.text).map(m => `[${m.type}] ${m.text}`);
286
+ return `=== Sub-agent ${sa.taskId} ===\n${texts.join('\n')}`;
287
+ });
288
+ output += '\n\n' + subTexts.join('\n\n');
289
+ }
290
+ return output;
291
+ }
292
+ case 'send_to_chat': {
293
+ const text = toolInput.text;
294
+ if (!text)
295
+ return 'Error: text is required';
296
+ if (sendToChat) {
297
+ console.log(`💬 [fast brain] send_to_chat: ${text.substring(0, 80)}...`);
298
+ sendToChat(text);
299
+ sendToChatCalledThisTurn = true;
300
+ return `Sent to chat successfully. Now return a brief spoken summary — do NOT repeat the content you just sent.`;
301
+ }
302
+ return 'Error: chat sending not available';
303
+ }
304
+ default:
305
+ return `Unknown tool: ${toolName}`;
306
+ }
307
+ }
308
+ catch (err) {
309
+ return `Tool error: ${err.message}`;
310
+ }
311
+ }
312
+ // ============================================================
313
+ // Anthropic tool definitions
314
+ // ============================================================
315
+ function buildAnthropicTools() {
316
+ return [
317
+ {
318
+ name: 'read_file',
319
+ description: 'Read a file from the session workspace. Use "spec.md" to read the session spec.',
320
+ input_schema: {
321
+ type: 'object',
322
+ properties: {
323
+ path: { type: 'string', description: 'Relative path within session workspace' }
324
+ },
325
+ required: ['path']
326
+ }
327
+ },
328
+ {
329
+ name: 'write_file',
330
+ description: 'Write or update a file in the session workspace. For spec.md, always read first then write the complete updated content.',
331
+ input_schema: {
332
+ type: 'object',
333
+ properties: {
334
+ path: { type: 'string', description: 'Relative path within session workspace' },
335
+ content: { type: 'string', description: 'The complete file content to write' }
336
+ },
337
+ required: ['path', 'content']
338
+ }
339
+ },
340
+ {
341
+ name: 'read_agent_results',
342
+ description: 'Read the research agent\'s FULL memory — complete untruncated tool outputs including entire file contents the agent read, full bash command outputs, web search results, and web page fetches. This is the agent\'s raw data. Use this FIRST when asked about anything the agent just researched. Default: last 40 results.',
343
+ input_schema: {
344
+ type: 'object',
345
+ properties: {
346
+ lastN: { type: 'number', description: 'Number of recent results to return (default: 40, max: 80)' }
347
+ }
348
+ }
349
+ },
350
+ {
351
+ name: 'read_agent_text',
352
+ description: 'Read the research agent\'s reasoning, analysis, and conclusions from JSONL. Contains the agent\'s step-by-step thinking, synthesis of findings, comparisons, and recommendations. Use this alongside read_agent_results to get the COMPLETE picture of what the agent researched and concluded. Default: last 60 messages.',
353
+ input_schema: {
354
+ type: 'object',
355
+ properties: {
356
+ lastN: { type: 'number', description: 'Number of recent text messages to return (default: 60, max: 100)' }
357
+ }
358
+ }
359
+ },
360
+ {
361
+ name: 'read_subagents',
362
+ description: 'Read all sub-agent (parallel Task) transcripts. Contains the detailed work done by sub-agents spawned during research. Use when the main agent delegated parts of the research to sub-agents working in parallel.',
363
+ input_schema: { type: 'object', properties: {} }
364
+ },
365
+ {
366
+ name: 'search_jsonl',
367
+ description: 'Search the agent\'s JSONL transcript for a keyword. Returns matching entries across all tool results, agent reasoning, and conversation history. Use to find specific mentions of a topic, file, function, or concept.',
368
+ input_schema: {
369
+ type: 'object',
370
+ properties: {
371
+ keyword: { type: 'string', description: 'The keyword to search for (case-insensitive)' },
372
+ maxResults: { type: 'number', description: 'Maximum number of results (default: 20)' }
373
+ },
374
+ required: ['keyword']
375
+ }
376
+ },
377
+ {
378
+ name: 'read_conversation',
379
+ description: 'Read the user/assistant conversation exchange history. Shows what the user asked and what the agent responded, without tool call details. Use for understanding conversation flow, user intent, and what was discussed.',
380
+ input_schema: {
381
+ type: 'object',
382
+ properties: {
383
+ lastN: { type: 'number', description: 'Number of recent exchanges to return (default: 30)' }
384
+ }
385
+ }
386
+ },
387
+ {
388
+ name: 'get_full_transcript',
389
+ description: 'Read the COMPLETE agent transcript + all sub-agent transcripts. This is the most comprehensive view of everything the agent did — use when targeted tools (read_agent_results, read_agent_text) aren\'t enough and you need the full picture. Large output.',
390
+ input_schema: { type: 'object', properties: {} }
391
+ },
392
+ {
393
+ name: 'get_session_stats',
394
+ description: 'Get session statistics: total messages, tool call counts by name, sub-agent count, data size, time range. Use this to understand how much data is in the session before deciding whether to use deep tools.',
395
+ input_schema: { type: 'object', properties: {} }
396
+ },
397
+ {
398
+ name: 'deep_read_results',
399
+ description: 'Read ALL tool results across the ENTIRE session — not just recent ones. Returns every file read, bash output, web search, web fetch, etc. Use toolFilter to narrow by tool type. Use this for generating detailed analyses, overviews, diagrams, answering specific questions requiring full context, or when the user wants comprehensive details.',
400
+ input_schema: {
401
+ type: 'object',
402
+ properties: {
403
+ toolFilter: {
404
+ type: 'array',
405
+ items: { type: 'string' },
406
+ description: 'Only return results from these tools. E.g., ["Read"] for file reads, ["WebSearch","WebFetch"] for web data, ["Bash"] for commands, ["Grep","Glob"] for code searches. Omit for all tools.'
407
+ }
408
+ }
409
+ }
410
+ },
411
+ {
412
+ name: 'deep_read_text',
413
+ description: 'Read ALL agent reasoning and analysis across the ENTIRE session — not just recent messages. Returns every piece of thinking, synthesis, comparison, and recommendation the agent produced. Use this for generating comprehensive overviews or when the user asks for detailed explanations of what the agent found.',
414
+ input_schema: { type: 'object', properties: {} }
415
+ },
416
+ {
417
+ name: 'send_to_chat',
418
+ description: 'Send formatted content to the user\'s chat panel. Use for URLs, links, lists, prices, code snippets, or anything that\'s better read than spoken. The content appears as a chat message in the frontend. You should STILL speak a brief summary — use this tool for the detailed/visual content.',
419
+ input_schema: {
420
+ type: 'object',
421
+ properties: {
422
+ text: { type: 'string', description: 'The formatted text to display in chat. Supports markdown.' }
423
+ },
424
+ required: ['text']
425
+ }
426
+ }
427
+ ];
428
+ }
429
+ const ANTHROPIC_WEB_SEARCH = {
430
+ type: 'web_search_20250305',
431
+ name: 'web_search',
432
+ max_uses: 3,
433
+ };
434
+ // ============================================================
435
+ // Gemini tool definitions
436
+ // ============================================================
437
+ function buildGeminiTools() {
438
+ // NOTE: Gemini API does NOT allow combining functionDeclarations with googleSearch
439
+ // in the same request (400 "Tool use with function calling is unsupported").
440
+ // Web search is implemented as a custom function that makes a separate grounded API call.
441
+ return [
442
+ {
443
+ functionDeclarations: [
444
+ {
445
+ name: 'read_file',
446
+ description: 'Read a file from the session workspace. Use "spec.md" to read the session spec.',
447
+ parameters: {
448
+ type: 'object',
449
+ properties: {
450
+ path: { type: 'string', description: 'Relative path within session workspace' }
451
+ },
452
+ required: ['path']
453
+ }
454
+ },
455
+ {
456
+ name: 'write_file',
457
+ description: 'Write or update a file in the session workspace. For spec.md, always read first then write the complete updated content.',
458
+ parameters: {
459
+ type: 'object',
460
+ properties: {
461
+ path: { type: 'string', description: 'Relative path within session workspace' },
462
+ content: { type: 'string', description: 'The complete file content to write' }
463
+ },
464
+ required: ['path', 'content']
465
+ }
466
+ },
467
+ {
468
+ name: 'web_search',
469
+ description: 'Search the web for current information. Use for factual questions like "current version of X", "what is X", definitions, etc.',
470
+ parameters: {
471
+ type: 'object',
472
+ properties: {
473
+ query: { type: 'string', description: 'The search query' }
474
+ },
475
+ required: ['query']
476
+ }
477
+ },
478
+ {
479
+ name: 'read_agent_results',
480
+ description: 'Read the research agent\'s FULL memory — complete untruncated tool outputs including entire file contents the agent read, full bash command outputs, web search results, and web page fetches. This is the agent\'s raw data. Use this FIRST when asked about anything the agent just researched. Default: last 40 results.',
481
+ parameters: {
482
+ type: 'object',
483
+ properties: {
484
+ lastN: { type: 'number', description: 'Number of recent results to return (default: 40, max: 60)' }
485
+ }
486
+ }
487
+ },
488
+ {
489
+ name: 'read_agent_text',
490
+ description: 'Read the research agent\'s reasoning, analysis, and conclusions from JSONL. Contains the agent\'s step-by-step thinking, synthesis of findings, comparisons, and recommendations. Use this alongside read_agent_results to get the COMPLETE picture of what the agent researched and concluded. Default: last 60 messages.',
491
+ parameters: {
492
+ type: 'object',
493
+ properties: {
494
+ lastN: { type: 'number', description: 'Number of recent text messages to return (default: 60, max: 100)' }
495
+ }
496
+ }
497
+ },
498
+ {
499
+ name: 'read_subagents',
500
+ description: 'Read all sub-agent (parallel Task) transcripts. Contains the detailed work done by sub-agents spawned during research.',
501
+ parameters: { type: 'object', properties: {} }
502
+ },
503
+ {
504
+ name: 'search_jsonl',
505
+ description: 'Search the agent\'s JSONL transcript for a keyword. Returns matching entries across all tool results, agent reasoning, and conversation history.',
506
+ parameters: {
507
+ type: 'object',
508
+ properties: {
509
+ keyword: { type: 'string', description: 'The keyword to search for (case-insensitive)' },
510
+ maxResults: { type: 'number', description: 'Maximum number of results (default: 20)' }
511
+ },
512
+ required: ['keyword']
513
+ }
514
+ },
515
+ {
516
+ name: 'read_conversation',
517
+ description: 'Read the user/assistant conversation exchange history. Shows what the user asked and what the agent responded.',
518
+ parameters: {
519
+ type: 'object',
520
+ properties: {
521
+ lastN: { type: 'number', description: 'Number of recent exchanges to return (default: 30)' }
522
+ }
523
+ }
524
+ },
525
+ {
526
+ name: 'get_full_transcript',
527
+ description: 'Read the COMPLETE agent transcript + all sub-agent transcripts. Most comprehensive view — use when targeted tools aren\'t enough.',
528
+ parameters: { type: 'object', properties: {} }
529
+ },
530
+ {
531
+ name: 'get_session_stats',
532
+ description: 'Get session statistics: total messages, tool call counts by name, sub-agent count, data size, time range. Use to understand how much data is in the session before using deep tools.',
533
+ parameters: { type: 'object', properties: {} }
534
+ },
535
+ {
536
+ name: 'deep_read_results',
537
+ description: 'Read ALL tool results across the ENTIRE session — not just recent ones. Use toolFilter to narrow by tool type. For detailed analyses, overviews, diagrams, specific questions requiring full context.',
538
+ parameters: {
539
+ type: 'object',
540
+ properties: {
541
+ toolFilter: {
542
+ type: 'array',
543
+ items: { type: 'string' },
544
+ description: 'Only return results from these tools. E.g., ["Read"] for file reads, ["WebSearch","WebFetch"] for web data. Omit for all.'
545
+ }
546
+ }
547
+ }
548
+ },
549
+ {
550
+ name: 'deep_read_text',
551
+ description: 'Read ALL agent reasoning across the ENTIRE session. For comprehensive overviews or detailed explanations of what the agent found throughout the session.',
552
+ parameters: { type: 'object', properties: {} }
553
+ },
554
+ {
555
+ name: 'send_to_chat',
556
+ description: 'Send formatted content to the user\'s chat panel. Use for URLs, links, lists, prices, code snippets, or anything better read than spoken. Still speak a brief summary — use this for the detailed/visual content.',
557
+ parameters: {
558
+ type: 'object',
559
+ properties: {
560
+ text: { type: 'string', description: 'The formatted text to display in chat. Supports markdown.' }
561
+ },
562
+ required: ['text']
563
+ }
564
+ }
565
+ ]
566
+ }
567
+ ];
568
+ }
569
+ /**
570
+ * Perform a web search via Gemini's Google Search grounding.
571
+ * This is called as a separate API request because Gemini doesn't allow
572
+ * combining googleSearch with functionDeclarations in the same request.
573
+ */
574
+ async function geminiWebSearch(query) {
575
+ try {
576
+ const ai = geminiClient;
577
+ const response = await ai.models.generateContent({
578
+ model: GEMINI_FAST_MODEL,
579
+ contents: [{ role: 'user', parts: [{ text: query }] }],
580
+ config: {
581
+ tools: [{ googleSearch: {} }],
582
+ }
583
+ });
584
+ return response.text || 'No web results found.';
585
+ }
586
+ catch (err) {
587
+ console.error('❌ Gemini web search failed:', err);
588
+ return `Web search failed: ${err.message}`;
589
+ }
590
+ }
591
+ // ============================================================
592
+ // Agent SDK Q&A implementation — replaces direct Anthropic API for Q&A
593
+ // ============================================================
594
+ /**
595
+ * Create an in-process MCP server with the send_to_chat tool for the Agent SDK fast brain.
596
+ */
597
+ function createFastBrainMcpServer(sendToChat) {
598
+ const tools = [];
599
+ if (sendToChat) {
600
+ tools.push(sdkTool('send_to_chat', 'Send formatted content to the user\'s chat panel. Use for URLs, links, lists, prices, code snippets, tables, or anything better read than spoken. Supports markdown. You should STILL speak a brief summary — the chat content is supplementary.', { text: z.string().describe('The formatted text to display in chat. Supports markdown.') }, async ({ text }) => {
601
+ sendToChat(text);
602
+ sendToChatCalledThisTurn = true;
603
+ return { content: [{ type: 'text', text: 'Sent to chat. Now give a brief spoken summary of what you sent.' }] };
604
+ }));
605
+ }
606
+ return createSdkMcpServer({
607
+ name: 'osborn-fast-brain',
608
+ version: '1.0.0',
609
+ tools,
610
+ });
611
+ }
612
+ /**
613
+ * Ask via Claude Agent SDK — the agent traverses JSONL files natively using Read/Grep/Glob.
614
+ * Falls back to Gemini on timeout or error.
615
+ */
616
+ async function askViaAgentSdk(question, workspace, researchContext, sessionId, workingDir, chatHistory, sendToChat, sessionBaseDir) {
617
+ sendToChatCalledThisTurn = false;
618
+ // Build the prompt with conversation context
619
+ let prompt = question;
620
+ if (researchContext) {
621
+ prompt += `\n\n[LIVE RESEARCH CONTEXT — the deep research agent is currently working]\n${researchContext}`;
622
+ }
623
+ if (chatHistory && chatHistory.length > 0) {
624
+ const historyStr = chatHistory.slice(-15).map(t => `${t.role}: ${t.text}`).join('\n');
625
+ prompt = `[Recent voice conversation]\n${historyStr}\n\n[Current question]\n${prompt}`;
626
+ }
627
+ // Create MCP server for send_to_chat
628
+ const mcpServer = createFastBrainMcpServer(sendToChat);
629
+ // Build system prompt with computed paths
630
+ const systemPrompt = buildFastBrainSdkPrompt(workingDir || workspace, sessionId || '', sessionBaseDir || workingDir || workspace);
631
+ // Tools: Read/Write/Edit for files, Grep/Glob for search, WebSearch/WebFetch for web
632
+ const toolNames = ['Read', 'Write', 'Edit', 'Grep', 'Glob', 'WebSearch', 'WebFetch'];
633
+ const mcpToolPatterns = sendToChat ? ['mcp__osborn-fast-brain__*'] : [];
634
+ const options = {
635
+ model: ANTHROPIC_FAST_MODEL,
636
+ cwd: workingDir,
637
+ systemPrompt,
638
+ maxTurns: 8,
639
+ tools: toolNames,
640
+ allowedTools: [...toolNames, ...mcpToolPatterns],
641
+ mcpServers: { 'osborn-fast-brain': mcpServer },
642
+ };
643
+ if (fastBrainSessionId) {
644
+ options.resume = fastBrainSessionId;
645
+ }
646
+ // Run with 30s timeout — allows time for large JSONL replay on session resume
647
+ const TIMEOUT_MS = 30000;
648
+ let timeoutHandle;
649
+ const timeoutPromise = new Promise((_, reject) => {
650
+ timeoutHandle = setTimeout(() => reject(new Error('fast-brain-timeout')), TIMEOUT_MS);
651
+ });
652
+ const queryPromise = (async () => {
653
+ let result = '';
654
+ try {
655
+ for await (const message of sdkQuery({ prompt, options })) {
656
+ if (message.type === 'result') {
657
+ result = message.result || '';
658
+ }
659
+ // Capture session ID eagerly — even if we timeout, next call can resume
660
+ if (message.type === 'assistant' && message.session_id) {
661
+ const sid = message.session_id;
662
+ if (sid !== fastBrainSessionId) {
663
+ fastBrainSessionId = sid;
664
+ console.log(`🧠 Fast brain session: ${sid.substring(0, 12)}... (${options.resume ? 'resumed' : 'new'})`);
665
+ }
666
+ }
667
+ }
668
+ }
669
+ catch (err) {
670
+ console.error('❌ Agent SDK query error:', err);
671
+ throw err;
672
+ }
673
+ clearTimeout(timeoutHandle);
674
+ return result;
675
+ })();
676
+ try {
677
+ const result = await Promise.race([queryPromise, timeoutPromise]);
678
+ if (!result || result.trim().length === 0) {
679
+ if (sendToChatCalledThisTurn)
680
+ return "I've sent the details to your chat panel.";
681
+ return 'No answer found.';
682
+ }
683
+ console.log(`🧠 Agent SDK fast brain: ${result.length} chars (session: ${fastBrainSessionId?.substring(0, 8) || 'new'})`);
684
+ return result;
685
+ }
686
+ catch (err) {
687
+ clearTimeout(timeoutHandle);
688
+ if (err.message === 'fast-brain-timeout') {
689
+ console.log('⏱️ Agent SDK fast brain timed out (15s), falling back to Gemini');
690
+ }
691
+ else {
692
+ console.error('❌ Agent SDK fast brain error:', err.message || err);
693
+ }
694
+ // Fall back to Gemini if available
695
+ if (geminiClient) {
696
+ console.log('🔄 Falling back to Gemini fast brain');
697
+ return askViaGemini(question, workspace, researchContext, sessionId, workingDir, chatHistory, sendToChat);
698
+ }
699
+ // Fall back to direct Anthropic API if no Gemini
700
+ if (anthropicClient) {
701
+ console.log('🔄 Falling back to direct Anthropic API');
702
+ return askViaAnthropic(question, workspace, researchContext, sessionId, workingDir, chatHistory, sendToChat);
703
+ }
704
+ return 'Fast brain unavailable. Try asking me to research it.';
705
+ }
706
+ }
707
+ // ============================================================
708
+ // Direct Anthropic API Q&A — kept as fallback for Agent SDK failures
709
+ // ============================================================
710
+ async function askViaAnthropic(question, workspace, researchContext, sessionId, workingDir, chatHistory, sendToChat) {
711
+ const client = anthropicClient;
712
+ const tools = buildAnthropicTools();
713
+ sendToChatCalledThisTurn = false;
714
+ const userContent = researchContext
715
+ ? `${question}\n\n[LIVE RESEARCH CONTEXT — the research agent is currently working]\n${researchContext}`
716
+ : question;
717
+ // Build messages: persistent fast brain history + live voice history + current question
718
+ const messages = [];
719
+ // 1. Inject persistent fast brain history (prior exchanges from this session)
720
+ for (const exchange of fastBrainHistory) {
721
+ messages.push({ role: 'user', content: exchange.question });
722
+ messages.push({ role: 'assistant', content: exchange.answer });
723
+ }
724
+ // 2. Inject live voice conversation history (from agent.chatCtx — what user/model actually said)
725
+ if (chatHistory && chatHistory.length > 0) {
726
+ for (const turn of chatHistory) {
727
+ messages.push({ role: turn.role, content: turn.text });
728
+ }
729
+ }
730
+ // 3. Current question
731
+ messages.push({ role: 'user', content: userContent });
732
+ const allTools = [...tools, ANTHROPIC_WEB_SEARCH];
733
+ const noAnswerFallback = () => sendToChatCalledThisTurn
734
+ ? "I've sent the details to your chat panel."
735
+ : 'No answer found.';
736
+ for (let i = 0; i < 10; i++) {
737
+ const response = await client.messages.create({
738
+ model: ANTHROPIC_FAST_MODEL,
739
+ max_tokens: 10000,
740
+ system: FAST_BRAIN_SYSTEM_PROMPT,
741
+ tools: allTools,
742
+ messages,
743
+ });
744
+ if (response.stop_reason === 'end_turn') {
745
+ const textBlock = response.content.find((b) => b.type === 'text');
746
+ const answer = textBlock?.text || noAnswerFallback();
747
+ // Persist this exchange for future calls
748
+ fastBrainHistory.push({ question: userContent, answer });
749
+ if (fastBrainHistory.length > MAX_FAST_BRAIN_HISTORY)
750
+ fastBrainHistory.shift();
751
+ return answer;
752
+ }
753
+ const toolUseBlocks = response.content.filter((b) => b.type === 'tool_use');
754
+ if (toolUseBlocks.length === 0 && response.stop_reason !== 'tool_use') {
755
+ const textBlock = response.content.find((b) => b.type === 'text');
756
+ const answer = textBlock?.text || noAnswerFallback();
757
+ fastBrainHistory.push({ question: userContent, answer });
758
+ if (fastBrainHistory.length > MAX_FAST_BRAIN_HISTORY)
759
+ fastBrainHistory.shift();
760
+ return answer;
761
+ }
762
+ messages.push({ role: 'assistant', content: response.content });
763
+ if (toolUseBlocks.length > 0) {
764
+ const toolResults = toolUseBlocks.map(toolUse => ({
765
+ type: 'tool_result',
766
+ tool_use_id: toolUse.id,
767
+ content: executeTool(toolUse.name, toolUse.input, workspace, sessionId, workingDir, sendToChat),
768
+ }));
769
+ messages.push({ role: 'user', content: toolResults });
770
+ }
771
+ }
772
+ if (sendToChatCalledThisTurn) {
773
+ const answer = "I've sent the full details to your chat. Let me know if you want to dive deeper into anything.";
774
+ fastBrainHistory.push({ question: userContent, answer });
775
+ if (fastBrainHistory.length > MAX_FAST_BRAIN_HISTORY)
776
+ fastBrainHistory.shift();
777
+ return answer;
778
+ }
779
+ return 'Fast brain reached maximum tool iterations. Try ask_agent for a deeper search.';
780
+ }
781
+ // ============================================================
782
+ // Gemini Q&A implementation
783
+ // ============================================================
784
+ async function askViaGemini(question, workspace, researchContext, sessionId, workingDir, chatHistory, sendToChat, sessionBaseDir) {
785
+ const ai = geminiClient;
786
+ const tools = buildGeminiTools();
787
+ sendToChatCalledThisTurn = false;
788
+ const userContent = researchContext
789
+ ? `${question}\n\n[LIVE RESEARCH CONTEXT — the research agent is currently working]\n${researchContext}`
790
+ : question;
791
+ // Create or reuse persistent Gemini Chat session.
792
+ // The Chat object auto-manages full conversation history (messages + tool calls).
793
+ // Cleared on disconnect/reconnect/session switch via clearFastBrainSession().
794
+ if (!geminiChat) {
795
+ // Seed with live voice conversation history so Gemini knows what user/model said
796
+ const history = [];
797
+ if (chatHistory && chatHistory.length > 0) {
798
+ for (const turn of chatHistory) {
799
+ history.push({
800
+ role: turn.role === 'assistant' ? 'model' : 'user',
801
+ parts: [{ text: turn.text }],
802
+ });
803
+ }
804
+ }
805
+ geminiChat = ai.chats.create({
806
+ model: GEMINI_FAST_MODEL,
807
+ config: {
808
+ systemInstruction: FAST_BRAIN_SYSTEM_PROMPT,
809
+ tools,
810
+ },
811
+ history,
812
+ });
813
+ console.log(`🧠 Gemini fast brain: new chat session (history: ${history.length} turns)`);
814
+ }
815
+ // Send user message via the persistent chat — history accumulates automatically.
816
+ // The Chat object tracks all messages + tool calls internally.
817
+ let response = await geminiChat.sendMessage({ message: userContent });
818
+ // Tool call loop: execute tools and send results back, up to 10 rounds
819
+ for (let i = 0; i < 10; i++) {
820
+ const functionCalls = response.functionCalls;
821
+ if (!functionCalls || functionCalls.length === 0) {
822
+ const text = response.text;
823
+ if (text)
824
+ return text;
825
+ if (sendToChatCalledThisTurn)
826
+ return "I've sent the details to your chat panel.";
827
+ return 'No answer found.';
828
+ }
829
+ // Execute tools
830
+ const functionResponses = await Promise.all(functionCalls.map(async (call) => {
831
+ let result;
832
+ if (call.name === 'web_search') {
833
+ result = await geminiWebSearch(call.args?.query || question);
834
+ }
835
+ else {
836
+ result = executeTool(call.name, call.args || {}, workspace, sessionId, workingDir, sendToChat);
837
+ }
838
+ return {
839
+ functionResponse: {
840
+ name: call.name,
841
+ response: { result }
842
+ }
843
+ };
844
+ }));
845
+ // Send tool results back — chat auto-tracks the full exchange
846
+ response = await geminiChat.sendMessage({ message: functionResponses });
847
+ }
848
+ if (sendToChatCalledThisTurn) {
849
+ return "I've sent the full details to your chat. Let me know if you want to dive deeper into anything.";
850
+ }
851
+ return 'Fast brain reached maximum tool iterations. Try ask_agent for a deeper search.';
852
+ }
853
+ // ============================================================
854
+ // askHaiku — Main Q&A function (dispatches to provider)
855
+ // ============================================================
856
+ /**
857
+ * Ask the fast brain a question with access to session files and web search.
858
+ * Returns an answer or "NEEDS_DEEPER_RESEARCH: ..." for escalation.
859
+ *
860
+ * Auth chain: Anthropic (API key → auth token → Keychain OAuth) → Gemini Flash fallback
861
+ *
862
+ * @param researchContext - Optional snapshot of the live research log.
863
+ * ~2 second response time for most queries.
864
+ */
865
+ export async function askHaiku(workingDir, sessionId, question, researchContext, chatHistory, sendToChat, sessionBaseDir) {
866
+ initProvider();
867
+ // workspace uses workingDir for spec.md (under ~/.claude/projects/{slug}/osb/)
868
+ // workingDir is for JSONL access (matches Claude SDK cwd)
869
+ const wsDir = workingDir;
870
+ const workspace = getSessionWorkspace(wsDir, sessionId);
871
+ // Primary: Gemini Flash (~1-2s) with pre-loaded JSONL context
872
+ // Fallback: Anthropic direct API or Agent SDK (slower but functional)
873
+ if (provider === 'gemini') {
874
+ return askViaGemini(question, workspace, researchContext, sessionId, workingDir, chatHistory, sendToChat, wsDir);
875
+ }
876
+ else if (provider === 'anthropic' || provider === 'agent-sdk') {
877
+ return askViaAgentSdk(question, workspace, researchContext, sessionId, workingDir, chatHistory, sendToChat, wsDir);
878
+ }
879
+ else {
880
+ return 'NEEDS_DEEPER_RESEARCH: Fast brain unavailable (no API key or CLI auth). Try ask_agent instead.';
881
+ }
882
+ }
883
+ let researchTaskCounter = 0;
884
+ /**
885
+ * Central orchestrator — ALL user questions from the realtime model come here.
886
+ * Routes to: direct answer, research triggering, decision recording, or document generation.
887
+ * Returns a teleprompter script the voice model reads verbatim.
888
+ */
889
+ export async function askFastBrain(workingDir, sessionId, question, opts) {
890
+ const { chatHistory, researchContext, callbacks } = opts;
891
+ const wsDir = workingDir;
892
+ // Detect document generation requests
893
+ const docMatch = detectDocumentRequest(question);
894
+ if (docMatch) {
895
+ try {
896
+ const result = await generateVisualDocument(workingDir, sessionId, question, docMatch, wsDir);
897
+ if (result) {
898
+ const fullPath = `${getSessionWorkspace(wsDir, sessionId)}/${result.fileName}`;
899
+ callbacks.sendToFrontend({
900
+ type: 'research_artifact_updated',
901
+ filePath: fullPath,
902
+ fileName: result.fileName,
903
+ });
904
+ return {
905
+ script: `I've created a ${docMatch} document called ${result.fileName}. You can see it in the files panel.`,
906
+ type: 'answer',
907
+ };
908
+ }
909
+ }
910
+ catch (err) {
911
+ console.error('❌ askFastBrain: document generation failed:', err);
912
+ }
913
+ // Fall through to regular handling if document gen fails
914
+ }
915
+ // Create sendToChat wrapper that sends assistant_response to frontend
916
+ const sendToChat = (text) => {
917
+ callbacks.sendToFrontend({ type: 'assistant_response', text });
918
+ };
919
+ // Core: ask the fast brain LLM
920
+ const answer = await askHaiku(workingDir, sessionId, question, researchContext, chatHistory, sendToChat, wsDir);
921
+ // Parse the response to determine routing
922
+ if (answer.startsWith('RECORDED:') || answer.includes('\nRECORDED:')) {
923
+ // Decision was recorded — extract the confirmation
924
+ const recordedLine = answer.split('\n').find(l => l.startsWith('RECORDED:'));
925
+ const confirmation = recordedLine
926
+ ? recordedLine.replace('RECORDED:', '').trim()
927
+ : 'Got it, noted.';
928
+ // Notify frontend about spec update
929
+ const specPath = `${wsDir}/.osborn/sessions/${sessionId}/spec.md`;
930
+ callbacks.sendToFrontend({
931
+ type: 'research_artifact_updated',
932
+ filePath: specPath,
933
+ fileName: 'spec.md',
934
+ });
935
+ return { script: confirmation, type: 'recorded' };
936
+ }
937
+ // Handle ASK_USER — questions directed at the user (not research tasks)
938
+ if (answer.startsWith('ASK_USER:') || answer.includes('\nASK_USER:')) {
939
+ const askLine = answer.split('\n').find(l => l.includes('ASK_USER:'));
940
+ const userQuestion = askLine
941
+ ? askLine.replace(/^ASK_USER:\s*/, '').trim()
942
+ : answer.replace(/^ASK_USER:\s*/, '').trim();
943
+ return { script: userQuestion, type: 'question' };
944
+ }
945
+ if (answer.includes('NEEDS_DEEPER_RESEARCH')) {
946
+ // Extract the research task context
947
+ const needsLine = answer.split('\n').find(l => l.includes('NEEDS_DEEPER_RESEARCH'));
948
+ const contextLine = answer.split('\n').find(l => l.startsWith('CONTEXT:'));
949
+ const researchTask = needsLine
950
+ ? needsLine.replace(/^(PARTIAL:\s*)?NEEDS_DEEPER_RESEARCH:\s*/, '').trim()
951
+ : question;
952
+ const contextStr = contextLine ? contextLine.replace('CONTEXT:', '').trim() : '';
953
+ // Safety check: if the "research task" looks like a question for the user
954
+ // (ends with ?, asks about preferences/needs, is very short), treat it as ASK_USER instead.
955
+ // This catches the common Gemini bug where clarification questions are formatted as research tasks.
956
+ const taskLower = researchTask.toLowerCase();
957
+ const looksLikeUserQuestion = (researchTask.endsWith('?') && (taskLower.includes('would you') ||
958
+ taskLower.includes('do you') ||
959
+ taskLower.includes('could you') ||
960
+ taskLower.includes('what kind of') ||
961
+ taskLower.includes('which') ||
962
+ taskLower.includes('your needs') ||
963
+ taskLower.includes('your preference') ||
964
+ taskLower.includes('more details') ||
965
+ taskLower.includes('clarif') ||
966
+ taskLower.includes('specify') ||
967
+ taskLower.includes('interested in') ||
968
+ researchTask.length < 80 // Very short "tasks" ending in ? are almost always user questions
969
+ ));
970
+ if (looksLikeUserQuestion) {
971
+ console.log(`🧠 [fast brain] Caught question-as-research-task, redirecting to ASK_USER: "${researchTask.substring(0, 100)}"`);
972
+ return { script: researchTask, type: 'question' };
973
+ }
974
+ const fullTask = contextStr ? `${researchTask}\n\nContext: ${contextStr}` : researchTask;
975
+ // Extract any partial answer (spoken script before NEEDS_DEEPER_RESEARCH)
976
+ const partialMatch = answer.match(/^PARTIAL:\s*([\s\S]*?)(?=\nNEEDS_DEEPER_RESEARCH)/m);
977
+ const partialScript = partialMatch ? partialMatch[1].trim() : '';
978
+ // Generate a task ID for frontend tracking
979
+ researchTaskCounter++;
980
+ const taskId = `research-${researchTaskCounter}-${Date.now()}`;
981
+ // Trigger research in background
982
+ callbacks.triggerResearch(fullTask);
983
+ callbacks.sendToFrontend({
984
+ type: 'research_task_started',
985
+ task: researchTask.substring(0, 200),
986
+ taskId,
987
+ });
988
+ // Generate acknowledgment script
989
+ let script;
990
+ if (partialScript) {
991
+ script = `${partialScript} Let me dig deeper on the rest.`;
992
+ }
993
+ else {
994
+ // Generate a contextual ack based on conversation flow
995
+ script = generateResearchAck(question, chatHistory);
996
+ }
997
+ return { script, type: 'research_started' };
998
+ }
999
+ // Direct answer — the response IS the teleprompter script
1000
+ return { script: answer, type: 'answer' };
1001
+ }
1002
+ /** Detect if the user's question is an EXPLICIT document generation request.
1003
+ * Must be very specific — don't catch general questions about analysis or comparisons.
1004
+ * Only triggers when the user explicitly asks for a written document/artifact. */
1005
+ function detectDocumentRequest(question) {
1006
+ const q = question.toLowerCase();
1007
+ // Only match explicit document requests — "create a comparison", "make a diagram", "write a summary"
1008
+ // Do NOT match: "compare X and Y", "analyze the code", "give me an overview"
1009
+ const docVerbs = /(create|make|generate|write|build|produce|draw)\s+(a\s+|an\s+|the\s+)?/;
1010
+ if (!docVerbs.test(q))
1011
+ return null;
1012
+ if (q.includes('comparison') || q.includes('comparison table') || q.includes('comparison document'))
1013
+ return 'comparison';
1014
+ if (q.includes('diagram') || q.includes('flow chart') || q.includes('architecture diagram'))
1015
+ return 'diagram';
1016
+ if (q.includes('analysis document') || q.includes('tradeoff document'))
1017
+ return 'analysis';
1018
+ if (q.includes('summary document') || q.includes('overview document'))
1019
+ return 'summary';
1020
+ return null;
1021
+ }
1022
+ /** Generate a natural research acknowledgment based on conversation context */
1023
+ function generateResearchAck(question, chatHistory) {
1024
+ // Use simple heuristics for a natural ack — no LLM call needed
1025
+ const q = question.toLowerCase();
1026
+ if (q.includes('how') && (q.includes('work') || q.includes('implement'))) {
1027
+ return "Let me look into how that works. I'll have the details for you shortly.";
1028
+ }
1029
+ if (q.includes('what') && (q.includes('option') || q.includes('available') || q.includes('choice'))) {
1030
+ return "Let me research the options for you.";
1031
+ }
1032
+ if (q.includes('why') || q.includes('explain')) {
1033
+ return "Good question. Let me dig into that.";
1034
+ }
1035
+ if (q.includes('find') || q.includes('search') || q.includes('look')) {
1036
+ return "On it. Give me a moment to look into that.";
1037
+ }
1038
+ return "Let me research that for you. I'll have findings shortly.";
1039
+ }
1040
+ // ============================================================
1041
+ // processResearchChunk — Incremental content processing during research
1042
+ // ============================================================
1043
+ /**
1044
+ * Process a batch of research content chunks through the fast brain.
1045
+ * Updates spec.md incrementally during research.
1046
+ *
1047
+ * @param isRefinement - true for the final post-research consolidation pass (higher token budget)
1048
+ */
1049
+ export async function processResearchChunk(workingDir, sessionId, task, contentChunks, isRefinement, sessionBaseDir) {
1050
+ initProvider();
1051
+ if (provider === 'none')
1052
+ return null;
1053
+ if (contentChunks.length === 0)
1054
+ return null;
1055
+ // Prevent concurrent spec writes
1056
+ if (specUpdateInProgress) {
1057
+ console.log('⏸️ processResearchChunk: spec update already in progress, skipping');
1058
+ return null;
1059
+ }
1060
+ specUpdateInProgress = true;
1061
+ const wsDir = workingDir;
1062
+ try {
1063
+ const workspace = getSessionWorkspace(wsDir, sessionId);
1064
+ const specPath = `${workspace}/spec.md`;
1065
+ if (!existsSync(specPath)) {
1066
+ console.log('⚠️ processResearchChunk: spec.md not found, skipping');
1067
+ return null;
1068
+ }
1069
+ const currentSpec = readFileSync(specPath, 'utf-8');
1070
+ // No content capping — models handle 200K+ tokens (Haiku) / 1M+ (Gemini Flash)
1071
+ const chunksText = contentChunks.join('\n\n---\n\n');
1072
+ const systemPrompt = isRefinement ? REFINEMENT_PROCESS_SYSTEM : CHUNK_PROCESS_SYSTEM;
1073
+ const userMessage = `Research task: "${task}"
1074
+
1075
+ Current spec.md:
1076
+ \`\`\`markdown
1077
+ ${currentSpec}
1078
+ \`\`\`
1079
+
1080
+ Content chunks from research:
1081
+ ${chunksText}
1082
+
1083
+ Return ONLY valid JSON — no code fences, no explanation.`;
1084
+ let responseText = null;
1085
+ if (anthropicClient) {
1086
+ const response = await anthropicClient.messages.create({
1087
+ model: ANTHROPIC_FAST_MODEL,
1088
+ max_tokens: isRefinement ? 20000 : 10000,
1089
+ system: systemPrompt,
1090
+ messages: [{ role: 'user', content: userMessage }]
1091
+ });
1092
+ responseText = response.content[0].type === 'text' ? response.content[0].text : null;
1093
+ }
1094
+ else if (geminiClient) {
1095
+ const response = await geminiClient.models.generateContent({
1096
+ model: GEMINI_FAST_MODEL,
1097
+ contents: userMessage,
1098
+ config: { systemInstruction: systemPrompt }
1099
+ });
1100
+ responseText = response.text || null;
1101
+ }
1102
+ if (!responseText)
1103
+ return null;
1104
+ // Parse JSON response — multi-strategy for robustness
1105
+ const parsed = parseChunkResponse(responseText);
1106
+ if (!parsed)
1107
+ return null;
1108
+ let updatedSpec = null;
1109
+ // Write spec.md
1110
+ if (parsed.spec && typeof parsed.spec === 'string' && parsed.spec.length > 50) {
1111
+ writeFileSync(specPath, parsed.spec, 'utf-8');
1112
+ updatedSpec = parsed.spec;
1113
+ const label = isRefinement ? 'refinement pass' : 'chunk';
1114
+ console.log(`📋 Fast brain processed research ${label} — spec.md updated (${parsed.spec.length} chars)`);
1115
+ }
1116
+ const label = isRefinement ? 'refinement' : `${contentChunks.length} content items`;
1117
+ console.log(`📋 Fast brain processed research chunk (${label})`);
1118
+ return { spec: updatedSpec, libraryFiles: [] };
1119
+ }
1120
+ catch (err) {
1121
+ console.error('❌ processResearchChunk failed:', err);
1122
+ return null;
1123
+ }
1124
+ finally {
1125
+ specUpdateInProgress = false;
1126
+ }
1127
+ }
1128
+ // Simple lock to prevent concurrent spec writes during research
1129
+ let specUpdateInProgress = false;
1130
+ // ============================================================
1131
+ // parseChunkResponse — Robust JSON parsing for LLM output
1132
+ // ============================================================
1133
+ /**
1134
+ * Multi-strategy JSON parser for LLM chunk processing responses.
1135
+ * Handles code fences, control characters, and raw markdown fallbacks.
1136
+ *
1137
+ * Strategies (tried in order):
1138
+ * 1. Direct JSON.parse after stripping code fences
1139
+ * 2. Control character stripping (newlines, tabs in string values)
1140
+ * 3. Regex extraction of spec field from malformed JSON
1141
+ * 4. Raw markdown detection (LLM returned spec directly instead of JSON)
1142
+ */
1143
+ function parseChunkResponse(responseText) {
1144
+ const cleaned = responseText.replace(/^```json?\s*/i, '').replace(/\s*```$/i, '').trim();
1145
+ // Strategy 1: Direct parse
1146
+ try {
1147
+ return JSON.parse(cleaned);
1148
+ }
1149
+ catch { /* continue */ }
1150
+ // Strategy 2: Strip control characters in string values
1151
+ try {
1152
+ const sanitized = cleaned.replace(/[\x00-\x1f]/g, (ch) => {
1153
+ if (ch === '\n')
1154
+ return '\\n';
1155
+ if (ch === '\r')
1156
+ return '\\r';
1157
+ if (ch === '\t')
1158
+ return '\\t';
1159
+ return '';
1160
+ });
1161
+ return JSON.parse(sanitized);
1162
+ }
1163
+ catch { /* continue */ }
1164
+ // Strategy 3: Regex extract spec field
1165
+ const specMatch = cleaned.match(/"spec"\s*:\s*"((?:[^"\\]|\\.)*)"/s);
1166
+ if (specMatch) {
1167
+ try {
1168
+ const specContent = JSON.parse(`"${specMatch[1]}"`);
1169
+ return { spec: specContent };
1170
+ }
1171
+ catch { /* continue */ }
1172
+ }
1173
+ // Strategy 4: Raw markdown — LLM returned spec directly
1174
+ if (cleaned.startsWith('#') && cleaned.includes('## ')) {
1175
+ console.log('⚠️ parseChunkResponse: detected raw markdown, treating as spec');
1176
+ return { spec: cleaned };
1177
+ }
1178
+ console.error('⚠️ parseChunkResponse: all strategies failed');
1179
+ return null;
1180
+ }
1181
+ // ============================================================
1182
+ // augmentResearchResult — Fast brain adds spec context to agent results (NO summarization)
1183
+ // ============================================================
1184
+ /**
1185
+ * Augment agent SDK research results with context from spec.md.
1186
+ * Passes ALL specific details through verbatim — only ADDS context annotations.
1187
+ * The voice model downstream handles summarization for speech.
1188
+ *
1189
+ * Falls back to returning the original result if the fast brain is unavailable.
1190
+ */
1191
+ export async function augmentResearchResult(workingDir, sessionId, task, agentResult) {
1192
+ initProvider();
1193
+ if (provider === 'none')
1194
+ return agentResult;
1195
+ try {
1196
+ // Read spec for context
1197
+ const specContent = readSessionSpec(workingDir, sessionId);
1198
+ const specSection = specContent
1199
+ ? `\n\nCurrent spec.md:\n${specContent}`
1200
+ : '';
1201
+ const userMessage = `Research task: "${task}"
1202
+
1203
+ Agent findings:
1204
+ ${agentResult}
1205
+ ${specSection}
1206
+
1207
+ Augment the agent's findings with relevant context from the spec. Pass ALL details through verbatim.`;
1208
+ let responseText = null;
1209
+ if (anthropicClient) {
1210
+ const response = await anthropicClient.messages.create({
1211
+ model: ANTHROPIC_FAST_MODEL,
1212
+ max_tokens: 16000,
1213
+ system: AUGMENT_RESULT_SYSTEM,
1214
+ messages: [{ role: 'user', content: userMessage }]
1215
+ });
1216
+ responseText = response.content[0].type === 'text' ? response.content[0].text : null;
1217
+ }
1218
+ else if (geminiClient) {
1219
+ const response = await geminiClient.models.generateContent({
1220
+ model: GEMINI_FAST_MODEL,
1221
+ contents: userMessage,
1222
+ config: { systemInstruction: AUGMENT_RESULT_SYSTEM }
1223
+ });
1224
+ responseText = response.text || null;
1225
+ }
1226
+ if (!responseText || responseText.length < agentResult.length * 0.5) {
1227
+ // If augmented result is suspiciously shorter, the LLM likely summarized — use original
1228
+ console.log('⚠️ augmentResearchResult: augmented result too short, using original');
1229
+ return agentResult;
1230
+ }
1231
+ console.log(`🔄 augmentResearchResult: augmented ${agentResult.length} → ${responseText.length} chars`);
1232
+ return responseText;
1233
+ }
1234
+ catch (err) {
1235
+ console.error('❌ augmentResearchResult failed:', err);
1236
+ return agentResult; // Fallback to original on error
1237
+ }
1238
+ }
1239
+ // ============================================================
1240
+ // updateSpecFromJSONL — Post-research spec consolidation via JSONL
1241
+ // ============================================================
1242
+ /**
1243
+ * Update spec.md after research completes.
1244
+ * Reads FULL untruncated data directly from Claude Agent SDK JSONL files
1245
+ * instead of receiving pre-truncated content chunks.
1246
+ *
1247
+ * Data sources:
1248
+ * - getRecentToolResults() — last 30 full tool results (Read, Bash, WebSearch, etc.)
1249
+ * - readSessionHistory() — last 50 assistant messages (agent reasoning/analysis)
1250
+ * - getSubagentTranscripts() — all sub-agent findings
1251
+ *
1252
+ * Returns { spec } or null if update failed.
1253
+ */
1254
+ export async function updateSpecFromJSONL(workingDir, sessionId, task, researchLog, sessionBaseDir) {
1255
+ initProvider();
1256
+ if (provider === 'none')
1257
+ return null;
1258
+ try {
1259
+ // 1. Read FULL data from JSONL — no truncation
1260
+ const toolResults = getRecentToolResults(sessionId, workingDir, 30);
1261
+ const assistantMessages = readSessionHistory(sessionId, workingDir, {
1262
+ lastN: 50,
1263
+ types: ['assistant']
1264
+ });
1265
+ const subagents = getSubagentTranscripts(sessionId, workingDir);
1266
+ // 2. Build comprehensive content from FULL data
1267
+ const contentChunks = [];
1268
+ // Tool results — full content
1269
+ if (toolResults.length > 0) {
1270
+ const toolContent = toolResults.map(tr => {
1271
+ const inputPreview = JSON.stringify(tr.toolInput).substring(0, 200);
1272
+ return `[${tr.toolName}: ${inputPreview}]\n${tr.resultContent}`;
1273
+ }).join('\n\n---\n\n');
1274
+ contentChunks.push(toolContent);
1275
+ }
1276
+ // Agent reasoning — full text
1277
+ const agentTexts = assistantMessages
1278
+ .filter(m => m.text && m.text.length > 20)
1279
+ .map(m => `[Agent reasoning]\n${m.text}`);
1280
+ if (agentTexts.length > 0) {
1281
+ contentChunks.push(agentTexts.join('\n\n'));
1282
+ }
1283
+ // Sub-agent findings — full text
1284
+ if (subagents.length > 0) {
1285
+ const subagentContent = subagents.map(sa => {
1286
+ const findings = sa.messages
1287
+ .filter(m => m.type === 'assistant' && m.text)
1288
+ .map(m => `[Sub-agent ${sa.taskId}]\n${m.text}`);
1289
+ return findings.join('\n\n');
1290
+ }).filter(c => c.length > 0);
1291
+ if (subagentContent.length > 0) {
1292
+ contentChunks.push(subagentContent.join('\n\n'));
1293
+ }
1294
+ }
1295
+ // Research log summary
1296
+ if (researchLog.length > 0) {
1297
+ contentChunks.push(`[Research log summary]\n${researchLog.slice(0, 25).join('\n')}`);
1298
+ }
1299
+ if (contentChunks.length === 0) {
1300
+ console.log('⚠️ updateSpecFromJSONL: no content found in JSONL');
1301
+ return null;
1302
+ }
1303
+ const totalChars = contentChunks.reduce((sum, c) => sum + c.length, 0);
1304
+ console.log(`📖 updateSpecFromJSONL: read ${toolResults.length} tool results, ${agentTexts.length} agent messages, ${subagents.length} sub-agents (${totalChars} total chars)`);
1305
+ // 3. Pass to processResearchChunk with isRefinement=true
1306
+ return processResearchChunk(workingDir, sessionId, task, contentChunks, true, sessionBaseDir);
1307
+ }
1308
+ catch (err) {
1309
+ console.error('❌ updateSpecFromJSONL failed:', err);
1310
+ return null;
1311
+ }
1312
+ }
1313
+ // ============================================================
1314
+ // Fire-and-forget: Question Writer — writes user question to spec BEFORE agent starts
1315
+ // ============================================================
1316
+ /**
1317
+ * Fire-and-forget: Write a user question to spec.md Open Questions > From User
1318
+ * before the agent starts researching. Ensures every escalated question is tracked.
1319
+ *
1320
+ * Uses a simple LLM call to fuzzy-match existing questions and avoid duplicates.
1321
+ * Skips if spec.md doesn't exist yet or no provider is available.
1322
+ */
1323
+ export async function writeQuestionToSpec(workingDir, sessionId, question) {
1324
+ initProvider();
1325
+ if (provider === 'none')
1326
+ return;
1327
+ try {
1328
+ const workspace = getSessionWorkspace(workingDir, sessionId);
1329
+ const specPath = `${workspace}/spec.md`;
1330
+ if (!existsSync(specPath))
1331
+ return;
1332
+ const currentSpec = readFileSync(specPath, 'utf-8');
1333
+ // Quick check: if the question (or something very similar) is already in the spec, skip
1334
+ const normalizedQ = question.toLowerCase().replace(/[^a-z0-9\s]/g, '').trim();
1335
+ if (normalizedQ.length < 10)
1336
+ return; // Too short to track
1337
+ const systemPrompt = `You manage the "Open Questions" section of a research spec file.
1338
+
1339
+ Given the current spec.md and a new user question, decide:
1340
+ 1. Is this question (or something very similar) already tracked? If yes, output: SKIP
1341
+ 2. If not, output the COMPLETE updated spec.md with the question added under "## Open Questions > ### From User (unanswered)" as a checkbox: - [ ] Question
1342
+
1343
+ Rules:
1344
+ - Add a timestamp: (asked ${new Date().toLocaleTimeString()})
1345
+ - Do NOT modify any other section of the spec
1346
+ - Do NOT mark existing questions as answered
1347
+ - Output ONLY the full spec.md content or the word SKIP — nothing else`;
1348
+ const userMessage = `Current spec.md:\n\`\`\`\n${currentSpec}\n\`\`\`\n\nNew user question to track:\n"${question}"`;
1349
+ let responseText = null;
1350
+ if (anthropicClient) {
1351
+ const response = await anthropicClient.messages.create({
1352
+ model: ANTHROPIC_FAST_MODEL,
1353
+ max_tokens: 8000,
1354
+ system: systemPrompt,
1355
+ messages: [{ role: 'user', content: userMessage }]
1356
+ });
1357
+ responseText = response.content[0].type === 'text' ? response.content[0].text : null;
1358
+ }
1359
+ else if (geminiClient) {
1360
+ const response = await geminiClient.models.generateContent({
1361
+ model: GEMINI_FAST_MODEL,
1362
+ contents: userMessage,
1363
+ config: { systemInstruction: systemPrompt }
1364
+ });
1365
+ responseText = response.text || null;
1366
+ }
1367
+ if (!responseText || responseText.trim() === 'SKIP') {
1368
+ console.log(`📝 writeQuestionToSpec: question already tracked or skipped`);
1369
+ return;
1370
+ }
1371
+ // Strip code fences if present
1372
+ let updatedSpec = responseText.trim();
1373
+ if (updatedSpec.startsWith('```')) {
1374
+ updatedSpec = updatedSpec.replace(/^```(?:markdown)?\n?/, '').replace(/\n?```$/, '');
1375
+ }
1376
+ // Sanity check: updated spec should be at least as long as current spec
1377
+ if (updatedSpec.length >= currentSpec.length * 0.8) {
1378
+ writeFileSync(specPath, updatedSpec, 'utf-8');
1379
+ console.log(`📝 writeQuestionToSpec: added question to spec (${updatedSpec.length} chars)`);
1380
+ }
1381
+ }
1382
+ catch (err) {
1383
+ console.error('❌ writeQuestionToSpec failed:', err);
1384
+ }
1385
+ }
1386
+ // ============================================================
1387
+ // Fire-and-forget: Answer Checker — checks agent output against open questions
1388
+ // ============================================================
1389
+ // Debounce guard: prevent flooding during rapid tool_result sequences
1390
+ let answerCheckTimer = null;
1391
+ let pendingAnswerCheck = null;
1392
+ /**
1393
+ * Fire-and-forget: Check if substantial agent output answers any open questions in spec.md.
1394
+ * Debounced (3s) to prevent flooding during rapid tool_result sequences.
1395
+ *
1396
+ * When a question is answered, marks it with [x] and moves the answer to Findings.
1397
+ */
1398
+ export async function checkOutputAgainstQuestions(workingDir, sessionId, output, outputType) {
1399
+ // Store the latest check request (newer output replaces older)
1400
+ pendingAnswerCheck = { workingDir, sessionId, output, outputType };
1401
+ // Debounce: only fire after 3s of quiet
1402
+ if (answerCheckTimer)
1403
+ return;
1404
+ answerCheckTimer = setTimeout(async () => {
1405
+ answerCheckTimer = null;
1406
+ const check = pendingAnswerCheck;
1407
+ pendingAnswerCheck = null;
1408
+ if (!check)
1409
+ return;
1410
+ await executeAnswerCheck(check.workingDir, check.sessionId, check.output, check.outputType);
1411
+ }, 3000);
1412
+ }
1413
+ async function executeAnswerCheck(workingDir, sessionId, output, outputType) {
1414
+ initProvider();
1415
+ if (provider === 'none')
1416
+ return;
1417
+ try {
1418
+ const workspace = getSessionWorkspace(workingDir, sessionId);
1419
+ const specPath = `${workspace}/spec.md`;
1420
+ if (!existsSync(specPath))
1421
+ return;
1422
+ const currentSpec = readFileSync(specPath, 'utf-8');
1423
+ // Quick check: are there any open questions?
1424
+ if (!currentSpec.includes('- [ ]')) {
1425
+ return; // No open questions to check against
1426
+ }
1427
+ const systemPrompt = `You check if research output answers any open questions in a spec file.
1428
+
1429
+ Given the current spec.md and a piece of agent output (${outputType}), decide:
1430
+ 1. Does this output answer (fully or partially) any "- [ ]" questions in "## Open Questions"?
1431
+ 2. If YES: output the COMPLETE updated spec.md with:
1432
+ - Answered questions marked: - [x] Question → Brief answer summary (from research)
1433
+ - Key findings added to "## Findings & Resources" section
1434
+ 3. If NO questions are answered: output NONE
1435
+
1436
+ Rules:
1437
+ - Only mark a question answered if the output CLEARLY provides the answer
1438
+ - Keep the answer summary brief (1-2 sentences)
1439
+ - Do NOT modify questions that aren't answered by this output
1440
+ - Do NOT remove or rewrite existing Findings
1441
+ - Output ONLY the full spec.md content or the word NONE — nothing else`;
1442
+ // Truncate output to avoid overwhelming the model on very large tool results
1443
+ const truncatedOutput = output.length > 15000 ? output.substring(0, 15000) + '\n[... truncated]' : output;
1444
+ const userMessage = `Current spec.md:\n\`\`\`\n${currentSpec}\n\`\`\`\n\nAgent output (${outputType}):\n\`\`\`\n${truncatedOutput}\n\`\`\``;
1445
+ let responseText = null;
1446
+ if (anthropicClient) {
1447
+ const response = await anthropicClient.messages.create({
1448
+ model: ANTHROPIC_FAST_MODEL,
1449
+ max_tokens: 8000,
1450
+ system: systemPrompt,
1451
+ messages: [{ role: 'user', content: userMessage }]
1452
+ });
1453
+ responseText = response.content[0].type === 'text' ? response.content[0].text : null;
1454
+ }
1455
+ else if (geminiClient) {
1456
+ const response = await geminiClient.models.generateContent({
1457
+ model: GEMINI_FAST_MODEL,
1458
+ contents: userMessage,
1459
+ config: { systemInstruction: systemPrompt }
1460
+ });
1461
+ responseText = response.text || null;
1462
+ }
1463
+ if (!responseText || responseText.trim() === 'NONE') {
1464
+ return;
1465
+ }
1466
+ // Strip code fences if present
1467
+ let updatedSpec = responseText.trim();
1468
+ if (updatedSpec.startsWith('```')) {
1469
+ updatedSpec = updatedSpec.replace(/^```(?:markdown)?\n?/, '').replace(/\n?```$/, '');
1470
+ }
1471
+ // Sanity check
1472
+ if (updatedSpec.length >= currentSpec.length * 0.8) {
1473
+ writeFileSync(specPath, updatedSpec, 'utf-8');
1474
+ console.log(`✅ checkOutputAgainstQuestions: marked question(s) as answered in spec (${updatedSpec.length} chars)`);
1475
+ }
1476
+ }
1477
+ catch (err) {
1478
+ console.error('❌ checkOutputAgainstQuestions failed:', err);
1479
+ }
1480
+ }
1481
+ // ============================================================
1482
+ // contextualizeResearchUpdate — Fast brain generates natural voice updates during research
1483
+ // ============================================================
1484
+ /**
1485
+ * Generate a natural, contextualized voice update from raw research events.
1486
+ * Called by scheduleResearchBatch() instead of injecting raw events directly.
1487
+ *
1488
+ * Returns a natural 1-2 sentence update, or null if nothing interesting to say.
1489
+ * 3-second timeout — returns null if the LLM is too slow.
1490
+ */
1491
+ export async function contextualizeResearchUpdate(workingDir, sessionId, task, batchEvents, researchLog, chatHistory, sessionBaseDir) {
1492
+ initProvider();
1493
+ if (provider === 'none')
1494
+ return null;
1495
+ const wsDir = workingDir;
1496
+ try {
1497
+ const specContent = readSessionSpec(wsDir, sessionId);
1498
+ const specTruncated = specContent ? specContent.substring(0, 1500) : '';
1499
+ // Read last 5 tool results for what was just found
1500
+ const recentResults = getRecentToolResults(sessionId, workingDir, 5);
1501
+ const resultsSummary = recentResults.map(tr => {
1502
+ const inputPreview = JSON.stringify(tr.toolInput).substring(0, 100);
1503
+ const resultPreview = tr.resultContent.substring(0, 200);
1504
+ return `[${tr.toolName}: ${inputPreview}] ${resultPreview}`;
1505
+ }).join('\n');
1506
+ const userMessage = `Research question: "${task}"
1507
+
1508
+ Recent events: ${batchEvents.slice(-10).join('. ')}
1509
+
1510
+ Research log (${researchLog.length} total steps): ${researchLog.slice(-15).join('. ')}
1511
+
1512
+ Recent findings:
1513
+ ${resultsSummary}
1514
+
1515
+ ${specTruncated ? `Spec context:\n${specTruncated}` : ''}`;
1516
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(null), 3000));
1517
+ let responsePromise;
1518
+ if (anthropicClient) {
1519
+ responsePromise = anthropicClient.messages.create({
1520
+ model: ANTHROPIC_FAST_MODEL,
1521
+ max_tokens: 200,
1522
+ system: CONTEXTUALIZE_UPDATE_SYSTEM,
1523
+ messages: [{ role: 'user', content: userMessage }]
1524
+ }).then(r => r.content[0].type === 'text' ? r.content[0].text : null);
1525
+ }
1526
+ else if (geminiClient) {
1527
+ responsePromise = geminiClient.models.generateContent({
1528
+ model: GEMINI_FAST_MODEL,
1529
+ contents: userMessage,
1530
+ config: { systemInstruction: CONTEXTUALIZE_UPDATE_SYSTEM }
1531
+ }).then(r => r.text || null);
1532
+ }
1533
+ else {
1534
+ return null;
1535
+ }
1536
+ const result = await Promise.race([responsePromise, timeoutPromise]);
1537
+ if (!result || result.trim() === 'NOTHING')
1538
+ return null;
1539
+ return result.trim();
1540
+ }
1541
+ catch (err) {
1542
+ console.error('❌ contextualizeResearchUpdate failed:', err);
1543
+ return null;
1544
+ }
1545
+ }
1546
+ // ============================================================
1547
+ // generateProactivePrompt — Fast brain generates conversation during research silence
1548
+ // ============================================================
1549
+ /**
1550
+ * Generate a proactive conversational prompt to keep the user engaged during research.
1551
+ * Called periodically (every 15s) during active research.
1552
+ *
1553
+ * Can ask open questions, discuss implications of findings, or give progress with depth.
1554
+ * Returns null/NOTHING if nothing interesting to say.
1555
+ * 3-second timeout.
1556
+ */
1557
+ export async function generateProactivePrompt(workingDir, sessionId, task, researchLog, previousPrompts, sessionBaseDir) {
1558
+ initProvider();
1559
+ if (provider === 'none')
1560
+ return null;
1561
+ const wsDir = workingDir;
1562
+ try {
1563
+ const specContent = readSessionSpec(wsDir, sessionId);
1564
+ const specTruncated = specContent ? specContent.substring(0, 2000) : '';
1565
+ // Read recent discoveries from JSONL
1566
+ const recentResults = getRecentToolResults(sessionId, workingDir, 8);
1567
+ const resultsSummary = recentResults.map(tr => {
1568
+ const inputPreview = JSON.stringify(tr.toolInput).substring(0, 100);
1569
+ const resultPreview = tr.resultContent.substring(0, 300);
1570
+ return `[${tr.toolName}: ${inputPreview}] ${resultPreview}`;
1571
+ }).join('\n');
1572
+ // Read recent agent reasoning
1573
+ const recentText = readSessionHistory(sessionId, workingDir, {
1574
+ lastN: 5,
1575
+ types: ['assistant']
1576
+ });
1577
+ const reasoningSummary = recentText
1578
+ .filter(m => m.text && m.text.length > 20)
1579
+ .map(m => m.text.substring(0, 300))
1580
+ .join('\n');
1581
+ const userMessage = `Research question: "${task}"
1582
+
1583
+ Research progress (${researchLog.length} steps so far): ${researchLog.slice(-10).join('. ')}
1584
+
1585
+ Recent findings:
1586
+ ${resultsSummary}
1587
+
1588
+ Agent reasoning:
1589
+ ${reasoningSummary}
1590
+
1591
+ ${specTruncated ? `Session spec:\n${specTruncated}` : ''}
1592
+
1593
+ Previous things already said (DO NOT repeat):
1594
+ ${previousPrompts.length > 0 ? previousPrompts.join('\n') : '(none yet)'}`;
1595
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(null), 3000));
1596
+ let responsePromise;
1597
+ if (anthropicClient) {
1598
+ responsePromise = anthropicClient.messages.create({
1599
+ model: ANTHROPIC_FAST_MODEL,
1600
+ max_tokens: 200,
1601
+ system: PROACTIVE_PROMPT_SYSTEM,
1602
+ messages: [{ role: 'user', content: userMessage }]
1603
+ }).then(r => r.content[0].type === 'text' ? r.content[0].text : null);
1604
+ }
1605
+ else if (geminiClient) {
1606
+ responsePromise = geminiClient.models.generateContent({
1607
+ model: GEMINI_FAST_MODEL,
1608
+ contents: userMessage,
1609
+ config: { systemInstruction: PROACTIVE_PROMPT_SYSTEM }
1610
+ }).then(r => r.text || null);
1611
+ }
1612
+ else {
1613
+ return null;
1614
+ }
1615
+ const result = await Promise.race([responsePromise, timeoutPromise]);
1616
+ if (!result || result.trim() === 'NOTHING')
1617
+ return null;
1618
+ return result.trim();
1619
+ }
1620
+ catch (err) {
1621
+ console.error('❌ generateProactivePrompt failed:', err);
1622
+ return null;
1623
+ }
1624
+ }
1625
+ // ============================================================
1626
+ // generateVisualDocument — Fast brain generates structured visual documents
1627
+ // ============================================================
1628
+ /**
1629
+ * Generate a structured visual document (comparison table, Mermaid diagram,
1630
+ * analysis, or summary) from research findings.
1631
+ *
1632
+ * Reads spec.md and JSONL results for context.
1633
+ * Writes the result to workspace and returns the filename + content.
1634
+ */
1635
+ export async function generateVisualDocument(workingDir, sessionId, request, documentType, sessionBaseDir) {
1636
+ initProvider();
1637
+ if (provider === 'none')
1638
+ return null;
1639
+ const wsDir = workingDir;
1640
+ try {
1641
+ const workspace = getSessionWorkspace(wsDir, sessionId);
1642
+ const specContent = readSessionSpec(wsDir, sessionId) || '';
1643
+ // Read recent JSONL results for raw data
1644
+ const toolResults = getRecentToolResults(sessionId, workingDir, 20);
1645
+ const toolResultsSummary = toolResults.map(tr => {
1646
+ const inputPreview = JSON.stringify(tr.toolInput).substring(0, 150);
1647
+ return `[${tr.toolName}: ${inputPreview}]\n${tr.resultContent.substring(0, 1000)}`;
1648
+ }).join('\n\n---\n\n');
1649
+ const userMessage = `Document request: "${request}"
1650
+ Document type: ${documentType}
1651
+
1652
+ Session spec:
1653
+ ${specContent}
1654
+
1655
+ Recent research data:
1656
+ ${toolResultsSummary}
1657
+
1658
+ Return JSON: {"fileName": "descriptive-name.md", "content": "full markdown content"}`;
1659
+ let responseText = null;
1660
+ if (anthropicClient) {
1661
+ const response = await anthropicClient.messages.create({
1662
+ model: ANTHROPIC_FAST_MODEL,
1663
+ max_tokens: 16000,
1664
+ system: VISUAL_DOCUMENT_SYSTEM,
1665
+ messages: [{ role: 'user', content: userMessage }]
1666
+ });
1667
+ responseText = response.content[0].type === 'text' ? response.content[0].text : null;
1668
+ }
1669
+ else if (geminiClient) {
1670
+ const response = await geminiClient.models.generateContent({
1671
+ model: GEMINI_FAST_MODEL,
1672
+ contents: userMessage,
1673
+ config: { systemInstruction: VISUAL_DOCUMENT_SYSTEM }
1674
+ });
1675
+ responseText = response.text || null;
1676
+ }
1677
+ if (!responseText)
1678
+ return null;
1679
+ // Parse JSON response
1680
+ const cleaned = responseText.replace(/^```json?\s*/i, '').replace(/\s*```$/i, '').trim();
1681
+ let parsed;
1682
+ try {
1683
+ parsed = JSON.parse(cleaned);
1684
+ }
1685
+ catch {
1686
+ // Try to extract from malformed response
1687
+ const fnMatch = cleaned.match(/"fileName"\s*:\s*"([^"]+)"/);
1688
+ const ctMatch = cleaned.match(/"content"\s*:\s*"((?:[^"\\]|\\.)*)"/s);
1689
+ if (fnMatch && ctMatch) {
1690
+ try {
1691
+ parsed = { fileName: fnMatch[1], content: JSON.parse(`"${ctMatch[1]}"`) };
1692
+ }
1693
+ catch {
1694
+ console.error('⚠️ generateVisualDocument: failed to parse response');
1695
+ return null;
1696
+ }
1697
+ }
1698
+ else {
1699
+ return null;
1700
+ }
1701
+ }
1702
+ if (!parsed.fileName || !parsed.content)
1703
+ return null;
1704
+ // Write to workspace
1705
+ const safeName = parsed.fileName.replace(/[^a-zA-Z0-9._-]/g, '-');
1706
+ mkdirSync(workspace, { recursive: true });
1707
+ const filePath = `${workspace}/${safeName}`;
1708
+ writeFileSync(filePath, parsed.content, 'utf-8');
1709
+ console.log(`📊 generateVisualDocument: wrote ${safeName} (${parsed.content.length} chars)`);
1710
+ return { fileName: safeName, content: parsed.content };
1711
+ }
1712
+ catch (err) {
1713
+ console.error('❌ generateVisualDocument failed:', err);
1714
+ return null;
1715
+ }
1716
+ }
1717
+ // ============================================================
1718
+ // processResearchCompletion — Generate teleprompter script from research results
1719
+ // ============================================================
1720
+ /**
1721
+ * Generate a complete teleprompter script from research results.
1722
+ * Replaces augmentResearchResult + extractPriorityContent.
1723
+ * Reads full JSONL and produces a spoken monologue.
1724
+ */
1725
+ export async function processResearchCompletion(workingDir, sessionId, task, agentResult, chatHistory, sendToChat, sessionBaseDir) {
1726
+ initProvider();
1727
+ if (provider === 'none')
1728
+ return agentResult.substring(0, 500);
1729
+ const wsDir = workingDir;
1730
+ try {
1731
+ // Read spec for context
1732
+ const specContent = readSessionSpec(wsDir, sessionId) || '';
1733
+ // Read FULL JSONL data — not truncated. The user waited for this research;
1734
+ // give the completion generator the complete picture.
1735
+ const toolResults = getRecentToolResults(sessionId, workingDir, 30);
1736
+ const toolSummary = toolResults.map(tr => {
1737
+ const inputPreview = JSON.stringify(tr.toolInput).substring(0, 200);
1738
+ return `[${tr.toolName}: ${inputPreview}]\n${tr.resultContent}`;
1739
+ }).join('\n\n---\n\n');
1740
+ // Also read agent reasoning for synthesis context
1741
+ const agentTexts = readSessionHistory(sessionId, workingDir, {
1742
+ lastN: 20,
1743
+ types: ['assistant']
1744
+ }).filter(m => m.text && m.text.length > 30)
1745
+ .map(m => m.text)
1746
+ .join('\n\n');
1747
+ // Read sub-agent findings if any
1748
+ const subagents = getSubagentTranscripts(sessionId, workingDir);
1749
+ const subagentSummary = subagents.length > 0
1750
+ ? subagents.map(sa => {
1751
+ const texts = sa.messages.filter(m => m.text && m.text.length > 30).map(m => m.text);
1752
+ return `[Sub-agent ${sa.taskId}]\n${texts.join('\n')}`;
1753
+ }).join('\n\n')
1754
+ : '';
1755
+ const historyStr = chatHistory
1756
+ ? chatHistory.slice(-10).map(t => `${t.role}: ${t.text}`).join('\n')
1757
+ : '';
1758
+ const userMessage = `Research task: "${task}"
1759
+
1760
+ Agent's headline findings:
1761
+ ${agentResult}
1762
+
1763
+ Full tool outputs (${toolResults.length} results):
1764
+ ${toolSummary}
1765
+
1766
+ ${agentTexts ? `Agent reasoning and analysis:\n${agentTexts.substring(0, 8000)}` : ''}
1767
+
1768
+ ${subagentSummary ? `Sub-agent findings:\n${subagentSummary.substring(0, 4000)}` : ''}
1769
+
1770
+ ${specContent ? `Session spec (for context):\n${specContent.substring(0, 3000)}` : ''}
1771
+
1772
+ ${historyStr ? `Recent conversation (match this vocabulary):\n${historyStr}` : ''}
1773
+
1774
+ Write the spoken monologue now. The user waited for this research — be comprehensive.${sendToChat ? ' If you have structured data (lists, URLs, code, steps), include a CHAT_CONTENT section at the end after a line "---CHAT---" with markdown content to send to the chat panel.' : ''}`;
1775
+ let script = null;
1776
+ if (anthropicClient) {
1777
+ const response = await anthropicClient.messages.create({
1778
+ model: ANTHROPIC_FAST_MODEL,
1779
+ max_tokens: 4000,
1780
+ system: RESEARCH_COMPLETION_SYSTEM,
1781
+ messages: [{ role: 'user', content: userMessage }]
1782
+ });
1783
+ script = response.content[0].type === 'text' ? response.content[0].text : null;
1784
+ }
1785
+ else if (geminiClient) {
1786
+ const response = await geminiClient.models.generateContent({
1787
+ model: GEMINI_FAST_MODEL,
1788
+ contents: userMessage,
1789
+ config: { systemInstruction: RESEARCH_COMPLETION_SYSTEM }
1790
+ });
1791
+ script = response.text || null;
1792
+ }
1793
+ if (!script)
1794
+ return agentResult.substring(0, 500);
1795
+ // Check for chat content section
1796
+ if (sendToChat && script.includes('---CHAT---')) {
1797
+ const parts = script.split('---CHAT---');
1798
+ const spokenPart = parts[0].trim();
1799
+ const chatPart = parts[1]?.trim();
1800
+ if (chatPart) {
1801
+ console.log(`💬 processResearchCompletion: sending ${chatPart.length} chars to chat`);
1802
+ sendToChat(chatPart);
1803
+ }
1804
+ console.log(`🎙️ processResearchCompletion: generated ${spokenPart.length} char script + ${chatPart?.length || 0} char chat content`);
1805
+ return spokenPart;
1806
+ }
1807
+ console.log(`🎙️ processResearchCompletion: generated ${script.length} char script`);
1808
+ return script;
1809
+ }
1810
+ catch (err) {
1811
+ console.error('❌ processResearchCompletion failed:', err);
1812
+ // Fallback: return truncated agent result as-is
1813
+ return agentResult.substring(0, 500);
1814
+ }
1815
+ }
1816
+ // ============================================================
1817
+ // handleResearchBatch — Decide whether research events are worth speaking
1818
+ // ============================================================
1819
+ /**
1820
+ * Process a batch of research events and decide whether to speak.
1821
+ * Replaces contextualizeResearchUpdate — but usually returns null (silent).
1822
+ * Only speaks when something genuinely critical is found.
1823
+ */
1824
+ export async function handleResearchBatch(workingDir, sessionId, task, batchEvents, researchLog, chatHistory, sessionBaseDir) {
1825
+ // Usually: stay silent. The frontend spinner handles visual feedback.
1826
+ // Only speak if the batch contains something genuinely interesting.
1827
+ // Quick heuristic: if fewer than 5 research steps, too early to say anything useful
1828
+ if (researchLog.length < 5)
1829
+ return null;
1830
+ // Check if any event mentions something critical (error, user-impacting finding)
1831
+ const hasCritical = batchEvents.some(e => e.toLowerCase().includes('error') ||
1832
+ e.toLowerCase().includes('warning') ||
1833
+ e.toLowerCase().includes('breaking') ||
1834
+ e.toLowerCase().includes('deprecated'));
1835
+ if (!hasCritical)
1836
+ return null;
1837
+ // Something interesting — generate a brief spoken update via contextualizeResearchUpdate
1838
+ return contextualizeResearchUpdate(workingDir, sessionId, task, batchEvents, researchLog, chatHistory, sessionBaseDir);
1839
+ }
1840
+ // ============================================================
1841
+ // prepareBriefingScript — Session resume/switch spoken briefing
1842
+ // ============================================================
1843
+ /**
1844
+ * Generate a brief spoken script for session resume or switch.
1845
+ * Replaces buildContextBriefing + getSpecForVoiceModel.
1846
+ */
1847
+ export async function prepareBriefingScript(workingDir, sessionId, conversationHistory, type = 'default') {
1848
+ initProvider();
1849
+ // Read spec for context
1850
+ const specContent = readSessionSpec(workingDir, sessionId);
1851
+ if (!specContent && (!conversationHistory || conversationHistory.length === 0)) {
1852
+ return type === 'switch'
1853
+ ? 'Switched sessions. What would you like to work on?'
1854
+ : 'Welcome back. What would you like to work on?';
1855
+ }
1856
+ // Extract goal and last topic from spec
1857
+ const goalMatch = specContent?.match(/## Goal\s*\n([\s\S]*?)(?=\n##|$)/);
1858
+ const goal = goalMatch ? goalMatch[1].trim().substring(0, 200) : '';
1859
+ const prefix = type === 'switch' ? 'Switched over.' : 'Welcome back.';
1860
+ // If we have a goal, generate a brief spoken briefing
1861
+ if (goal) {
1862
+ const lastExchanges = conversationHistory
1863
+ ? conversationHistory.slice(-3).map(e => `${e.role}: ${e.text.substring(0, 100)}`).join('. ')
1864
+ : '';
1865
+ if (lastExchanges) {
1866
+ return `${prefix} We were working on ${goal}. Last time we discussed ${lastExchanges.substring(0, 150)}. Where would you like to pick up?`;
1867
+ }
1868
+ return `${prefix} We were working on ${goal}. Where would you like to pick up?`;
1869
+ }
1870
+ return type === 'switch'
1871
+ ? 'Switched sessions. What would you like to work on?'
1872
+ : 'Session resumed. What would you like to work on?';
1873
+ }
1874
+ // ============================================================
1875
+ // prepareRecoveryScript — Gemini crash recovery spoken script
1876
+ // ============================================================
1877
+ /**
1878
+ * Generate a spoken script after Gemini auto-recovery.
1879
+ * Replaces inline recovery logic in index.ts.
1880
+ */
1881
+ export async function prepareRecoveryScript(conversationHistory) {
1882
+ if (conversationHistory && conversationHistory.length > 0) {
1883
+ const lastTopic = conversationHistory[conversationHistory.length - 1];
1884
+ return `Voice session was briefly interrupted but I'm back. We were talking about ${lastTopic.text.substring(0, 100)}. Where were we?`;
1885
+ }
1886
+ return 'Voice session was briefly interrupted but I\'m back. What were we working on?';
1887
+ }