⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
Updated hooks.
Daniel Miesslera9594be0325a
diff --git a/.claude/hooks/load-dynamic-requirements.ts b/.claude/hooks/load-dynamic-requirements.tsold mode 100755new mode 100644index fc07c97e..a8e787c2--- a/.claude/hooks/load-dynamic-requirements.ts+++ b/.claude/hooks/load-dynamic-requirements.ts@@ -51,7 +51,7 @@ async function main() {const paiDir = process.env.PAI_DIR || `${process.env.HOME}/.claude`;const mdPath = `${paiDir}/commands/load-dynamic-requirements.md`;const mdContent = readFileSync(mdPath, 'utf-8');-+// Output the markdown content to stdout// This will be passed to Claude as instructionsconsole.log(mdContent);diff --git a/.claude/hooks/session-start-hook.ts b/.claude/hooks/session-start-hook.tsindex 88664124..6da946b9 100755--- a/.claude/hooks/session-start-hook.ts+++ b/.claude/hooks/session-start-hook.ts@@ -1,5 +1,7 @@#!/usr/bin/env bun+import { existsSync, statSync } from 'fs';+async function sendNotification(title: string, message: string, priority: string = 'normal') {try {const response = await fetch('http://localhost:8888/notify', {@@ -15,7 +17,7 @@ async function sendNotification(title: string, message: string, priority: stringvoice_id: 'jqcCZkN6Knx8BJ5TBdYR' // Assistant's voice ID}),});-+if (!response.ok) {console.error(`Notification failed: ${response.status}`);}@@ -24,10 +26,54 @@ async function sendNotification(title: string, message: string, priority: string}}+async function testStopHook() {+ const stopHookPath = '/Users/daniel/.claude/hooks/stop-hook.ts';++ console.error('\n🔍 Testing stop-hook configuration...');++ // Check if stop-hook exists+ if (!existsSync(stopHookPath)) {+ console.error('❌ Stop-hook NOT FOUND at:', stopHookPath);+ return false;+ }++ // Check if stop-hook is executable+ try {+ const stats = statSync(stopHookPath);+ const isExecutable = (stats.mode & 0o111) !== 0;++ if (!isExecutable) {+ console.error('❌ Stop-hook exists but is NOT EXECUTABLE');+ return false;+ }++ console.error('✅ Stop-hook found and is executable');++ // Set initial tab title to show session started with Kai ready+ process.stderr.write('\x1b]0;Kai Ready\x07');+ process.stderr.write('\x1b]2;Kai Ready\x07');+ process.stderr.write('\x1b]30;Kai Ready\x07');+ console.error('📍 Set initial tab title: "Kai Ready"');++ return true;+ } catch (e) {+ console.error('❌ Error checking stop-hook:', e);+ return false;+ }+}+async function main() {try {- const daName = process.env.DA || 'Assistant';+ // Test stop-hook first+ const stopHookOk = await testStopHook();++ const daName = process.env.DA || 'Kai';const message = `${daName} here, ready to go.`;++ if (!stopHookOk) {+ console.error('\n⚠️ STOP-HOOK ISSUE DETECTED - Tab titles may not update automatically');+ }+await sendNotification(`${daName} Systems Initialized`, message, 'low');process.exit(0);} catch (error) {diff --git a/.claude/hooks/stop-hook.ts b/.claude/hooks/stop-hook.tsindex 1425fb0d..3ce31352 100755--- a/.claude/hooks/stop-hook.ts+++ b/.claude/hooks/stop-hook.ts@@ -3,10 +3,34 @@import { readFileSync } from 'fs';/**- * Generate 3-word tab title from user prompt+ * Generate 4-word tab title summarizing what was done*/-function generateTabTitle(prompt: string): string {- // Clean the prompt and extract meaningful words+function generateTabTitle(prompt: string, completedLine?: string): string {+ // If we have a completed line, try to use it for a better summary+ if (completedLine) {+ const cleanCompleted = completedLine+ .replace(/\*+/g, '')+ .replace(/\[.*?\]/g, '')+ .replace(/🎯\s*COMPLETED:\s*/gi, '')+ .trim();++ // Extract meaningful words from the completed line+ const completedWords = cleanCompleted.split(/\s+/)+ .filter(word => word.length > 2 &&+ !['the', 'and', 'but', 'for', 'are', 'with', 'his', 'her', 'this', 'that', 'you', 'can', 'will', 'have', 'been', 'your', 'from', 'they', 'were', 'said', 'what', 'them', 'just', 'told', 'how', 'does', 'into', 'about', 'completed'].includes(word.toLowerCase()))+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());++ if (completedWords.length >= 2) {+ // Build a 4-word summary from completed line+ const summary = completedWords.slice(0, 4);+ while (summary.length < 4) {+ summary.push('Done');+ }+ return summary.slice(0, 4).join(' ');+ }+ }++ // Fall back to parsing the promptconst cleanPrompt = prompt.replace(/[^\w\s]/g, ' ').trim();const words = cleanPrompt.split(/\s+/).filter(word =>word.length > 2 &&@@ -16,14 +40,22 @@ function generateTabTitle(prompt: string): string {const lowerPrompt = prompt.toLowerCase();// Find action verb if present- const actionVerbs = ['test', 'rename', 'fix', 'debug', 'research', 'write', 'create', 'make', 'build', 'implement', 'analyze', 'review', 'update', 'modify', 'generate', 'develop', 'design', 'deploy', 'configure', 'setup', 'install', 'remove', 'delete', 'add', 'check', 'verify', 'validate', 'optimize', 'refactor', 'enhance', 'improve', 'send', 'email', 'help'];+ const actionVerbs = ['test', 'rename', 'fix', 'debug', 'research', 'write', 'create', 'make', 'build', 'implement', 'analyze', 'review', 'update', 'modify', 'generate', 'develop', 'design', 'deploy', 'configure', 'setup', 'install', 'remove', 'delete', 'add', 'check', 'verify', 'validate', 'optimize', 'refactor', 'enhance', 'improve', 'send', 'email', 'help', 'updated', 'fixed', 'created', 'built', 'added'];let titleWords = [];// Check for action verbfor (const verb of actionVerbs) {if (lowerPrompt.includes(verb)) {- titleWords.push(verb.charAt(0).toUpperCase() + verb.slice(1));+ // Convert to past tense for summary+ let pastTense = verb;+ if (verb === 'write') pastTense = 'Wrote';+ else if (verb === 'make') pastTense = 'Made';+ else if (verb === 'send') pastTense = 'Sent';+ else if (verb.endsWith('e')) pastTense = verb.charAt(0).toUpperCase() + verb.slice(1, -1) + 'ed';+ else pastTense = verb.charAt(0).toUpperCase() + verb.slice(1) + 'ed';++ titleWords.push(pastTense);break;}}@@ -33,9 +65,9 @@ function generateTabTitle(prompt: string): string {.filter(word => !actionVerbs.includes(word.toLowerCase())).map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());- // Fill up to 3 words total+ // Fill up to 4 words totalfor (const word of remainingWords) {- if (titleWords.length < 3) {+ if (titleWords.length < 4) {titleWords.push(word);} else {break;@@ -44,35 +76,53 @@ function generateTabTitle(prompt: string): string {// If we don't have enough words, add generic onesif (titleWords.length === 0) {- titleWords.push('Kai');+ titleWords.push('Completed');}if (titleWords.length === 1) {titleWords.push('Task');}if (titleWords.length === 2) {- titleWords.push('Complete');+ titleWords.push('Successfully');+ }+ if (titleWords.length === 3) {+ titleWords.push('Done');}- return titleWords.slice(0, 3).join(' ');+ return titleWords.slice(0, 4).join(' ');}/**- * Set Kitty terminal tab title+ * Set terminal tab title (works with Kitty, Ghostty, iTerm2, etc.)*/-function setKittyTabTitle(title: string): void {- // Use OSC escape sequences to set both tab and window title with checkmark- // Send to stderr to bypass potential output filtering+function setTerminalTabTitle(title: string): void {+ // Get terminal type+ const term = process.env.TERM || '';- // OSC 0 sets both icon and window title- process.stderr.write(`\x1b]0;✓ ${title}\x07`);-- // OSC 2 sets window title specifically- process.stderr.write(`\x1b]2;✓ ${title}\x07`);+ // Send to stderr to bypass potential output filtering- // Kitty-specific tab title sequence- process.stderr.write(`\x1b]30;✓ ${title}\x07`);+ if (term.includes('ghostty')) {+ // Ghostty-specific sequences+ // Ghostty uses standard xterm sequences but may need different approach+ process.stderr.write(`\x1b]2;${title}\x07`); // Window title+ process.stderr.write(`\x1b]0;${title}\x07`); // Icon and window title++ // Try OSC 7 for Ghostty tab titles (some terminals use this)+ process.stderr.write(`\x1b]7;${title}\x07`);++ // Also try the standard xterm way with ST terminator+ process.stderr.write(`\x1b]2;${title}\x1b\\`);+ } else if (term.includes('kitty')) {+ // Kitty-specific sequences+ process.stderr.write(`\x1b]0;${title}\x07`);+ process.stderr.write(`\x1b]2;${title}\x07`);+ process.stderr.write(`\x1b]30;${title}\x07`); // Kitty-specific+ } else {+ // Generic sequences for other terminals+ process.stderr.write(`\x1b]0;${title}\x07`); // Icon and window+ process.stderr.write(`\x1b]2;${title}\x07`); // Window title+ }- // Also flush stderr to ensure immediate output+ // Flush stderr to ensure immediate outputif (process.stderr.isTTY) {process.stderr.write('');}@@ -157,6 +207,10 @@ function generateIntelligentResponse(userQuery: string, assistantResponse: strin}async function main() {+ // Log that hook was triggered+ const timestamp = new Date().toISOString();+ console.error(`\n🎬 STOP-HOOK TRIGGERED AT ${timestamp}`);+// Get inputlet input = '';const decoder = new TextDecoder();@@ -169,26 +223,37 @@ async function main() {input += decoder.decode(value, { stream: true });}} catch (e) {+ console.error(`❌ Error reading input: ${e}`);process.exit(0);}- if (!input) process.exit(0);+ if (!input) {+ console.error('❌ No input received');+ process.exit(0);+ }let transcriptPath;try {const parsed = JSON.parse(input);transcriptPath = parsed.transcript_path;+ console.error(`📁 Transcript path: ${transcriptPath}`);} catch (e) {+ console.error(`❌ Error parsing input JSON: ${e}`);process.exit(0);}- if (!transcriptPath) process.exit(0);+ if (!transcriptPath) {+ console.error('❌ No transcript_path in input');+ process.exit(0);+ }// Read the transcriptlet transcript;try {transcript = readFileSync(transcriptPath, 'utf-8');+ console.error(`📜 Transcript loaded: ${transcript.split('\n').length} lines`);} catch (e) {+ console.error(`❌ Error reading transcript: ${e}`);process.exit(0);}@@ -268,11 +333,65 @@ async function main() {// Generate the announcementlet message = '';let voiceId = VOICES.kai; // Default to Kai's voice+ let kaiHasCustomCompleted = false;- if (isAgentTask && taskResult) {- // AGENT DID THE TASK - Look for their CUSTOM COMPLETED or COMPLETED line+ // ALWAYS check Kai's response FIRST (even when agents are used)+ const lastResponse = lines[lines.length - 1];+ try {+ const entry = JSON.parse(lastResponse);+ if (entry.type === 'assistant' && entry.message?.content) {+ const content = entry.message.content.map(c => c.text || '').join(' ');++ // First, look for CUSTOM COMPLETED line (voice-optimized)+ const customCompletedMatch = content.match(/🗣️\s*CUSTOM\s+COMPLETED:\s*(.+?)(?:\n|$)/im);++ if (customCompletedMatch) {+ // Get the custom voice response+ let customText = customCompletedMatch[1].trim()+ .replace(/\[.*?\]/g, '') // Remove bracketed text like [Optional: ...]+ .replace(/\*+/g, '') // Remove asterisks+ .trim();++ // Use custom completed if it's under 8 words+ const wordCount = customText.split(/\s+/).length;+ if (customText && wordCount <= 8) {+ message = customText;+ kaiHasCustomCompleted = true;+ console.error(`🗣️ KAI CUSTOM VOICE: ${message}`);+ } else {+ // Custom completed too long, fall back to regular COMPLETED+ const completedMatch = content.match(/🎯\s*COMPLETED:\s*(.+?)(?:\n|$)/im);+ if (completedMatch) {+ let completedText = completedMatch[1].trim();+ message = generateIntelligentResponse(lastUserQuery, content, completedText);+ console.error(`🎯 KAI FALLBACK (custom too long): ${message}`);+ }+ }+ } else if (!isAgentTask) {+ // No CUSTOM COMPLETED and no agent - look for regular COMPLETED line+ const completedMatch = content.match(/🎯\s*COMPLETED:\s*(.+?)(?:\n|$)/im);- // First, try to find CUSTOM COMPLETED line+ if (completedMatch) {+ // Get the raw text after the colon+ let completedText = completedMatch[1].trim();++ // Generate intelligent response+ message = generateIntelligentResponse(lastUserQuery, content, completedText);++ console.error(`🎯 KAI INTELLIGENT: ${message}`);+ } else {+ // No COMPLETED line found - don't send anything+ console.error('⚠️ No COMPLETED line found');+ }+ }+ }+ } catch (e) {+ console.error('⚠️ Error parsing Kai response:', e);+ }++ // If Kai didn't provide a CUSTOM COMPLETED and an agent was used, check agent's response+ if (!message && isAgentTask && taskResult) {+ // First, try to find CUSTOM COMPLETED line in agent responseconst customCompletedMatch = taskResult.match(/🗣️\s*CUSTOM\s+COMPLETED:\s*(.+?)(?:\n|$)/im);if (customCompletedMatch) {@@ -288,7 +407,7 @@ async function main() {if (customText && wordCount <= 8) {message = customText;voiceId = VOICES[agentType.toLowerCase()] || VOICES.kai;- console.error(`🗣️ AGENT CUSTOM VOICE: ${message}`);+ console.error(`🗣️ AGENT CUSTOM VOICE (fallback): ${message}`);} else {// Custom completed too long, fall back to regular COMPLETEDconst completedMatch = taskResult.match(/🎯\s*COMPLETED:\s*(.+?)$/im);@@ -320,86 +439,68 @@ async function main() {message = generateIntelligentResponse(lastUserQuery, taskResult, completedText);voiceId = VOICES[agentType.toLowerCase()] || VOICES.kai;- console.error(`🎯 AGENT INTELLIGENT: ${message}`);+ console.error(`🎯 AGENT INTELLIGENT (fallback): ${message}`);}}+ }++ // FIRST: Send voice notification if we have a message+ if (message) {+ // Send to voice server+ await fetch('http://localhost:8888/notify', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ message: message, // Changed from 'text' to 'message' to match server expectation+ voice_id: voiceId // Changed from 'voiceId' to 'voice_id' to match server expectation+ })+ }).catch(() => {});+ console.error(`🔊 Voice notification sent: "${message}" with voice: ${voiceId}`);+ }++ // LAST: Set the Kitty tab title with a 4-word summary of what was done+ let completedText = '';+ // Extract completed text for better summary+ if (isAgentTask && taskResult) {+ const completedMatch = taskResult.match(/🎯\s*COMPLETED:\s*(.+?)$/im);+ if (completedMatch) {+ completedText = completedMatch[1].trim();+ }} else {- // I (KAI) DID THE TASK - Look for my CUSTOM COMPLETED or COMPLETED line+ // Try to get completed text from Kai's responseconst lastResponse = lines[lines.length - 1];try {const entry = JSON.parse(lastResponse);if (entry.type === 'assistant' && entry.message?.content) {const content = entry.message.content.map(c => c.text || '').join(' ');-- // First, look for CUSTOM COMPLETED line (voice-optimized)- const customCompletedMatch = content.match(/🗣️\s*CUSTOM\s+COMPLETED:\s*(.+?)(?:\n|$)/im);-- if (customCompletedMatch) {- // Get the custom voice response- let customText = customCompletedMatch[1].trim()- .replace(/\[.*?\]/g, '') // Remove bracketed text like [Optional: ...]- .replace(/\*+/g, '') // Remove asterisks- .trim();-- // Use custom completed if it's under 8 words- const wordCount = customText.split(/\s+/).length;- if (customText && wordCount <= 8) {- message = customText;- console.error(`🗣️ CUSTOM VOICE: ${message}`);- } else {- // Custom completed too long, fall back to regular COMPLETED- const completedMatch = content.match(/🎯\s*COMPLETED:\s*(.+?)(?:\n|$)/im);- if (completedMatch) {- let completedText = completedMatch[1].trim();- message = generateIntelligentResponse(lastUserQuery, content, completedText);- console.error(`🎯 KAI FALLBACK (custom too long): ${message}`);- }- }- } else {- // No CUSTOM COMPLETED, look for regular COMPLETED line- const completedMatch = content.match(/🎯\s*COMPLETED:\s*(.+?)(?:\n|$)/im);-- if (completedMatch) {- // Get the raw text after the colon- let completedText = completedMatch[1].trim();-- // Generate intelligent response- message = generateIntelligentResponse(lastUserQuery, content, completedText);-- console.error(`🎯 KAI INTELLIGENT: ${message}`);- } else {- // No COMPLETED line found - don't send anything- console.error('⚠️ No COMPLETED line found');- }+ const completedMatch = content.match(/🎯\s*COMPLETED:\s*(.+?)(?:\n|$)/im);+ if (completedMatch) {+ completedText = completedMatch[1].trim();}}} catch (e) {- console.error('⚠️ Error parsing response:', e);+ // Ignore parse errors}}- // Set the Kitty tab title based on the user query- if (lastUserQuery) {- const tabTitle = generateTabTitle(lastUserQuery);- setKittyTabTitle(tabTitle);- // Debug log to confirm hook execution- console.error(`🏷️ Tab title set to: ${tabTitle}`);- } else {- console.error('⚠️ No user query found for tab title');- }+ // ALWAYS set a tab title - even if we don't have a query, make something up+ const tabTitle = lastUserQuery+ ? generateTabTitle(lastUserQuery, completedText)+ : 'Task Completed Successfully Done';- if (message) {- // Send to voice server- await fetch('http://localhost:8888/notify', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- message: message, // Changed from 'text' to 'message' to match server expectation- voice_id: voiceId // Changed from 'voiceId' to 'voice_id' to match server expectation- })- }).catch(() => {});+ console.error(`📝 User query: ${lastUserQuery || 'No query found'}`);+ console.error(`✅ Completed: ${completedText || 'No completed text found'}`);++ // Do tab title update LAST as requested+ try {+ setTerminalTabTitle(tabTitle);+ console.error(`\n🏷️ STOP-HOOK SUCCESS: Tab title set to: "${tabTitle}"`);+ } catch (e) {+ console.error(`❌ Failed to set tab title: ${e}`);}++ console.error(`🎬 STOP-HOOK COMPLETED SUCCESSFULLY at ${new Date().toISOString()}\n`);}main().catch(() => {});\ No newline at end of filediff --git a/.claude/hooks/subagent-stop-hook.ts b/.claude/hooks/subagent-stop-hook.tsindex 3d155a8a..852a10c3 100755--- a/.claude/hooks/subagent-stop-hook.ts+++ b/.claude/hooks/subagent-stop-hook.ts@@ -10,83 +10,17 @@ const AGENT_VOICE_IDS: Record<string, string> = {designer: 'ZF6FPAbjXT4488VcRRnw',architect: 'muZKMsIDGYtIkjjiUS82',writer: 'gfRt6Z3Z8aTbpLfexQ7N',- assistant: 'jqcCZkN6Knx8BJ5TBdYR', // Default assistant voice+ kai: 'jqcCZkN6Knx8BJ5TBdYR',default: 'jqcCZkN6Knx8BJ5TBdYR'};-// Intelligent response generator - prioritizes custom COMPLETED messages-function generateIntelligentResponse(userQuery: string, assistantResponse: string, completedLine: string): string {- // Clean the completed line- const cleanCompleted = completedLine- .replace(/\*+/g, '')- .replace(/\[AGENT:\w+\]\s*/i, '')- .trim();-- // If the completed line has meaningful custom content (not generic), use it- const genericPhrases = [- 'completed successfully',- 'task completed',- 'done successfully',- 'finished successfully',- 'completed the task',- 'completed your request',- 'the requested task'- ];-- const isGenericCompleted = genericPhrases.some(phrase =>- cleanCompleted.toLowerCase() === phrase ||- cleanCompleted.toLowerCase() === `${phrase}.`- );-- // If we have a custom, non-generic completed message, prefer it- if (!isGenericCompleted && cleanCompleted.length > 10) {- return cleanCompleted;- }-- // Extract key information from the full response- const responseLC = assistantResponse.toLowerCase();- const queryLC = userQuery.toLowerCase();-- // Only apply shortcuts for very specific simple cases-- // Simple thanks acknowledgment - high priority- if (queryLC.match(/^(thank|thanks|awesome|great|good job|well done)[\s!?.]*$/i)) {- return "You're welcome!";- }-- // Simple math calculations - ONLY if it's just a calculation- if (queryLC.match(/^\s*\d+\s*[\+\-\*\/]\s*\d+\s*\??$/)) {- const resultMatch = assistantResponse.match(/=\s*(-?\d+(?:\.\d+)?)|(?:equals?|is)\s+(-?\d+(?:\.\d+)?)/i);- if (resultMatch) {- return resultMatch[1] || resultMatch[2];- }- }-- // Very simple yes/no - ONLY if the query is extremely simple- if (queryLC.match(/^(is|are|was|were)\s+\w+\s+\w+\??$/i)) {- if (cleanCompleted.toLowerCase() === 'yes' || cleanCompleted.toLowerCase() === 'no') {- return cleanCompleted;- }- }-- // Simple time query - ONLY if asking for just the time- if (queryLC.match(/^what\s+time\s+is\s+it\??$/i)) {- const timeMatch = assistantResponse.match(/\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM)?/i);- if (timeMatch) {- return timeMatch[0];- }- }-- // For all other cases, use the actual completed message- // This ensures custom messages are preserved- return cleanCompleted;-}-async function delay(ms: number): Promise<void> {return new Promise(resolve => setTimeout(resolve, ms));}-async function findTaskResult(transcriptPath: string, maxAttempts: number = 10): Promise<{ result: string | null, agentType: string | null, userQuery: string | null }> {+async function findTaskResult(transcriptPath: string, maxAttempts: number = 10): Promise<{ result: string | null, agentType: string | null }> {+ console.error(`📂 Looking for Task result in transcript: ${transcriptPath}`);+for (let attempt = 0; attempt < maxAttempts; attempt++) {if (attempt > 0) {// Wait progressively longer between attempts@@ -94,48 +28,24 @@ async function findTaskResult(transcriptPath: string, maxAttempts: number = 10):}if (!existsSync(transcriptPath)) {+ console.error(`❌ Transcript file doesn't exist yet (attempt ${attempt + 1}/${maxAttempts})`);continue;}try {const transcript = readFileSync(transcriptPath, 'utf-8');const lines = transcript.trim().split('\n');-- // First, find the last user query- let lastUserQuery = '';++ // Search from the end of the transcript backwardsfor (let i = lines.length - 1; i >= 0; i--) {try {const entry = JSON.parse(lines[i]);- if (entry.type === 'user' && entry.message?.content) {- // Extract text from user message- const content = entry.message.content;- if (typeof content === 'string') {- lastUserQuery = content;- break;- } else if (Array.isArray(content)) {- for (const item of content) {- if (item.type === 'text' && item.text) {- lastUserQuery = item.text;- break;- }- }- if (lastUserQuery) break;- }- }- } catch (e) {- // Skip invalid JSON- }- }-- // Search from the end of the transcript backwards for Task result- for (let i = lines.length - 1; i >= 0; i--) {- try {- const entry = JSON.parse(lines[i]);-+// Look for assistant messages that contain Task tool_useif (entry.type === 'assistant' && entry.message?.content) {for (const content of entry.message.content) {if (content.type === 'tool_use' && content.name === 'Task') {+ console.error(`✅ Found Task invocation with subagent: ${content.input?.subagent_type}`);// Found a Task invocation, now look for its result// The result should be in a subsequent user messagefor (let j = i + 1; j < lines.length; j++) {@@ -145,15 +55,15 @@ async function findTaskResult(transcriptPath: string, maxAttempts: number = 10):if (resultContent.type === 'tool_result' && resultContent.tool_use_id === content.id) {// Found the matching Task resultconst taskOutput = resultContent.content;-- // Extract agent type from the input or output- let agentType = content.input?.subagent_type || 'default';++ // Extract agent type from the output+ let agentType = 'default';const agentMatch = taskOutput.match(/Sub-agent\s+(\w+)\s+completed/i);if (agentMatch) {agentType = agentMatch[1].toLowerCase();}-- return { result: taskOutput, agentType, userQuery: lastUserQuery };++ return { result: taskOutput, agentType };}}}@@ -169,37 +79,50 @@ async function findTaskResult(transcriptPath: string, maxAttempts: number = 10):// Error reading file, will retry}}-- return { result: null, agentType: null, userQuery: null };++ return { result: null, agentType: null };}-function extractCompletionMessage(taskOutput: string, userQuery: string | null): { message: string | null, agentType: string | null } {+function extractCompletionMessage(taskOutput: string): { message: string | null, agentType: string | null } {console.error('🔍 DEBUG - Extracting from task output, length:', taskOutput.length);console.error('🔍 DEBUG - First 200 chars:', taskOutput.substring(0, 200));console.error('🔍 DEBUG - Last 200 chars:', taskOutput.substring(taskOutput.length - 200));- // First, check for CUSTOM COMPLETED line (voice-optimized)- const customCompletedMatch = taskOutput.match(/🗣️\s*CUSTOM\s+COMPLETED:\s*(.+?)(?:\n|$)/im);+ // First, check for CUSTOM COMPLETED line (voice-optimized) - with or without emoji+ const customCompletedMatch = taskOutput.match(/(?:🗣️\s*)?(?:\*+)?CUSTOM\s+COMPLETED:\s*(?:\*+)?\s*(.+?)(?:\n|$)/im);if (customCompletedMatch) {// Get the custom voice responselet customText = customCompletedMatch[1].trim().replace(/\[.*?\]/g, '') // Remove bracketed text like [Optional: ...].replace(/\*+/g, '') // Remove asterisks- .replace(/\[AGENT:\w+\]\s*/i, '') // Remove agent tags.trim();// Use custom completed if it's under 8 wordsconst wordCount = customText.split(/\s+/).length;if (customText && wordCount <= 8) {- // Try to extract agent type from context+ // Try to extract agent type from the full outputlet agentType = null;- const agentMatch = taskOutput.match(/\[AGENT:(\w+)\]/i);- if (agentMatch) {- agentType = agentMatch[1].toLowerCase();++ // Look for agent type in various formats+ const agentTypePatterns = [+ /\[AGENT:(\w+)\]/i,+ /Sub-agent\s+(\w+)\s+completed/i,+ /(\w+)\s+Agent\s+completed/i,+ /🎯\s*COMPLETED:\s*\[AGENT:(\w+)\]/i+ ];++ for (const pattern of agentTypePatterns) {+ const match = taskOutput.match(pattern);+ if (match) {+ agentType = match[1].toLowerCase();+ break;+ }}- console.error(`🗣️ FOUND CUSTOM COMPLETED: ${customText}`);+ console.error(`🗣️ FOUND CUSTOM COMPLETED: ${customText} [Agent: ${agentType || 'unknown'}]`);++ // Don't prepend agent name if custom text already sounds completereturn { message: customText, agentType };}}@@ -207,41 +130,45 @@ function extractCompletionMessage(taskOutput: string, userQuery: string | null):// Look for the COMPLETED section in the agent's output// Priority is given to [AGENT:type] formatconst agentPatterns = [- /🎯\s*COMPLETED:\s*\[AGENT:(\w+)\]\s*(.+?)(?:\n|$)/is,- /COMPLETED:\s*\[AGENT:(\w+)\]\s*(.+?)(?:\n|$)/is,+ // Handle markdown formatting with asterisks+ /\*+🎯\s*COMPLETED:\*+\s*\[AGENT:(\w+)\]\s*I\s+completed\s+(.+?)(?:\n|$)/is,+ /\*+🎯\s+COMPLETED:\*+\s*\[AGENT:(\w+)\]\s*I\s+completed\s+(.+?)(?:\n|$)/is,+ // Non-markdown patterns+ /🎯\s*COMPLETED:\s*\[AGENT:(\w+)\]\s*I\s+completed\s+(.+?)(?:\n|$)/is,+ /COMPLETED:\s*\[AGENT:(\w+)\]\s*I\s+completed\s+(.+?)(?:\n|$)/is,/\[AGENT:(\w+)\]\s*I\s+completed\s+(.+?)(?:\.|!|\n|$)/is,- // New pattern for our current format+ // Generic pattern for current format/🎯.*COMPLETED.*\[AGENT:(\w+)\]\s*I\s+completed\s+(.+?)(?:\n|$)/is];// First try to match agent-specific patternsfor (const pattern of agentPatterns) {const match = taskOutput.match(pattern);- if (match && match[1]) {+ if (match && match[1] && match[2]) {const agentType = match[1].toLowerCase();- let message = match[2] || (match[0].split('COMPLETED:')[1] || '').trim();+ let message = match[2].trim();// Clean up the message- message = message- .replace(/\*+/g, '')- .replace(/\[AGENT:\w+\]\s*/i, '')- .replace(/\s+/g, ' ')- .trim();+ message = message.replace(/\*+/g, '');+ message = message.replace(/\s+/g, ' ');- // Use intelligent response if we have the user query- if (userQuery) {- message = generateIntelligentResponse(userQuery, taskOutput, message);- }+ // Prepend agent name for spoken message+ const agentName = agentType.charAt(0).toUpperCase() + agentType.slice(1);+ const fullMessage = `${agentName} completed ${message}`;- console.error(`✅ FOUND AGENT MATCH: [${agentType}] ${message}`);+ console.error(`✅ FOUND AGENT MATCH: [${agentType}] ${fullMessage}`);// Return agent type and message- return { message, agentType };+ return { message: fullMessage, agentType };}}- // Fall back to generic patterns+ // Fall back to generic patterns but try to extract agent typeconst genericPatterns = [+ // Handle markdown formatting+ /\*+🎯\s*COMPLETED:\*+\s*(.+?)(?:\n|$)/i,+ /\*+COMPLETED:\*+\s*(.+?)(?:\n|$)/i,+ // Non-markdown patterns/🎯\s*COMPLETED:\s*(.+?)(?:\n|$)/i,/COMPLETED:\s*(.+?)(?:\n|$)/i,/Sub-agent\s+\w+\s+completed\s+(.+?)(?:\.|!|\n|$)/i,@@ -254,24 +181,24 @@ function extractCompletionMessage(taskOutput: string, userQuery: string | null):let message = match[1].trim();// Clean up the message- message = message- .replace(/^(the\s+)?requested\s+task$/i, '')- .replace(/\*+/g, '')- .replace(/\[AGENT:\w+\]\s*/i, '')- .replace(/\s+/g, ' ')- .trim();-- // Use intelligent response if we have the user query- if (userQuery && message) {- message = generateIntelligentResponse(userQuery, taskOutput, message);- }+ message = message.replace(/^(the\s+)?requested\s+task$/i, '');+ message = message.replace(/\*+/g, '');+ message = message.replace(/\s+/g, ' ');// Only return if it's not a generic messageif (message &&!message.match(/^(the\s+)?requested\s+task$/i) &&!message.match(/^task$/i) &&message.length > 5) {- return { message, agentType: null };++ // Try to detect agent type from context+ let agentType = null;+ const agentMatch = taskOutput.match(/Sub-agent\s+(\w+)\s+completed/i);+ if (agentMatch) {+ agentType = agentMatch[1].toLowerCase();+ }++ return { message, agentType };}}}@@ -286,11 +213,11 @@ async function main() {try {const decoder = new TextDecoder();const reader = Bun.stdin.stream().getReader();-+const timeoutPromise = new Promise<void>((resolve) => {setTimeout(() => resolve(), 500);});-+const readPromise = (async () => {while (true) {const { done, value } = await reader.read();@@ -298,18 +225,18 @@ async function main() {input += decoder.decode(value, { stream: true });}})();-+await Promise.race([readPromise, timeoutPromise]);} catch (e) {console.error('Failed to read input:', e);process.exit(0);}-+if (!input) {console.log('No input received');process.exit(0);}-+let transcriptPath: string;try {const parsed = JSON.parse(input);@@ -318,32 +245,35 @@ async function main() {console.error('Invalid input JSON:', e);process.exit(0);}-+if (!transcriptPath) {console.log('No transcript path provided');process.exit(0);}-+// Wait for and find the Task result- const { result: taskOutput, agentType, userQuery } = await findTaskResult(transcriptPath);-+ const { result: taskOutput, agentType } = await findTaskResult(transcriptPath);+if (!taskOutput) {console.log('No Task result found in transcript after waiting');process.exit(0);}-+// Extract the completion message and agent type- const { message: completionMessage, agentType: extractedAgentType } = extractCompletionMessage(taskOutput, userQuery);-+ const { message: completionMessage, agentType: extractedAgentType } = extractCompletionMessage(taskOutput);+if (!completionMessage) {console.log('No specific completion message found in Task output');process.exit(0);}-+// Use extracted agent type if available, otherwise use the one from task analysisconst finalAgentType = extractedAgentType || agentType || 'default';++ // Prepare the notification+ const fullMessage = completionMessage; // Message is already prepared with agent nameconst agentName = finalAgentType.charAt(0).toUpperCase() + finalAgentType.slice(1);-+// Send to notification servertry {await fetch('http://localhost:8888/notify', {@@ -351,14 +281,14 @@ async function main() {headers: { 'Content-Type': 'application/json' },body: JSON.stringify({title: `${agentName} Agent`,- message: completionMessage,+ message: fullMessage,voice_enabled: true,agent_type: finalAgentType,voice_id: AGENT_VOICE_IDS[finalAgentType] || AGENT_VOICE_IDS.default})});-- console.log(`✅ Sent: [${agentName}] ${completionMessage}`);++ console.log(`✅ Sent: [${agentName}] ${fullMessage}`);} catch (e) {console.error('Failed to send notification:', e);}diff --git a/.claude/hooks/user-prompt-submit-hook.ts b/.claude/hooks/user-prompt-submit-hook.tsindex 68592a23..4d76fb41 100755--- a/.claude/hooks/user-prompt-submit-hook.ts+++ b/.claude/hooks/user-prompt-submit-hook.ts@@ -1,8 +1,8 @@#!/usr/bin/env bun/**- * User Prompt Submit Hook - Voice greeting when assistant starts working- * Triggered when user submits a request and assistant begins processing- * Announces when assistant is starting work on the task+ * User Prompt Submit Hook - Voice greeting when Kai starts working+ * Triggered when user submits a request and Kai begins processing+ * Announces when Kai is starting work on the task*/interface NotificationPayload {@@ -27,27 +27,27 @@ interface HookInput {function generateTaskSummary(prompt: string): string {// Clean and extract meaningful words from the promptconst cleanPrompt = prompt.replace(/[^\w\s]/g, ' ').trim();- const words = cleanPrompt.split(/\s+/).filter(word =>- word.length > 2 &&+ const words = cleanPrompt.split(/\s+/).filter(word =>+ word.length > 2 &&!['the', 'and', 'but', 'for', 'are', 'with', 'his', 'her', 'this', 'that', 'you', 'can', 'will', 'have', 'been', 'your', 'from', 'they', 'were', 'said', 'what', 'them', 'just', 'told', 'said'].includes(word.toLowerCase()));-+const lowerPrompt = prompt.toLowerCase();-+// Dynamic extraction based on actual contentlet actionWord = '';let subjectWords = [];-+// Find the primary action verb from the actual promptconst actionVerbs = ['fix', 'debug', 'research', 'write', 'create', 'make', 'build', 'implement', 'analyze', 'review', 'update', 'modify', 'generate', 'develop', 'design', 'test', 'deploy', 'configure', 'setup', 'install', 'remove', 'delete', 'add', 'check', 'verify', 'validate', 'optimize', 'refactor', 'enhance', 'improve', 'send', 'email', 'help'];-+for (const verb of actionVerbs) {if (lowerPrompt.includes(verb)) {actionWord = verb;break;}}-+// If no specific action found, infer from contextif (!actionWord) {if (lowerPrompt.includes('hook') || lowerPrompt.includes('static') || lowerPrompt.includes('dynamic')) {@@ -71,42 +71,42 @@ function generateTaskSummary(prompt: string): string {actionWord = actionWord + 'ing';}}-+// Extract key subject matter (skip common words, focus on nouns/topics)- const skipWords = ['user', 'prompt', 'thing', 'says', 'responding', 'greeting', 'properly', 'interpreting', 'section', 'those', 'things', 'some', 'that', 'have', 'your', 'need', 'dynamically', 'respond', 'describing', 'exactly', 'doing', 'basically', 'words', 'static', 'line', 'told', 'just'];-- subjectWords = words.filter(word =>+ const skipWords = ['user', 'prompt', 'thing', 'says', 'responding', 'greeting', 'properly', 'interpreting', 'section', 'those', 'things', 'some', 'that', 'have', 'your', 'need', 'dynamically', 'respond', 'describing', 'exactly', 'doing', 'basically', 'words', 'static', 'fucking', 'line', 'told', 'just'];++ subjectWords = words.filter(word =>!actionVerbs.includes(word.toLowerCase()) &&!skipWords.includes(word.toLowerCase()) &&!word.toLowerCase().includes(actionWord.replace('ing', '')) &&word.length > 2).slice(0, 3);-+// Build the dynamic summarylet summary = actionWord;-+// Add the most relevant subject wordsfor (const word of subjectWords.slice(0, 3)) {summary += ' ' + word.toLowerCase();}-+// If we don't have enough specific words, extract more aggressivelyif (subjectWords.length === 0) {const fallbackWords = prompt.split(/\s+/)- .filter(word =>- word.length > 3 &&- !/^(the|and|but|for|are|with|his|her|this|that|you|can|will|have|been|your|from|they|were|said|what|them|some|those|thing|says|just|told)$/i.test(word)+ .filter(word =>+ word.length > 3 &&+ !/^(the|and|but|for|are|with|his|her|this|that|you|can|will|have|been|your|from|they|were|said|what|them|some|those|thing|says|just|told|fucking)$/i.test(word)).slice(0, 3);-+for (const word of fallbackWords) {summary += ' ' + word.toLowerCase();}}-+// Clean up the summarysummary = summary.replace(/\s+/g, ' ').trim();-+// Make it conversational by adding "for you" or similarif (!summary.includes('for you') && !summary.includes('that') && !summary.includes('this')) {if (subjectWords.length > 0) {@@ -115,13 +115,18 @@ function generateTaskSummary(prompt: string): string {summary += ' that for you';}}-+return summary;}+// DISABLED: Tab title setting moved to stop-hook.ts only+// This prevents conflicts and ensures tab titles reflect completed work+// rather than what was requested+/*/*** Generate 3-word tab title from user prompt*/+/*function generateTabTitle(prompt: string): string {// Clean the prompt and extract meaningful wordsconst cleanPrompt = prompt.replace(/[^\w\s]/g, ' ').trim();@@ -161,7 +166,7 @@ function generateTabTitle(prompt: string): string {// If we don't have enough words, add generic onesif (titleWords.length === 0) {- titleWords.push('Assistant');+ titleWords.push('Kai');}if (titleWords.length === 1) {titleWords.push('Task');@@ -172,17 +177,21 @@ function generateTabTitle(prompt: string): string {return titleWords.slice(0, 3).join(' ');}+*/+/*/*** Set Kitty terminal tab title*/+/*function setKittyTabTitle(title: string): void {// Use OSC escape sequence to set tab/window titleprocess.stdout.write(`\x1b]0;${title}\x07`);}+*//**- * Generate greeting phrase for when assistant starts working+ * Generate greeting phrase for when Kai starts working*/function generateVoiceGreeting(): string {const greetings = [@@ -202,7 +211,7 @@ function generateVoiceGreeting(): string {}/**- * Send notification to the notification server+ * Send notification to the Kai notification server*/async function sendNotification(payload: NotificationPayload): Promise<void> {try {@@ -211,7 +220,7 @@ async function sendNotification(payload: NotificationPayload): Promise<void> {headers: { 'Content-Type': 'application/json' },body: JSON.stringify(payload),});-+if (!response.ok) {console.error('Notification server error:', response.statusText);}@@ -229,16 +238,16 @@ async function readStdinWithTimeout(timeout: number = 5000): Promise<string> {const timer = setTimeout(() => {reject(new Error('Timeout reading from stdin'));}, timeout);-+process.stdin.on('data', (chunk) => {data += chunk.toString();});-+process.stdin.on('end', () => {clearTimeout(timer);resolve(data);});-+process.stdin.on('error', (err) => {clearTimeout(timer);reject(err);@@ -251,9 +260,10 @@ async function main() {const input = await readStdinWithTimeout();const data: HookInput = JSON.parse(input);- // Generate 3-word tab title and set it in Kitty- const tabTitle = generateTabTitle(data.prompt);- setKittyTabTitle(tabTitle);+ // DISABLED: Tab title setting moved to stop-hook.ts only+ // This prevents conflicts with stop-hook and ensures titles reflect completed work+ // const tabTitle = generateTabTitle(data.prompt);+ // setKittyTabTitle(tabTitle);// DISABLED: Immediate voice notification causes janky experience// Voice feedback should come from completion hooks instead@@ -264,13 +274,13 @@ async function main() {// const taskSummary = generateTaskSummary(data.prompt);// const fullMessage = `${greeting}, ${taskSummary}`;- // COMMENTED OUT: Send notification with assistant's voice+ // COMMENTED OUT: Send notification with Kai's voice// const payload: NotificationPayload = {- // title: 'Assistant',+ // title: 'Kai',// message: fullMessage,// voice_enabled: true,// priority: 'low',- // voice_id: 'YOUR_VOICE_ID_HERE' // Replace with your assistant's voice ID+ // voice_id: 'jqcCZkN6Knx8BJ5TBdYR' // Kai's main voice ID// };// await sendNotification(payload);