⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
feat: Add Kitty tab renaming and intelligent voice responses to hooks
Daniel Miessler71e023e2091a
diff --git a/.claude/hooks/stop-hook.ts b/.claude/hooks/stop-hook.tsindex 4d874f80..94d9209b 100755--- a/.claude/hooks/stop-hook.ts+++ b/.claude/hooks/stop-hook.ts@@ -2,25 +2,152 @@import { readFileSync } from 'fs';+/**+ * Generate 3-word tab title from user prompt+ */+function generateTabTitle(prompt: string): string {+ // Clean the prompt and extract meaningful words+ const cleanPrompt = prompt.replace(/[^\w\s]/g, ' ').trim();+ 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', 'how', 'does', 'into', 'about'].includes(word.toLowerCase())+ );++ 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'];++ let titleWords = [];++ // Check for action verb+ for (const verb of actionVerbs) {+ if (lowerPrompt.includes(verb)) {+ titleWords.push(verb.charAt(0).toUpperCase() + verb.slice(1));+ break;+ }+ }++ // Add most meaningful remaining words+ const remainingWords = words+ .filter(word => !actionVerbs.includes(word.toLowerCase()))+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());++ // Fill up to 3 words total+ for (const word of remainingWords) {+ if (titleWords.length < 3) {+ titleWords.push(word);+ } else {+ break;+ }+ }++ // If we don't have enough words, add generic ones+ if (titleWords.length === 0) {+ titleWords.push('Assistant');+ }+ if (titleWords.length === 1) {+ titleWords.push('Task');+ }+ if (titleWords.length === 2) {+ titleWords.push('Complete');+ }++ return titleWords.slice(0, 3).join(' ');+}++/**+ * Set Kitty terminal tab title+ */+function setKittyTabTitle(title: string): void {+ // Use OSC escape sequence to set tab/window title with checkmark+ process.stdout.write(`\x1b]0;✓ ${title}\x07`);+}+// Simple voice mappingsconst VOICES = {researcher: 'AXdMgz6evoL7OPd7eU12',- pentester: 'hmMWXCj9K7N5mCPcRkfC',+ pentester: 'hmMWXCj9K7N5mCPcRkfC',engineer: 'kmSVBPu7loj4ayNinwWM',designer: 'ZF6FPAbjXT4488VcRRnw',architect: 'muZKMsIDGYtIkjjiUS82',writer: 'gfRt6Z3Z8aTbpLfexQ7N',- kai: 'jqcCZkN6Knx8BJ5TBdYR'+ assistant: 'jqcCZkN6Knx8BJ5TBdYR' // Default assistant voice};-// Removed summarizeTask function - no longer needed+// 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'+ ];++ 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 main() {// Get inputlet input = '';const decoder = new TextDecoder();const reader = Bun.stdin.stream().getReader();-+try {while (true) {const { done, value } = await reader.read();@@ -32,7 +159,7 @@ async function main() {}if (!input) process.exit(0);-+let transcriptPath;try {const parsed = JSON.parse(input);@@ -54,6 +181,31 @@ async function main() {// Parse the JSON lines to find what happened in this sessionconst lines = transcript.trim().split('\n');+ // Get the last user query for context+ let lastUserQuery = '';+ for (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;+ } 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+ }+ }+// First, check if the LAST assistant message contains a Task tool or a COMPLETED linelet isAgentTask = false;let taskResult = '';@@ -101,56 +253,111 @@ async function main() {// Generate the announcementlet message = '';- let voiceId = VOICES.kai; // Default to Kai's voice+ let voiceId = VOICES.assistant; // Default to assistant's voiceif (isAgentTask && taskResult) {- // AGENT DID THE TASK - Look for their COMPLETED line- const completedMatch = taskResult.match(/🎯\s*COMPLETED:\s*(.+?)$/im);+ // AGENT DID THE TASK - Look for their CUSTOM COMPLETED or COMPLETED line- if (completedMatch) {- // Get exactly what the agent said after COMPLETED:- let completedText = completedMatch[1].trim();+ // First, try to find CUSTOM COMPLETED line+ const customCompletedMatch = taskResult.match(/🗣️\s*CUSTOM\s+COMPLETED:\s*(.+?)(?:\n|$)/im);- // Remove markdown formatting- completedText = completedText- .replace(/\*+/g, '') // Remove asterisks+ if (customCompletedMatch) {+ // Get the custom voice response+ let customText = customCompletedMatch[1].trim()+ .replace(/\[.*?\]/g, '') // Remove bracketed text+ .replace(/\*+/g, '') // Remove asterisks.replace(/\[AGENT:\w+\]\s*/i, '') // Remove agent tags.trim();- // Send exactly what was in the agent's COMPLETED line- message = completedText;- voiceId = VOICES[agentType.toLowerCase()] || VOICES.kai;+ // Use custom completed if it's under 8 words+ const wordCount = customText.split(/\s+/).length;+ if (customText && wordCount <= 8) {+ message = customText;+ voiceId = VOICES[agentType.toLowerCase()] || VOICES.assistant;+ console.error(`🗣️ AGENT CUSTOM VOICE: ${message}`);+ } else {+ // Custom completed too long, fall back to regular COMPLETED+ const completedMatch = taskResult.match(/🎯\s*COMPLETED:\s*(.+?)$/im);+ if (completedMatch) {+ let completedText = completedMatch[1].trim()+ .replace(/\*+/g, '')+ .replace(/\[AGENT:\w+\]\s*/i, '')+ .trim();+ message = generateIntelligentResponse(lastUserQuery, taskResult, completedText);+ voiceId = VOICES[agentType.toLowerCase()] || VOICES.assistant;+ console.error(`🎯 AGENT FALLBACK (custom too long): ${message}`);+ }+ }+ } else {+ // No CUSTOM COMPLETED, look for regular COMPLETED line+ const completedMatch = taskResult.match(/🎯\s*COMPLETED:\s*(.+?)$/im);++ if (completedMatch) {+ // Get exactly what the agent said after COMPLETED:+ let completedText = completedMatch[1].trim();++ // Remove markdown formatting+ completedText = completedText+ .replace(/\*+/g, '') // Remove asterisks+ .replace(/\[AGENT:\w+\]\s*/i, '') // Remove agent tags+ .trim();++ // Generate intelligent response for agent tasks+ message = generateIntelligentResponse(lastUserQuery, taskResult, completedText);+ voiceId = VOICES[agentType.toLowerCase()] || VOICES.assistant;- console.error(`🎯 AGENT COMPLETION: ${message}`);+ console.error(`🎯 AGENT INTELLIGENT: ${message}`);+ }}} else {- // I (KAI) DID THE TASK - Look for my COMPLETED line+ // I (ASSISTANT) DID THE TASK - Look for my CUSTOM COMPLETED or COMPLETED lineconst 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(' ');- // Look for the COMPLETED line and extract EXACTLY what's after the colon- const completedMatch = content.match(/🎯\s*COMPLETED:\s*(.+?)$/im);-- if (completedMatch) {- // Get the raw text after the colon- let completedText = completedMatch[1].trim();+ // First, look for CUSTOM COMPLETED line (voice-optimized)+ const customCompletedMatch = content.match(/🗣️\s*CUSTOM\s+COMPLETED:\s*(.+?)(?:\n|$)/im);- // Remove any markdown formatting but keep the actual message- completedText = completedText- .replace(/\*+/g, '') // Remove asterisks+ if (customCompletedMatch) {+ // Get the custom voice response+ let customText = customCompletedMatch[1].trim()+ .replace(/\[.*?\]/g, '') // Remove bracketed text like [Optional: ...]+ .replace(/\*+/g, '') // Remove asterisks.trim();- // Send exactly what was in the COMPLETED line- message = completedText;-- console.error(`🎯 KAI COMPLETION: ${message}`);+ // 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(`🎯 ASSISTANT FALLBACK (custom too long): ${message}`);+ }+ }} else {- // No COMPLETED line found - don't send anything- console.error('⚠️ No COMPLETED line found');+ // 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(`🎯 ASSISTANT INTELLIGENT: ${message}`);+ } else {+ // No COMPLETED line found - don't send anything+ console.error('⚠️ No COMPLETED line found');+ }}}} catch (e) {@@ -158,6 +365,12 @@ async function main() {}}+ // Set the Kitty tab title based on the user query+ if (lastUserQuery) {+ const tabTitle = generateTabTitle(lastUserQuery);+ setKittyTabTitle(tabTitle);+ }+if (message) {// Send to voice serverawait fetch('http://localhost:8888/notify', {diff --git a/.claude/hooks/user-prompt-submit-hook.ts b/.claude/hooks/user-prompt-submit-hook.tsnew file mode 100755index 00000000..68592a23--- /dev/null+++ b/.claude/hooks/user-prompt-submit-hook.ts@@ -0,0 +1,285 @@+#!/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+ */++interface NotificationPayload {+ title: string;+ message: string;+ voice_enabled: boolean;+ priority?: 'low' | 'normal' | 'high';+ voice_id: string;+}++interface HookInput {+ session_id: string;+ prompt: string;+ transcript_path: string;+ hook_event_name: string;+}++/**+ * Generate conversational task summary from user prompt (action-oriented)+ * Dynamically extracts the actual task being requested+ */+function generateTaskSummary(prompt: string): string {+ // Clean and extract meaningful words from the prompt+ const cleanPrompt = prompt.replace(/[^\w\s]/g, ' ').trim();+ 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 content+ let actionWord = '';+ let subjectWords = [];++ // Find the primary action verb from the actual prompt+ const 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 context+ if (!actionWord) {+ if (lowerPrompt.includes('hook') || lowerPrompt.includes('static') || lowerPrompt.includes('dynamic')) {+ actionWord = 'fixing';+ } else if (lowerPrompt.includes('?')) {+ actionWord = 'answering';+ } else if (lowerPrompt.includes('greeting') || lowerPrompt.includes('hello') || lowerPrompt.includes('hi')) {+ actionWord = 'responding';+ } else {+ actionWord = 'handling';+ }+ } else {+ // Convert to progressive form for "I'm [verb]ing"+ if (actionWord.endsWith('e')) {+ actionWord = actionWord.slice(0, -1) + 'ing';+ } else if (actionWord === 'fix') {+ actionWord = 'fixing';+ } else if (actionWord === 'debug') {+ actionWord = 'debugging';+ } else if (!actionWord.endsWith('ing')) {+ 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 =>+ !actionVerbs.includes(word.toLowerCase()) &&+ !skipWords.includes(word.toLowerCase()) &&+ !word.toLowerCase().includes(actionWord.replace('ing', '')) &&+ word.length > 2+ ).slice(0, 3);++ // Build the dynamic summary+ let summary = actionWord;++ // Add the most relevant subject words+ for (const word of subjectWords.slice(0, 3)) {+ summary += ' ' + word.toLowerCase();+ }++ // If we don't have enough specific words, extract more aggressively+ if (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)+ )+ .slice(0, 3);++ for (const word of fallbackWords) {+ summary += ' ' + word.toLowerCase();+ }+ }++ // Clean up the summary+ summary = summary.replace(/\s+/g, ' ').trim();++ // Make it conversational by adding "for you" or similar+ if (!summary.includes('for you') && !summary.includes('that') && !summary.includes('this')) {+ if (subjectWords.length > 0) {+ summary += ' for you';+ } else {+ summary += ' that for you';+ }+ }++ return summary;+}++/**+ * Generate 3-word tab title from user prompt+ */+function generateTabTitle(prompt: string): string {+ // Clean the prompt and extract meaningful words+ const cleanPrompt = prompt.replace(/[^\w\s]/g, ' ').trim();+ 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', 'how', 'does', 'into', 'about'].includes(word.toLowerCase())+ );++ 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'];++ let titleWords = [];++ // Check for action verb+ for (const verb of actionVerbs) {+ if (lowerPrompt.includes(verb)) {+ titleWords.push(verb.charAt(0).toUpperCase() + verb.slice(1));+ break;+ }+ }++ // Add most meaningful remaining words+ const remainingWords = words+ .filter(word => !actionVerbs.includes(word.toLowerCase()))+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());++ // Fill up to 3 words total+ for (const word of remainingWords) {+ if (titleWords.length < 3) {+ titleWords.push(word);+ } else {+ break;+ }+ }++ // If we don't have enough words, add generic ones+ if (titleWords.length === 0) {+ titleWords.push('Assistant');+ }+ if (titleWords.length === 1) {+ titleWords.push('Task');+ }+ if (titleWords.length === 2) {+ titleWords.push('Active');+ }++ return titleWords.slice(0, 3).join(' ');+}++/**+ * Set Kitty terminal tab title+ */+function setKittyTabTitle(title: string): void {+ // Use OSC escape sequence to set tab/window title+ process.stdout.write(`\x1b]0;${title}\x07`);+}++/**+ * Generate greeting phrase for when assistant starts working+ */+function generateVoiceGreeting(): string {+ const greetings = [+ "Okay, I'm",+ "Sure thing, I'm",+ "Got it, I'm",+ "Alright, I'm",+ "On it, I'm",+ "Absolutely, I'm",+ "Right away, I'm",+ "Perfect, I'm",+ "Sounds good, I'm",+ "Will do, I'm"+ ];++ return greetings[Math.floor(Math.random() * greetings.length)];+}++/**+ * Send notification to the notification server+ */+async function sendNotification(payload: NotificationPayload): Promise<void> {+ try {+ const response = await fetch('http://localhost:8888/notify', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ });++ if (!response.ok) {+ console.error('Notification server error:', response.statusText);+ }+ } catch (error) {+ console.error('Failed to send notification:', error);+ }+}++/**+ * Read stdin with timeout+ */+async function readStdinWithTimeout(timeout: number = 5000): Promise<string> {+ return new Promise((resolve, reject) => {+ let data = '';+ 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);+ });+ });+}++async function main() {+ try {+ 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: Immediate voice notification causes janky experience+ // Voice feedback should come from completion hooks instead+ // This ensures clean, single voice notification after AI processing completes++ // Generate greeting with task summary (keeping for future use)+ // const greeting = generateVoiceGreeting();+ // const taskSummary = generateTaskSummary(data.prompt);+ // const fullMessage = `${greeting}, ${taskSummary}`;++ // COMMENTED OUT: Send notification with assistant's voice+ // const payload: NotificationPayload = {+ // title: 'Assistant',+ // message: fullMessage,+ // voice_enabled: true,+ // priority: 'low',+ // voice_id: 'YOUR_VOICE_ID_HERE' // Replace with your assistant's voice ID+ // };++ // await sendNotification(payload);++ process.exit(0);+ } catch (error) {+ console.error('UserPromptSubmit hook error:', error);+ process.exit(1);+ }+}++main();\ No newline at end of file