⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
chore: Remove remaining deprecated single-file pack formats
Daniel Miessler79715e19af46
diff --git a/Packs/kai-art-skill.md b/Packs/kai-art-skill.mddeleted file mode 100644index 24af8eff..00000000--- a/Packs/kai-art-skill.md+++ /dev/null@@ -1,1989 +0,0 @@-----name: Kai Art Skill-pack-id: danielmiessler-kai-art-skill-core-v1.1.0-version: 1.1.0-author: danielmiessler-description: Visual content generation with Excalidraw hand-drawn aesthetic - technical diagrams, comics, editorial illustrations-type: skill-purpose-type: [creativity, productivity, development]-platform: claude-code-dependencies: []-keywords: [art, visualization, diagrams, comics, excalidraw, hand-drawn, technical-diagrams, image-generation, illustrations, dark-mode]------<p align="center">- <img src="icons/kai-art-skill.png" alt="Kai Art Skill" width="256">-</p>--# Kai Art Skill--> Visual content generation system with Excalidraw hand-drawn aesthetic - technical diagrams, comics, and editorial illustrations with consistent dark-mode styling--## Installation Prompt--You are receiving a PAI Pack - a modular upgrade for AI agent systems.--**What is PAI?** See: [PAI Project Overview](../README.md#what-is-pai)--**What is a Pack?** See: [How PAI Packs Work](../README.md#-how-pai-packs-work)--This pack adds a complete visual content generation skill to your AI infrastructure. The Art Skill provides:--- **Technical Diagrams**: Clean Excalidraw-style architecture and process diagrams-- **Editorial Illustrations**: Header images and editorial art for blog posts-- **Comics**: Sequential panel storytelling with sophisticated editorial style-- **Consistent Aesthetic**: Dark-mode, tech-forward color palette with hand-drawn feel-- **CLI Tool**: Deterministic image generation with multiple AI model backends--**Core principle:** Consistent, professional visual content with zero manual design work.--The skill routes requests to specialized workflows that handle the prompt construction, model selection, and validation automatically.--Please follow the installation instructions below to integrate this pack into your infrastructure.-------## What's Included--| Component | File | Purpose |-|-----------|------|---------|-| Art skill | `skills/Art/SKILL.md` | Routing and quick reference |-| Aesthetic config | `skills/Art/Aesthetic.md` | Style preferences and palette |-| Generate tool | `skills/Art/Tools/Generate.ts` | Multi-model image generation CLI |-| Technical diagrams | `skills/Art/Workflows/TechnicalDiagrams.md` | Architecture diagram workflow |-| Essay headers | `skills/Art/Workflows/Essay.md` | Blog header image workflow |-| Comics workflow | `skills/Art/Workflows/Comics.md` | Sequential panel generation |--**Summary:**-- **Files created:** 8+ (skill, tool, workflows)-- **Hooks registered:** 0 (skill-based, not hook-based)-- **Dependencies:** kai-core-install (required), API keys for image models-------## The Concept and/or Problem--AI image generation is powerful but inconsistent. Each request requires:--1. **Prompt Engineering**: Figuring out what words produce the desired style-2. **Model Selection**: Choosing between Flux, DALL-E, Gemini, etc.-3. **Size/Format Decisions**: Aspect ratios, resolutions, file formats-4. **Post-Processing**: Background removal, thumbnails, optimization-5. **Style Consistency**: Making sure each image matches your brand--**The Problems:**--**Inconsistent Results:**-- Same prompt produces wildly different styles across sessions-- No visual language continuity between images-- Each request starts from scratch--**Prompt Overhead:**-- Remembering which phrases produce good results-- Re-discovering effective prompts each time-- No institutional knowledge about what works--**Technical Complexity:**-- Different models have different APIs and parameters-- Background removal requires additional tools-- Thumbnail generation needs manual intervention--**Quality Control:**-- No validation that output matches intent-- Easy to accept "good enough" when great is achievable-- No checklist for what makes an image complete--**The Result:**--Without a systematic approach, AI image generation becomes a time sink. You spend more time fighting the tools than creating content. Visual consistency across your work is impossible.-------## The Solution--The Art Skill solves this through **workflow-based generation**. Instead of raw prompts, you describe what you need and the skill:--1. **Routes** your request to the appropriate workflow (diagrams, essays, comics)-2. **Applies** a consistent aesthetic (Excalidraw hand-drawn, dark-mode colors)-3. **Constructs** an optimized prompt using proven templates-4. **Executes** with the right model, size, and post-processing-5. **Validates** the output against quality criteria--**Architecture:**--```-User Request ("create a diagram of the auth flow")- |- v-[SKILL.md Routing] ─── Routes based on request type- |- v-[Workflow] ─── TechnicalDiagrams.md / Essay.md / Comics.md- | - Aesthetic guidelines- | - Prompt template- | - Validation checklist- v-[Generate.ts CLI] ─── Deterministic image generation- | - Model selection- | - Size/aspect handling- | - Background removal- | - Thumbnail generation- v-[Output] ─── Validated image ready for use-```--**Key Innovations:**--1. **Aesthetic as Code**: The visual style is documented in Aesthetic.md - colors, typography, composition rules. This ensures every image uses the same visual language.--2. **Workflow Templates**: Each workflow (diagrams, essays, comics) has a proven prompt structure that consistently produces quality results.--3. **Intent-to-Flag Mapping**: User intent ("make it high quality", "create a thumbnail") maps to specific CLI flags. No guessing at parameters.--4. **Validation Checklists**: Each workflow includes must-have and must-not-have criteria. Regenerate until validation passes.--5. **CLI Determinism**: The Generate.ts tool wraps multiple AI models (Flux, Gemini, GPT) behind a consistent interface. Same flags, same behavior.-------## What Makes This Different--This sounds similar to using AI image generators directly, which also creates images from prompts. What makes this approach different?--The Art Skill treats image generation as a repeatable process, not a creative gamble. By encoding aesthetic decisions, prompt patterns, and quality criteria into structured workflows, you get consistent results without prompt engineering expertise. The skill separates WHAT you want (a technical diagram) from HOW to achieve it (specific prompts, models, and validation).--- Aesthetic consistency enforced through documented color and style guidelines-- Workflow templates eliminate prompt engineering for each request-- CLI tool provides deterministic, composable image generation-- Validation checklists ensure quality before accepting output-------## Installation--### Prerequisites--- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`-- **Claude Code** (or compatible agent system with skill support)-- **Write access** to `$PAI_DIR/` (default: `~/.config/pai`)-- **API Keys in `$PAI_DIR/.env`** (at least one required):- - `REPLICATE_API_TOKEN` - For Flux and Nano Banana models- - `GOOGLE_API_KEY` - For Nano Banana Pro (Gemini 3) model- - `OPENAI_API_KEY` - For GPT-image-1 model- - `REMOVEBG_API_KEY` - For background removal feature--### Pre-Installation: System Analysis--**IMPORTANT:** Before installing, analyze the current system state.--#### Step 0.1: Detect Current Configuration--```bash-# 1. Check PAI_DIR-echo "PAI_DIR: ${PAI_DIR:-'NOT SET - will use ~/.config/pai'}"--# 2. Check for existing Skills directory-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"-if [ -d "$PAI_CHECK/skills/Art" ]; then- echo "WARNING: Art skill already exists at: $PAI_CHECK/skills/Art"- echo "Contents:"- ls -la "$PAI_CHECK/skills/Art" 2>/dev/null || echo " (empty)"-else- echo "OK: No existing Art skill (clean install)"-fi--# 3. Check for API keys-echo ""-echo "API Key Status:"-[ -n "$REPLICATE_API_TOKEN" ] && echo " REPLICATE_API_TOKEN: Set" || echo " REPLICATE_API_TOKEN: NOT SET"-[ -n "$GOOGLE_API_KEY" ] && echo " GOOGLE_API_KEY: Set" || echo " GOOGLE_API_KEY: NOT SET"-[ -n "$OPENAI_API_KEY" ] && echo " OPENAI_API_KEY: Set" || echo " OPENAI_API_KEY: NOT SET"-[ -n "$REMOVEBG_API_KEY" ] && echo " REMOVEBG_API_KEY: Set" || echo " REMOVEBG_API_KEY: NOT SET"-```--#### Step 0.2: Conflict Resolution Matrix--| Scenario | Existing State | Action |-|----------|---------------|--------|-| **Clean Install** | No Art skill exists | Proceed with Step 1 |-| **Skill Exists** | Art skill already present | Backup existing, then replace |-| **No API Keys** | Missing all API keys | Add at least one key to .env |--#### Step 0.3: Backup Existing Configuration (If Needed)--```bash-# Create timestamped backup if Art skill exists-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"-if [ -d "$PAI_CHECK/skills/Art" ]; then- BACKUP_DIR="$HOME/.pai-backup/$(date +%Y%m%d-%H%M%S)"- mkdir -p "$BACKUP_DIR"- cp -r "$PAI_CHECK/skills/Art" "$BACKUP_DIR/Art"- echo "Backed up existing Art skill to: $BACKUP_DIR/Art"-fi-```-------### Step 1: Create Directory Structure--```bash-PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"--# Create Art skill directories-mkdir -p "$PAI_DIR/skills/Art/Workflows"-mkdir -p "$PAI_DIR/skills/Art/Tools"--# Verify structure-echo "Created directories:"-ls -la "$PAI_DIR/skills/Art/"-```-------### Step 2: Create SKILL.md (Routing File)--```bash-cat > "$PAI_DIR/skills/Art/SKILL.md" << 'SKILL_EOF'-----name: Art-description: Visual content generation with Excalidraw hand-drawn aesthetic. USE WHEN user wants diagrams, visualizations, comics, or editorial illustrations.------# Art Skill--Visual content generation system using **Excalidraw hand-drawn** aesthetic with dark-mode, tech-forward color palette.--## Output Location--```-ALL GENERATED IMAGES GO TO ~/Downloads/ FIRST-Preview in Finder/Preview before final placement-Only copy to project directories after review-```--## Workflow Routing--Route to the appropriate workflow based on the request:-- - Technical or architecture diagram → `Workflows/TechnicalDiagrams.md`- - Blog header or editorial illustration → `Workflows/Essay.md`- - Comic or sequential panels → `Workflows/Comics.md`-------## Core Aesthetic--**Excalidraw Hand-Drawn** - Clean, approachable technical illustrations with:-- Slightly wobbly hand-drawn lines (NOT perfect vectors)-- Simple shapes with organic imperfections-- Consistent hand-lettered typography style-- Dark mode backgrounds with bright accents--**Full aesthetic documentation:** `$PAI_DIR/skills/Art/Aesthetic.md`-------## Color System--| Color | Hex | Usage |-|-------|-----|-------|-| Background | `#0a0a0f` | Primary dark background |-| PAI Blue | `#4a90d9` | Key elements, primary accents |-| Electric Cyan | `#22d3ee` | Flows, connections, secondary |-| Accent Purple | `#8b5cf6` | Highlights, callouts (10-15%) |-| Text White | `#e5e7eb` | Primary text, labels |-| Surface | `#1a1a2e` | Cards, panels |-| Line Work | `#94a3b8` | Hand-drawn borders |-------## Image Generation--**Default model:** nano-banana-pro (Gemini 3 Pro)--```bash-bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "[PROMPT]" \- --size 2K \- --aspect-ratio 16:9 \- --output ~/Downloads/output.png-```--**API keys in:** `$PAI_DIR/.env` (single source of truth for all authentication)-------## Examples--**Example 1: Technical diagram**-```-User: "create a diagram showing the auth flow"-→ Invokes TECHNICALDIAGRAMS workflow-→ Creates Excalidraw-style architecture visual-→ Outputs PNG with dark background, blue accents-```--**Example 2: Blog header**-```-User: "create a header for my post about AI agents"-→ Invokes ESSAY workflow-→ Generates hand-drawn illustration-→ Saves to ~/Downloads/ for preview-```--**Example 3: Comic strip**-```-User: "create a comic showing the before/after of using AI"-→ Invokes COMICS workflow-→ Creates 3-4 panel sequential narrative-→ Editorial style, not cartoonish-```-SKILL_EOF--echo "Created SKILL.md"-```-------### Step 3: Create Aesthetic.md (Color and Style Reference)--```bash-cat > "$PAI_DIR/skills/Art/Aesthetic.md" << 'AESTHETIC_EOF'-# Art Skill Aesthetic--**Excalidraw Hand-Drawn** - Tech-forward dark-mode aesthetic for professional visual content.-------## Core Style--**Visual Language:** Clean Excalidraw-style diagrams and illustrations-- Hand-drawn feel with slightly imperfect lines-- Organic, approachable, but professional-- Dark mode backgrounds with bright accent colors-- Whiteboard/sketch aesthetic--**Influences:**-- Excalidraw diagrams-- Technical whiteboard sketches-- Modern dark-mode UI design-- Architectural hand-drawings-------## Color Palette--### Primary Colors--| Color | Hex | RGB | Usage |-|-------|-----|-----|-------|-| **Background** | `#0a0a0f` | 10, 10, 15 | Primary dark background |-| **PAI Blue** | `#4a90d9` | 74, 144, 217 | Key elements, primary accents, main structures |-| **Electric Cyan** | `#22d3ee` | 34, 211, 238 | Flows, connections, secondary paths |-| **Accent Purple** | `#8b5cf6` | 139, 92, 246 | Highlights, insights, callouts (10-15% usage) |--### Text Colors--| Color | Hex | RGB | Usage |-|-------|-----|-----|-------|-| **Text White** | `#e5e7eb` | 229, 231, 235 | Primary text, labels |-| **Text Muted** | `#9ca3af` | 156, 163, 175 | Secondary text, annotations |--### Surface Colors--| Color | Hex | RGB | Usage |-|-------|-----|-----|-------|-| **Surface** | `#1a1a2e` | 26, 26, 46 | Cards, panels, elevated surfaces |-| **Line Work** | `#94a3b8` | 148, 163, 184 | Hand-drawn borders, sketch lines |--### Semantic Colors--| Color | Hex | Usage |-|-------|-----|-------|-| **Success** | `#22c55e` | Positive states, completion |-| **Warning** | `#f59e0b` | Caution, attention needed |-| **Error** | `#ef4444` | Errors, critical issues |-------## Color Usage Guidelines--### Ratios--- **Background**: 40-50% of image (dark backdrop)-- **Line Work**: 30-40% (hand-drawn elements in slate/white)-- **PAI Blue**: 15-20% (key components, primary accents)-- **Electric Cyan**: 5-10% (flows, connections)-- **Accent Purple**: 5-10% (highlights, callouts)--### Rules--1. **Dark dominates** - Background and line work make up majority-2. **Blue for structure** - Main components, boxes, important elements-3. **Cyan for flow** - Arrows, connections, data movement-4. **Purple sparingly** - Only for insights, callouts, emphasis-5. **White text always** - Never use dark text on dark background-------## Typography--### Tier 1: Headers (Valkyrie-style)-- Elegant serif with wedge-shaped serifs-- High stroke contrast-- Use for: Titles, section headers-- Color: White `#e5e7eb`--### Tier 2: Labels (Concourse-style)-- Geometric sans-serif-- Clean, technical, precise-- Use for: Box labels, node names, technical identifiers-- Color: White `#e5e7eb`--### Tier 3: Insights (Advocate-style)-- Condensed italic sans-serif-- Editorial, attention-grabbing-- Use for: Callouts, annotations, key insights-- Color: PAI Blue `#4a90d9` or Electric Cyan `#22d3ee`-------## Excalidraw Characteristics--### Line Quality-- **Slightly wobbly** - Not perfectly straight-- **Variable weight** - Thicker for emphasis, thinner for details-- **Organic joints** - Imperfect connections between shapes-- **Sketch quality** - Like someone drew it quickly but skillfully--### Shapes-- **Rounded corners** - Soft, not sharp-- **Imperfect rectangles** - Slightly uneven sides-- **Hand-drawn circles** - Not perfect ovals-- **Organic arrows** - Curved, not ruler-straight--### Overall Feel-- Would you believe someone drew this on a whiteboard?-- Professional but approachable-- Technical but not cold-- Modern dark-mode aesthetic-------## Emotional Registers--Use these to guide the tone of illustrations:--| Register | When to Use | Visual Treatment |-|----------|-------------|------------------|-| **Technical** | Architecture, systems, processes | Clean lines, structured layout |-| **Discovery** | Breakthroughs, new ideas | Light, open composition |-| **Warning** | Security, risks, caution | More contrast, warning colors |-| **Progress** | Before/after, improvements | Flow from left to right |-| **Complexity** | Many components, systems | Organized chaos, clear hierarchy |-| **Simplicity** | Single concepts, focus | Minimal elements, breathing space |-------## Validation Checklist--Before accepting any generated image:--### Must Have-- [ ] Dark background (`#0a0a0f` or similar)-- [ ] Hand-drawn Excalidraw aesthetic-- [ ] PAI Blue (`#4a90d9`) for key elements-- [ ] White text (`#e5e7eb`) for labels-- [ ] Professional quality-- [ ] Readable at intended size--### Must NOT Have-- [ ] Light/white backgrounds-- [ ] Perfect vector shapes-- [ ] Generic AI illustration style-- [ ] Neon or garish colors-- [ ] Gradients or shadows (keep flat)-- [ ] Too many colors competing-AESTHETIC_EOF--echo "Created Aesthetic.md"-```-------### Step 4: Create TechnicalDiagrams.md Workflow--```bash-cat > "$PAI_DIR/skills/Art/Workflows/TechnicalDiagrams.md" << 'TECHDIAGRAM_EOF'-# Technical Diagram Workflow--**Clean Excalidraw-style technical diagrams with dark-mode aesthetic.**-------## Purpose--Technical diagrams for system architectures, process flows, and presentations.--**Use for:** Architecture diagrams, process flows, pipelines, infrastructure maps, presentations.-------## Visual Aesthetic--**Style:** Clean Excalidraw diagrams - professional, approachable, hand-drawn feel.--### Core Rules--1. **Excalidraw style** - Hand-drawn lines, slightly organic, professional-2. **Dark background #0a0a0f** - NO light backgrounds, NO grid lines-3. **Custom typography** - Specific hierarchy (see below)-4. **Strategic color** - PAI Blue #4a90d9 for key elements, Cyan #22d3ee for flows-5. **Line work dominant** - 70% of elements in white/gray, color is accent only-------## Typography System--### TIER 1: Headers & Subtitles--**Elegant wedge-serif style (like Valkyrie):**-- High stroke contrast, refined serifs-- Header: Large, italic, white `#e5e7eb`-- Subtitle: Smaller, regular weight, muted `#9ca3af`--### TIER 2: Labels--**Geometric sans-serif (like Concourse):**-- Clean, technical, precise-- Used for box labels, node names-- Color: White `#e5e7eb`--### TIER 3: Insights--**Condensed italic sans (like Advocate):**-- Editorial feel, attention-grabbing-- Used for callouts and annotations-- Color: PAI Blue `#4a90d9` or Cyan `#22d3ee`-------## Color Palette--```-Background #0a0a0f - Dark background (MANDATORY)-PAI Blue #4a90d9 - Key components, insights (15-20%)-Cyan #22d3ee - Flows, connections (5-10%)-White #e5e7eb - Text, labels, primary structure-Line Work #94a3b8 - Hand-drawn borders, boxes-Surface #1a1a2e - Card backgrounds (if needed)-```-------## Execution Steps--1. **Understand** - Read the content, identify key components and relationships-2. **Structure** - Plan the diagram layout (boxes, arrows, hierarchy)-3. **Compose** - Design the visual with title, subtitle, and 1-3 key insights-4. **Prompt** - Construct using the template below-5. **Generate** - Execute with CLI tool-6. **Validate** - Check against validation criteria-------## Prompt Template--```-Clean Excalidraw-style technical diagram on dark background.--BACKGROUND: Pure dark #0a0a0f - NO grid lines, NO texture, completely clean.--STYLE: Hand-drawn Excalidraw aesthetic - like a skilled architect's whiteboard sketch.--TYPOGRAPHY:-- HEADER: Elegant serif italic, large, white color, top-left position-- SUBTITLE: Same serif but regular weight, smaller, gray color, below header-- LABELS: Geometric sans-serif, white, clean and technical-- INSIGHTS: Condensed italic, PAI Blue #4a90d9, used for callouts with asterisks--DIAGRAM CONTENT:-Title: '[TITLE]' (Top left)-Subtitle: '[SUBTITLE]' (Below title)-Components: [LIST THE MAIN COMPONENTS]-Connections: [DESCRIBE THE FLOW/RELATIONSHIPS]--Include 1-3 insight callouts like "*key insight here*" in PAI Blue.--COLOR USAGE:-- White #e5e7eb for all text and primary structure-- PAI Blue #4a90d9 for key components and insights-- Cyan #22d3ee for flow arrows and connections-- Keep 70% of image in white/gray tones, color as accent--EXCALIDRAW CHARACTERISTICS:-- Slightly wobbly hand-drawn lines-- Imperfect rectangles with rounded corners-- Organic arrow curves-- Variable line weight-- Professional but approachable feel-```-------## Intent-to-Flag Mapping--### Model Selection--| User Says | Flag | When to Use |-|-----------|------|-------------|-| "fast", "quick", "draft" | `--model nano-banana` | Faster iteration |-| (default), "best", "high quality" | `--model nano-banana-pro` | Best quality (recommended) |-| "flux", "variety" | `--model flux` | Different aesthetic |--### Size Selection--| User Says | Flag | Resolution |-|-----------|------|------------|-| "draft", "preview" | `--size 1K` | Quick iterations |-| (default), "standard" | `--size 2K` | Standard output |-| "high res", "print" | `--size 4K` | Maximum resolution |--### Aspect Ratio--| User Says | Flag | Use Case |-|-----------|------|----------|-| "wide", "slide", "presentation" | `--aspect-ratio 16:9` | Default for diagrams |-| "square" | `--aspect-ratio 1:1` | Social media |-| "ultrawide" | `--aspect-ratio 21:9` | Wide system diagrams |-------## Generate Command--```bash-bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "[YOUR PROMPT]" \- --size 2K \- --aspect-ratio 16:9 \- --output ~/Downloads/diagram.png-```-------## Validation--### Must Have-- [ ] Dark background #0a0a0f (NO light backgrounds)-- [ ] Hand-drawn Excalidraw aesthetic-- [ ] Title and subtitle in top-left-- [ ] 1-3 insight callouts in PAI Blue-- [ ] Strategic color usage (70% white/gray, 30% color accents)-- [ ] Readable labels and text--### Must NOT Have-- [ ] Light/white backgrounds-- [ ] Grid lines or textures-- [ ] Perfect vector shapes-- [ ] Cartoony or clip-art style-- [ ] Over-coloring (everything blue)-- [ ] Generic AI illustration look--### If Validation Fails--| Problem | Fix |-|---------|-----|-| Light background | Add "dark background #0a0a0f" more explicitly |-| Too perfect/clean | Add "hand-drawn, slightly wobbly, Excalidraw style" |-| Wrong colors | Specify exact hex codes in prompt |-| No insights | Add "include 1-3 callouts in PAI Blue" |-------**The workflow: Understand → Structure → Compose → Prompt → Generate → Validate**-TECHDIAGRAM_EOF--echo "Created TechnicalDiagrams.md"-```-------### Step 5: Create Essay.md Workflow--```bash-cat > "$PAI_DIR/skills/Art/Workflows/Essay.md" << 'ESSAY_EOF'-# Editorial Illustration Workflow--**Hand-drawn Excalidraw-style illustrations for blog headers and editorial content.**-------## Purpose--Header images and editorial illustrations that visually represent content concepts.--**Use for:** Blog headers, article illustrations, concept visualizations, editorial art.-------## Visual Aesthetic--**Style:** Excalidraw hand-drawn sketch - professional, conceptual, dark-mode.--### Core Rules--1. **Excalidraw technique** - Hand-drawn gestural quality, not clean vectors-2. **Dark background #0a0a0f** - Consistent with overall aesthetic-3. **Conceptual subjects** - Draw what the content is ABOUT-4. **Strategic color** - PAI Blue for key elements, Cyan for secondary-5. **Minimalist composition** - Few elements, each intentional-------## Workflow Steps--### Step 1: Understand the Content--**Before doing anything:**-1. Read the full content (blog post, essay, article)-2. Identify the core concept or argument-3. Extract key metaphors, imagery, or concrete elements-4. Determine what should be visualized--**Output:** Clear understanding of what to illustrate.-------### Step 2: Design Composition--**Determine what to draw:**--1. **What is the content ABOUT?**- - Not surface-level - the actual core concept- - What visual would represent THAT?--2. **What are concrete elements?**- - Nouns, objects, metaphors from the content- - These should appear in the illustration--3. **What is the emotional register?**- - Technical, hopeful, warning, discovery, etc.- - This affects line quality and composition--4. **Composition approach:**- - Centered, minimalist, breathing space- - Subjects should fill the frame- - NOT cluttered, NOT busy--**Output:** A clear composition design.-------### Step 3: Construct the Prompt--### Prompt Template--```-Hand-drawn Excalidraw-style editorial illustration on dark background.--BACKGROUND: Pure dark #0a0a0f - clean, no texture.--SUBJECT: [WHAT TO DRAW - the core visual concept]--STYLE - EXCALIDRAW HAND-DRAWN:-- Gestural, slightly imperfect lines-- Variable line weight-- Hand-drawn quality (NOT clean vectors)-- Organic, approachable feel-- Sketch-like but professional--COMPOSITION:-- Subjects FILL THE FRAME (not small with empty space)-- Minimalist - few elements, each intentional-- Clean, uncluttered-- Professional editorial quality--COLOR:-- Dark background #0a0a0f (MANDATORY)-- White #e5e7eb for line work and structure-- PAI Blue #4a90d9 for key elements (15-20%)-- Cyan #22d3ee for secondary accents (5-10%)-- Accent Purple #8b5cf6 sparingly for highlights--EMOTIONAL REGISTER: [TECHNICAL/DISCOVERY/WARNING/PROGRESS/etc.]--CRITICAL:-- NO light backgrounds-- Subjects must be LARGE and fill the frame-- Hand-drawn Excalidraw aesthetic-- Professional quality suitable for publication-```-------### Step 4: Execute Generation--```bash-bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "[YOUR PROMPT]" \- --size 2K \- --aspect-ratio 1:1 \- --output ~/Downloads/header.png-```--**For blog headers that need thumbnails:**--```bash-bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "[YOUR PROMPT]" \- --size 2K \- --aspect-ratio 1:1 \- --thumbnail \- --output ~/Downloads/header.png-```--This creates BOTH:-- `header.png` - With transparent background (for inline display)-- `header-thumb.png` - With solid background (for social previews)-------### Step 5: Validation--### Must Have-- [ ] Dark background #0a0a0f-- [ ] Hand-drawn Excalidraw aesthetic-- [ ] Subject matches content concept-- [ ] Subjects LARGE and fill the frame-- [ ] Professional editorial quality-- [ ] Strategic color usage--### Must NOT Have-- [ ] Light/white backgrounds-- [ ] Perfect clean vectors-- [ ] Generic AI illustration style-- [ ] Too small subjects with lots of empty space-- [ ] Busy, cluttered composition-- [ ] Cartoony or clip-art style--### If Validation Fails--| Problem | Fix |-|---------|-----|-| Subjects too small | Add "LARGE SUBJECTS that FILL THE FRAME" |-| Light background | Emphasize "dark background #0a0a0f" |-| Too perfect | Add "hand-drawn Excalidraw style, slightly imperfect" |-| Doesn't match content | Re-read content, identify better visual metaphor |-------## Aspect Ratio Guide--| Use Case | Aspect Ratio | Notes |-|----------|--------------|-------|-| Blog header (square) | 1:1 | Default for most posts |-| Wide banner | 16:9 | For wide layouts |-| Social preview | 1:1 or 16:9 | Platform dependent |-------**The workflow: Understand → Design → Prompt → Generate → Validate**-ESSAY_EOF--echo "Created Essay.md"-```-------### Step 6: Create Comics.md Workflow--```bash-cat > "$PAI_DIR/skills/Art/Workflows/Comics.md" << 'COMICS_EOF'-# Editorial Comics Workflow--**Sequential panel storytelling with sophisticated hand-drawn aesthetic.**-------## Purpose--Editorial comics use sequential panels to explain concepts, tell stories, or illustrate scenarios.--**Use for:**-- Explaining complex concepts through narrative-- Before/during/after sequences-- Illustrated thought experiments-- Multi-step processes shown visually-- Scenario storytelling-------## Visual Aesthetic--**Style:** Sophisticated sequential art - New Yorker style, NOT cartoonish.--### Core Characteristics--1. **Multi-panel** - 3-4 panels telling sequential story-2. **Editorial style** - Sophisticated, not cutesy-3. **Planeform figures** - Angular, architectural character design-4. **Hand-drawn** - Imperfect linework, gestural quality-5. **Narrative flow** - Panels build to make a point-6. **Minimal dialogue** - Visual storytelling prioritized-------## Color System--```-Background #0a0a0f - Overall dark canvas-Panel BG #1a1a2e - Individual panel backgrounds-Line Work #e5e7eb - All linework, character outlines-PAI Blue #4a90d9 - Main character accent-Cyan #22d3ee - Secondary character accent-Text #e5e7eb - Dialogue, captions-```--### Color Strategy--- Dark overall canvas with slightly lighter panel backgrounds-- Characters primarily white linework-- PAI Blue accent on protagonist-- Cyan on secondary character if needed-- Minimal color - mostly linework-------## Workflow Steps--### Step 1: Define Comic Narrative--**Plan the story:**--```-COMIC CONCEPT: [What you're illustrating]-PANELS: [3 or 4]--NARRATIVE ARC:-Panel 1: [Setup - initial state]-Panel 2: [Action/Complication - what changes]-Panel 3: [Escalation or Result]-Panel 4: [Punchline/Insight] (if 4 panels)--DIALOGUE (Minimal):-Panel 1: "[Optional text]"-Panel 2: "[Optional text]"-Panel 3: "[Optional text]"-Panel 4: "[Punchline]"--CHARACTERS:-- [Character 1]: [Description, PAI Blue accent]-- [Character 2]: [Description, Cyan accent if needed]-```-------### Step 2: Design Panel Layout--**Panel arrangement options:**-- Horizontal strip (3-4 panels left to right)-- Vertical strip (3-4 panels top to bottom)-- Grid (2x2 for 4 panels)--**Panel sizing:**-- Equal sized panels (classic)-- Final panel larger (punchline emphasis)-------### Step 3: Construct Prompt--### Prompt Template--```-Hand-drawn editorial comic strip on dark background.--STYLE: New Yorker cartoon, editorial sophistication, NOT cartoonish.--BACKGROUND: Dark #0a0a0f canvas with #1a1a2e panel backgrounds.--COMIC STRUCTURE: [3-panel / 4-panel] [horizontal / vertical / grid]--PANEL LAYOUT:-- [Number] panels arranged [direction]-- Hand-drawn panel borders (slightly wobbly)-- Panel sizes: [Equal / Varied]--CHARACTER DESIGN - PLANEFORM AESTHETIC:-- Angular planes (like architectural paper models)-- Adult proportions (1:7 head-to-body), elongated-- Faces are minimal geometric blocks-- Emotion through GESTURE and SILHOUETTE-- NOT cute, NOT cartoonish-- Hand-drawn gestural quality with angular construction--COMIC NARRATIVE: "[Overall concept]"--PANEL 1 - [SETUP]:-Scene: [What's happening]-Characters: [Who, doing what]-Dialogue: "[Text]" or no text--PANEL 2 - [COMPLICATION]:-Scene: [What changes]-Characters: [Actions]-Dialogue: "[Text]" or no text--PANEL 3 - [RESULT]:-Scene: [Outcome]-Characters: [Final states]-Dialogue: "[Text]" or no text--PANEL 4 - [PUNCHLINE] (if 4 panels):-Scene: [Revelation]-Characters: [Conclusion]-Dialogue: "[Insight text]"--COLOR USAGE:-- White #e5e7eb for linework and character outlines-- PAI Blue #4a90d9 accent on main character-- Cyan #22d3ee accent on secondary character-- Dark backgrounds throughout--CRITICAL:-- Sophisticated editorial style (NOT cutesy)-- Clear narrative flow across panels-- Character consistency throughout-- Visual storytelling prioritized-- Professional quality-```-------### Step 4: Determine Aspect Ratio--| Layout | Aspect Ratio |-|--------|--------------|-| 3-panel horizontal | 16:9 or 21:9 |-| 4-panel horizontal | 21:9 |-| 3-panel vertical | 9:16 |-| 4-panel grid (2x2) | 1:1 |-------### Step 5: Execute Generation--```bash-bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "[YOUR PROMPT]" \- --size 2K \- --aspect-ratio 16:9 \- --output ~/Downloads/comic.png-```-------### Step 6: Validation--### Must Have-- [ ] Clear panel structure-- [ ] Sophisticated editorial aesthetic (NOT cartoonish)-- [ ] Narrative flow across panels-- [ ] Character consistency-- [ ] Hand-drawn quality-- [ ] Dark backgrounds-- [ ] Planeform character design (angular, adult proportions)--### Must NOT Have-- [ ] Cartoonish or cutesy style-- [ ] Round forms on figures (should be angular)-- [ ] Big heads, stubby proportions-- [ ] Detailed cute faces-- [ ] Light backgrounds-- [ ] Busy complex backgrounds-- [ ] Generic AI illustration style--### Character Validation-- [ ] Angular construction (NOT round)-- [ ] Adult proportions 1:7 (NOT stubby 1:3)-- [ ] Minimal geometric faces-- [ ] Emotion through gesture-- [ ] Consistent across panels-------## Example Narratives--### Example 1: "Before/After AI" (3 panels)-- Panel 1: Person struggling with manual task-- Panel 2: AI assistant appears-- Panel 3: Task completed, person relieved--### Example 2: "Security Theater" (4 panels)-- Panel 1: Fancy lock on flimsy door-- Panel 2: Simple lock on solid door-- Panel 3: Intruder easily bypasses fancy setup-- Panel 4: Stopped by simple solid approach-------**The workflow: Define → Design → Prompt → Generate → Validate**-COMICS_EOF--echo "Created Comics.md"-```-------### Step 7: Create Generate.ts Tool--```bash-cat > "$PAI_DIR/skills/Art/Tools/Generate.ts" << 'GENERATE_EOF'-#!/usr/bin/env bun--/**- * generate - Image Generation CLI- *- * Generate images using Flux 1.1 Pro, Nano Banana, Nano Banana Pro, or GPT-image-1.- * Follows deterministic, composable CLI design.- *- * Usage:- * bun run Generate.ts --model nano-banana-pro --prompt "..." --size 2K --output /tmp/image.png- */--import Replicate from "replicate";-import OpenAI from "openai";-import { GoogleGenAI } from "@google/genai";-import { writeFile, readFile } from "node:fs/promises";-import { extname, resolve } from "node:path";-import { exec } from "node:child_process";-import { promisify } from "node:util";--const execAsync = promisify(exec);--// ============================================================================-// Environment Loading-// ============================================================================--async function loadEnv(): Promise<void> {- // Load from canonical location: $PAI_DIR/.env (single source of truth)- // Falls back to legacy locations for backwards compatibility- const paiDir = process.env.PAI_DIR || resolve(process.env.HOME!, '.config/pai');- const envPaths = [- resolve(paiDir, '.env'),- resolve(process.env.HOME!, '.claude/.env'), // Legacy location- ];-- for (const envPath of envPaths) {- try {- const envContent = await readFile(envPath, 'utf-8');- for (const line of envContent.split('\n')) {- const trimmed = line.trim();- if (!trimmed || trimmed.startsWith('#')) continue;- const eqIndex = trimmed.indexOf('=');- if (eqIndex === -1) continue;- const key = trimmed.slice(0, eqIndex).trim();- let value = trimmed.slice(eqIndex + 1).trim();- if ((value.startsWith('"') && value.endsWith('"')) ||- (value.startsWith("'") && value.endsWith("'"))) {- value = value.slice(1, -1);- }- if (!process.env[key]) {- process.env[key] = value;- }- }- break; // Stop after first successful load- } catch {- // Continue to next path- }- }-}--// ============================================================================-// Types-// ============================================================================--type Model = "flux" | "nano-banana" | "nano-banana-pro" | "gpt-image-1";-type ReplicateSize = "1:1" | "16:9" | "3:2" | "2:3" | "3:4" | "4:3" | "4:5" | "5:4" | "9:16" | "21:9";-type OpenAISize = "1024x1024" | "1536x1024" | "1024x1536";-type GeminiSize = "1K" | "2K" | "4K";-type Size = ReplicateSize | OpenAISize | GeminiSize;--interface CLIArgs {- model: Model;- prompt: string;- size: Size;- output: string;- creativeVariations?: number;- aspectRatio?: ReplicateSize;- transparent?: boolean;- referenceImages?: string[]; // Multiple reference images (up to 14 total)- removeBg?: boolean;- addBg?: string;- thumbnail?: boolean;-}--// ============================================================================-// Configuration-// ============================================================================--const DEFAULTS = {- model: "nano-banana-pro" as Model,- size: "2K" as Size,- output: `${process.env.HOME}/Downloads/art-output.png`,-};--const REPLICATE_SIZES: ReplicateSize[] = ["1:1", "16:9", "3:2", "2:3", "3:4", "4:3", "4:5", "5:4", "9:16", "21:9"];-const OPENAI_SIZES: OpenAISize[] = ["1024x1024", "1536x1024", "1024x1536"];-const GEMINI_SIZES: GeminiSize[] = ["1K", "2K", "4K"];-const GEMINI_ASPECT_RATIOS: ReplicateSize[] = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];--// ============================================================================-// Error Handling-// ============================================================================--class CLIError extends Error {- constructor(message: string, public exitCode: number = 1) {- super(message);- this.name = "CLIError";- }-}--function handleError(error: unknown): never {- if (error instanceof CLIError) {- console.error(`Error: ${error.message}`);- process.exit(error.exitCode);- }- if (error instanceof Error) {- console.error(`Unexpected error: ${error.message}`);- process.exit(1);- }- console.error(`Unknown error:`, error);- process.exit(1);-}--// ============================================================================-// Help-// ============================================================================--// PAI directory for documentation paths-const PAI_DIR = process.env.PAI_DIR || `${process.env.HOME}/.config/pai`;--function showHelp(): void {- console.log(`-generate - Image Generation CLI--Generate images using Flux, Nano Banana, Nano Banana Pro, or GPT-image-1.--USAGE:- bun run Generate.ts --model <model> --prompt "<prompt>" [OPTIONS]--REQUIRED:- --model <model> Model: flux, nano-banana, nano-banana-pro, gpt-image-1- --prompt <text> Image generation prompt--OPTIONS:- --size <size> Image size (default: 2K for Gemini, 16:9 for others)- Replicate: 1:1, 16:9, 3:2, 2:3, 3:4, 4:3, 4:5, 5:4, 9:16, 21:9- OpenAI: 1024x1024, 1536x1024, 1024x1536- Gemini: 1K, 2K, 4K- --aspect-ratio <ratio> Aspect ratio for Gemini (default: 16:9)- --output <path> Output path (default: ~/Downloads/art-output.png)- --reference-image <path> Reference image for style/character consistency (nano-banana-pro only)- Can specify MULTIPLE times for improved consistency- API Limits: Up to 5 human refs, 6 object refs, 14 total max- --transparent Add transparency instructions to prompt- --remove-bg Remove background using remove.bg API- --add-bg <hex> Add background color (e.g., "#0a0a0f")- --thumbnail Create both transparent + thumbnail versions- --creative-variations <n> Generate N variations (1-10)- --help, -h Show this help--EXAMPLES:- # Technical diagram (recommended)- bun run Generate.ts --model nano-banana-pro --prompt "..." --size 2K --aspect-ratio 16:9-- # Blog header with thumbnail- bun run Generate.ts --model nano-banana-pro --prompt "..." --size 2K --aspect-ratio 1:1 --thumbnail-- # Quick draft- bun run Generate.ts --model nano-banana --prompt "..." --size 16:9-- # MULTIPLE reference images for character consistency (nano-banana-pro only)- bun run Generate.ts --model nano-banana-pro --prompt "Person from references at a party..." \\- --reference-image face1.jpg --reference-image face2.jpg --reference-image face3.jpg \\- --size 2K --aspect-ratio 16:9--MULTI-REFERENCE LIMITS (Gemini API):- - Up to 5 human reference images for character consistency- - Up to 6 object reference images- - Maximum 14 total reference images per request--ENVIRONMENT VARIABLES:- REPLICATE_API_TOKEN Required for flux, nano-banana- GOOGLE_API_KEY Required for nano-banana-pro- OPENAI_API_KEY Required for gpt-image-1- REMOVEBG_API_KEY Required for --remove-bg--MORE INFO:- Documentation: \${PAI_DIR}/skills/Art/README.md- Source: \${PAI_DIR}/skills/Art/Tools/Generate.ts-`);- process.exit(0);-}--// ============================================================================-// Argument Parsing-// ============================================================================--function parseArgs(argv: string[]): CLIArgs {- const args = argv.slice(2);-- if (args.includes("--help") || args.includes("-h") || args.length === 0) {- showHelp();- }-- const parsed: Partial<CLIArgs> = {- model: DEFAULTS.model,- size: DEFAULTS.size,- output: DEFAULTS.output,- };-- // Collect reference images into array- const referenceImages: string[] = [];-- for (let i = 0; i < args.length; i++) {- const flag = args[i];-- if (!flag.startsWith("--")) {- throw new CLIError(`Invalid flag: ${flag}`);- }-- const key = flag.slice(2);-- // Boolean flags- if (key === "transparent") { parsed.transparent = true; continue; }- if (key === "remove-bg") { parsed.removeBg = true; continue; }- if (key === "thumbnail") { parsed.thumbnail = true; parsed.removeBg = true; continue; }-- // Flags with values- const value = args[i + 1];- if (!value || value.startsWith("--")) {- throw new CLIError(`Missing value for: ${flag}`);- }-- switch (key) {- case "model":- if (!["flux", "nano-banana", "nano-banana-pro", "gpt-image-1"].includes(value)) {- throw new CLIError(`Invalid model: ${value}`);- }- parsed.model = value as Model;- i++;- break;- case "prompt":- parsed.prompt = value;- i++;- break;- case "size":- parsed.size = value as Size;- i++;- break;- case "aspect-ratio":- parsed.aspectRatio = value as ReplicateSize;- i++;- break;- case "output":- parsed.output = value;- i++;- break;- case "reference-image":- // Collect multiple reference images into array- referenceImages.push(value);- i++;- break;- case "creative-variations":- const n = parseInt(value, 10);- if (isNaN(n) || n < 1 || n > 10) {- throw new CLIError(`Invalid creative-variations: ${value}`);- }- parsed.creativeVariations = n;- i++;- break;- case "add-bg":- if (!/^#[0-9A-Fa-f]{6}$/.test(value)) {- throw new CLIError(`Invalid hex color: ${value}`);- }- parsed.addBg = value;- i++;- break;- default:- throw new CLIError(`Unknown flag: ${flag}`);- }- }-- // Assign collected reference images if any- if (referenceImages.length > 0) {- parsed.referenceImages = referenceImages;- }-- if (!parsed.prompt) throw new CLIError("Missing: --prompt");- if (!parsed.model) throw new CLIError("Missing: --model");-- if (parsed.referenceImages && parsed.referenceImages.length > 0 && parsed.model !== "nano-banana-pro") {- throw new CLIError("--reference-image only works with nano-banana-pro");- }-- // Validate reference image count (API limits: 5 human, 6 object, 14 total max)- if (parsed.referenceImages && parsed.referenceImages.length > 14) {- throw new CLIError(`Too many reference images: ${parsed.referenceImages.length}. Maximum is 14 total`);- }-- // Validate size for model- if (parsed.model === "gpt-image-1" && !OPENAI_SIZES.includes(parsed.size as OpenAISize)) {- throw new CLIError(`Invalid size for gpt-image-1: ${parsed.size}`);- } else if (parsed.model === "nano-banana-pro") {- if (!GEMINI_SIZES.includes(parsed.size as GeminiSize)) {- throw new CLIError(`Invalid size for nano-banana-pro: ${parsed.size}`);- }- if (!parsed.aspectRatio) parsed.aspectRatio = "16:9";- } else if (!REPLICATE_SIZES.includes(parsed.size as ReplicateSize)) {- throw new CLIError(`Invalid size: ${parsed.size}`);- }-- return parsed as CLIArgs;-}--// ============================================================================-// Background Operations-// ============================================================================--async function addBackgroundColor(inputPath: string, outputPath: string, hexColor: string): Promise<void> {- console.log(`Adding background ${hexColor}...`);- const command = `magick "${inputPath}" -background "${hexColor}" -flatten "${outputPath}"`;- try {- await execAsync(command);- console.log(`Thumbnail saved: ${outputPath}`);- } catch (error) {- throw new CLIError(`Failed to add background: ${error instanceof Error ? error.message : String(error)}`);- }-}--async function removeBackground(imagePath: string): Promise<void> {- const apiKey = process.env.REMOVEBG_API_KEY;- if (!apiKey) throw new CLIError("Missing: REMOVEBG_API_KEY");-- console.log("Removing background...");-- const imageBuffer = await readFile(imagePath);- const formData = new FormData();- formData.append("image_file", new Blob([imageBuffer]), "image.png");- formData.append("size", "auto");-- const response = await fetch("https://api.remove.bg/v1.0/removebg", {- method: "POST",- headers: { "X-Api-Key": apiKey },- body: formData,- });-- if (!response.ok) {- const errorText = await response.text();- throw new CLIError(`remove.bg error: ${response.status} - ${errorText}`);- }-- const resultBuffer = Buffer.from(await response.arrayBuffer());- await writeFile(imagePath, resultBuffer);- console.log("Background removed");-}--// ============================================================================-// Image Generation-// ============================================================================--async function generateWithFlux(prompt: string, size: ReplicateSize, output: string): Promise<void> {- const token = process.env.REPLICATE_API_TOKEN;- if (!token) throw new CLIError("Missing: REPLICATE_API_TOKEN");-- const replicate = new Replicate({ auth: token });- console.log("Generating with Flux 1.1 Pro...");-- const result = await replicate.run("black-forest-labs/flux-1.1-pro", {- input: {- prompt,- aspect_ratio: size,- output_format: "png",- output_quality: 95,- prompt_upsampling: false,- },- });-- await writeFile(output, result);- console.log(`Saved: ${output}`);-}--async function generateWithNanoBanana(prompt: string, size: ReplicateSize, output: string): Promise<void> {- const token = process.env.REPLICATE_API_TOKEN;- if (!token) throw new CLIError("Missing: REPLICATE_API_TOKEN");-- const replicate = new Replicate({ auth: token });- console.log("Generating with Nano Banana...");-- const result = await replicate.run("google/nano-banana", {- input: {- prompt,- aspect_ratio: size,- output_format: "png",- },- });-- await writeFile(output, result);- console.log(`Saved: ${output}`);-}--async function generateWithNanoBananaPro(- prompt: string,- size: GeminiSize,- aspectRatio: ReplicateSize,- output: string,- referenceImages?: string[]-): Promise<void> {- const apiKey = process.env.GOOGLE_API_KEY;- if (!apiKey) throw new CLIError("Missing: GOOGLE_API_KEY");-- const ai = new GoogleGenAI({ apiKey });-- if (referenceImages && referenceImages.length > 0) {- console.log(`Generating with Nano Banana Pro at ${size} ${aspectRatio} with ${referenceImages.length} reference image(s)...`);- } else {- console.log(`Generating with Nano Banana Pro at ${size} ${aspectRatio}...`);- }-- const parts: Array<{ text?: string; inlineData?: { mimeType: string; data: string } }> = [];-- // Add all reference images if provided- if (referenceImages && referenceImages.length > 0) {- for (const referenceImage of referenceImages) {- const imageBuffer = await readFile(referenceImage);- const imageBase64 = imageBuffer.toString("base64");- const ext = extname(referenceImage).toLowerCase();- const mimeMap: Record<string, string> = {- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".webp": "image/webp",- };- const mimeType = mimeMap[ext];- if (!mimeType) throw new CLIError(`Unsupported format: ${ext}`);- parts.push({ inlineData: { mimeType, data: imageBase64 } });- }- }-- parts.push({ text: prompt });-- const response = await ai.models.generateContent({- model: "gemini-3-pro-image-preview",- contents: [{ parts }],- config: {- responseModalities: ["TEXT", "IMAGE"],- imageConfig: { aspectRatio, imageSize: size },- },- });-- let imageData: string | undefined;- if (response.candidates && response.candidates.length > 0) {- for (const part of response.candidates[0].content.parts) {- if (part.inlineData?.data) {- imageData = part.inlineData.data;- break;- }- }- }-- if (!imageData) throw new CLIError("No image returned from Gemini");-- await writeFile(output, Buffer.from(imageData, "base64"));- console.log(`Saved: ${output}`);-}--async function generateWithGPTImage(prompt: string, size: OpenAISize, output: string): Promise<void> {- const apiKey = process.env.OPENAI_API_KEY;- if (!apiKey) throw new CLIError("Missing: OPENAI_API_KEY");-- const openai = new OpenAI({ apiKey });- console.log("Generating with GPT-image-1...");-- const response = await openai.images.generate({- model: "gpt-image-1",- prompt,- size,- n: 1,- });-- const imageData = response.data[0].b64_json;- if (!imageData) throw new CLIError("No image returned from OpenAI");-- await writeFile(output, Buffer.from(imageData, "base64"));- console.log(`Saved: ${output}`);-}--// ============================================================================-// Main-// ============================================================================--async function main(): Promise<void> {- try {- await loadEnv();- const args = parseArgs(process.argv);-- let finalPrompt = args.prompt;- if (args.transparent) {- finalPrompt = "CRITICAL: Transparent background (PNG with alpha). " + finalPrompt;- }-- // Handle variations- if (args.creativeVariations && args.creativeVariations > 1) {- console.log(`Generating ${args.creativeVariations} variations...`);- const basePath = args.output.replace(/\.png$/, "");-- for (let i = 1; i <= args.creativeVariations; i++) {- const varOutput = `${basePath}-v${i}.png`;- console.log(`Variation ${i}/${args.creativeVariations}`);-- if (args.model === "flux") {- await generateWithFlux(finalPrompt, args.size as ReplicateSize, varOutput);- } else if (args.model === "nano-banana") {- await generateWithNanoBanana(finalPrompt, args.size as ReplicateSize, varOutput);- } else if (args.model === "nano-banana-pro") {- await generateWithNanoBananaPro(finalPrompt, args.size as GeminiSize, args.aspectRatio!, varOutput, args.referenceImages);- } else if (args.model === "gpt-image-1") {- await generateWithGPTImage(finalPrompt, args.size as OpenAISize, varOutput);- }- }- console.log(`Generated ${args.creativeVariations} variations`);- return;- }-- // Single image generation- if (args.model === "flux") {- await generateWithFlux(finalPrompt, args.size as ReplicateSize, args.output);- } else if (args.model === "nano-banana") {- await generateWithNanoBanana(finalPrompt, args.size as ReplicateSize, args.output);- } else if (args.model === "nano-banana-pro") {- await generateWithNanoBananaPro(finalPrompt, args.size as GeminiSize, args.aspectRatio!, args.output, args.referenceImages);- } else if (args.model === "gpt-image-1") {- await generateWithGPTImage(finalPrompt, args.size as OpenAISize, args.output);- }-- // Post-processing- if (args.removeBg) {- await removeBackground(args.output);- }-- if (args.addBg && !args.thumbnail) {- const tempPath = args.output.replace(/\.png$/, "-temp.png");- await addBackgroundColor(args.output, tempPath, args.addBg);- const { rename } = await import("node:fs/promises");- await rename(tempPath, args.output);- }-- if (args.thumbnail) {- const thumbPath = args.output.replace(/\.png$/, "-thumb.png");- const THUMB_BG = "#0a0a0f"; // Dark background for thumbnails- await addBackgroundColor(args.output, thumbPath, THUMB_BG);- console.log(`\nCreated both versions:`);- console.log(` Transparent: ${args.output}`);- console.log(` Thumbnail: ${thumbPath}`);- }- } catch (error) {- handleError(error);- }-}--main();-GENERATE_EOF--echo "Created Generate.ts"-```-------### Step 8: Set Up Environment Variables--Create or update your `.env` file with API keys:--```bash-PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"--# Create .env if it doesn't exist-if [ ! -f "$PAI_DIR/.env" ]; then- cat > "$PAI_DIR/.env" << 'ENV_EOF'-# Art Skill API Keys-# Uncomment and fill in the keys you have--# For Flux and Nano Banana models (Replicate)-# REPLICATE_API_TOKEN=r8_your_token_here--# For Nano Banana Pro (Gemini 3)-# GOOGLE_API_KEY=your_google_api_key_here--# For GPT-image-1 (OpenAI)-# OPENAI_API_KEY=sk-your_openai_key_here--# For background removal-# REMOVEBG_API_KEY=your_removebg_key_here-ENV_EOF- echo "Created $PAI_DIR/.env - Please add your API keys"-else- echo ".env already exists at $PAI_DIR/.env"-fi-```-------### Step 9: Verify Installation--```bash-PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"--echo "Verifying Art Skill installation..."-echo ""--# Check files-echo "Files:"-[ -f "$PAI_DIR/skills/Art/SKILL.md" ] && echo " [OK] SKILL.md" || echo " [MISSING] SKILL.md"-[ -f "$PAI_DIR/skills/Art/Aesthetic.md" ] && echo " [OK] Aesthetic.md" || echo " [MISSING] Aesthetic.md"-[ -f "$PAI_DIR/skills/Art/Workflows/TechnicalDiagrams.md" ] && echo " [OK] TechnicalDiagrams.md" || echo " [MISSING] TechnicalDiagrams.md"-[ -f "$PAI_DIR/skills/Art/Workflows/Essay.md" ] && echo " [OK] Essay.md" || echo " [MISSING] Essay.md"-[ -f "$PAI_DIR/skills/Art/Workflows/Comics.md" ] && echo " [OK] Comics.md" || echo " [MISSING] Comics.md"-[ -f "$PAI_DIR/skills/Art/Tools/Generate.ts" ] && echo " [OK] Generate.ts" || echo " [MISSING] Generate.ts"--echo ""-echo "API Keys (check $PAI_DIR/.env):"-[ -n "$REPLICATE_API_TOKEN" ] && echo " [OK] REPLICATE_API_TOKEN" || echo " [--] REPLICATE_API_TOKEN (optional)"-[ -n "$GOOGLE_API_KEY" ] && echo " [OK] GOOGLE_API_KEY" || echo " [--] GOOGLE_API_KEY (optional)"-[ -n "$OPENAI_API_KEY" ] && echo " [OK] OPENAI_API_KEY" || echo " [--] OPENAI_API_KEY (optional)"-[ -n "$REMOVEBG_API_KEY" ] && echo " [OK] REMOVEBG_API_KEY" || echo " [--] REMOVEBG_API_KEY (optional)"--echo ""-echo "Test CLI tool:"-bun run "$PAI_DIR/skills/Art/Tools/Generate.ts" --help | head -5--echo ""-echo "Installation complete!"-```-------## Invocation Scenarios--The Art Skill activates based on user requests:--| User Request | Workflow | Output |-|--------------|----------|--------|-| "create a diagram of the auth flow" | TechnicalDiagrams | Architecture diagram PNG |-| "make a technical diagram showing X" | TechnicalDiagrams | Process flow PNG |-| "create a header for my blog post about Y" | Essay | Editorial illustration PNG |-| "illustrate the concept of Z" | Essay | Conceptual illustration PNG |-| "make a comic showing before/after" | Comics | 3-4 panel comic strip PNG |-| "create a visual explanation of W" | Comics | Sequential narrative PNG |-------## Example Usage--### Example 1: Technical Diagram--```bash-# User: "create a diagram showing how authentication works"--# Skill routes to TechnicalDiagrams workflow, which constructs prompt:-bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "Clean Excalidraw-style technical diagram on dark background #0a0a0f. Title: 'Authentication Flow'. Shows: User -> Login Form -> Auth Service -> Token -> Protected Resource. Hand-drawn style, PAI Blue #4a90d9 for key components, Cyan #22d3ee for arrows. Include insight callout '*tokens expire after 24h*' in blue." \- --size 2K \- --aspect-ratio 16:9 \- --output ~/Downloads/auth-diagram.png-```--### Example 2: Blog Header--```bash-# User: "create a header image for my post about AI agents"--bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "Hand-drawn Excalidraw-style illustration on dark background #0a0a0f. Subject: Multiple AI agents working together, represented as geometric angular figures collaborating. Style: gestural hand-drawn lines, professional editorial quality. Colors: White #e5e7eb linework, PAI Blue #4a90d9 accents, Cyan #22d3ee for connections. Subjects fill the frame, minimalist composition." \- --size 2K \- --aspect-ratio 1:1 \- --thumbnail \- --output ~/Downloads/ai-agents-header.png-```--### Example 3: Editorial Comic--```bash-# User: "create a comic showing the difference between manual and automated testing"--bun run $PAI_DIR/skills/Art/Tools/Generate.ts \- --model nano-banana-pro \- --prompt "Hand-drawn editorial comic strip, 3 panels horizontal, dark background. Panel 1: Developer manually clicking through app, exhausted (PAI Blue accent). Panel 2: Same developer writing test script, focused. Panel 3: Tests running automatically while developer relaxes. Planeform character design - angular, adult proportions, minimal faces. New Yorker sophistication, NOT cartoonish." \- --size 2K \- --aspect-ratio 21:9 \- --output ~/Downloads/testing-comic.png-```-------## Configuration--### Environment Variables--```bash-# Required (at least one)-export REPLICATE_API_TOKEN="r8_..." # For Flux, Nano Banana-export GOOGLE_API_KEY="..." # For Nano Banana Pro (recommended)-export OPENAI_API_KEY="sk-..." # For GPT-image-1--# Optional-export REMOVEBG_API_KEY="..." # For background removal-export PAI_DIR="$HOME/.config/pai" # Custom PAI directory-```-------## Customization--### Recommended Customization--**Personalize Your Aesthetic Through AI Conversation**--The single most valuable customization for this pack is to have an extended conversation with your AI about your personal aesthetic preferences, then capture that in `Aesthetic.md`. This transforms the Art Skill from a generic tool into one that produces images reflecting YOUR unique visual taste.--**What to Customize:** `$PAI_DIR/skills/Art/Aesthetic.md`--**Why:** The default Aesthetic.md contains a generic Excalidraw-style dark-mode palette. By investing 15-30 minutes in an aesthetic exploration conversation, every image generated will feel like YOUR work, not generic AI output. This is the difference between "usable" and "perfectly on-brand."--**Process:**--1. **Start the Aesthetic Exploration Conversation**-- Tell your AI something like:- ```- I want to define my personal aesthetic for the Art Skill. Let's have a conversation- where you ask me questions about my visual preferences, and we'll capture the- result in Aesthetic.md.- ```--2. **Answer Questions About Your Preferences**-- Your AI will ask about:- - Color preferences (warm vs cool, muted vs vibrant, specific colors you love/hate)- - Line quality (precise vs gestural, thick vs thin, confident vs sketchy)- - Composition style (minimal vs detailed, symmetric vs organic, structured vs chaotic)- - Influences and inspiration (artists, design movements, specific images you love)- - Emotional tone (technical, whimsical, serious, playful, elegant, raw)- - Typography preferences (serif vs sans, heavy vs light, classic vs modern)- - Specific use cases (blog headers, diagrams, social media, presentations)--3. **Iterate with Visual Examples**-- As you discuss, your AI can generate test images:- ```- Generate a sample header image using what we've discussed so far- ```- Use these to refine the aesthetic definition. "More like this, less like that."--4. **Capture the Final Aesthetic**-- Once you're satisfied, ask:- ```- Now update my Aesthetic.md with everything we've defined- ```- Your AI will rewrite Aesthetic.md with your personalized color palette, style guidelines, and validation criteria.--**Expected Outcome:** After this process, running `create a header image for my post about X` will produce images that feel unmistakably YOURS—matching your brand, preferences, and visual language.-------### Optional Customization--| Customization | File | Impact |-|---------------|------|--------|-| **Custom Color Palette** | `Aesthetic.md` | Change hex codes to match your brand colors |-| **Custom Prompt Templates** | `Workflows/*.md` | Create prompt patterns for your specific use cases |-| **Additional Workflows** | `Workflows/` | Add workflows for content types you create frequently (infographics, presentations, etc.) |-| **Model Preference** | `SKILL.md` | Change default model if you prefer different generation characteristics |-| **Validation Criteria** | `Aesthetic.md` | Add specific must-have/must-not-have rules for your brand |--**Example: Brand Color Customization**--Edit `Aesthetic.md` to replace the default palette:--```markdown-## Color Palette--### Primary Colors-| Color | Hex | Usage |-|-------|-----|-------|-| **Background** | `#1a1a2e` | Your brand's dark background |-| **Primary** | `#ff6b35` | Your brand's accent color |-| **Secondary** | `#4ecdc4` | Your brand's secondary color |-```--**Example: Adding a Custom Workflow**--Create `$PAI_DIR/skills/Art/Workflows/Infographics.md` for a specific content type you create often:--```markdown-# Infographic Workflow--[Your custom workflow for infographic-style visuals with your specific-prompt templates, validation criteria, and generation settings]-```--Then add a routing entry in `SKILL.md`:-```markdown- - Infographic or data visualization → `Workflows/Infographics.md`-```-------## Credits--- **Original concept**: Daniel Miessler - developed as part of Kai personal AI infrastructure-- **Aesthetic inspiration**: Excalidraw, modern dark-mode design systems-- **AI models**: Replicate (Flux, Nano Banana), Google (Gemini), OpenAI (GPT-image)-------## Related Work--*None specified - maintainer to provide if applicable.*-------## Works Well With--*None specified - maintainer to provide if applicable.*-------## Changelog--### 1.1.0 - 2025-12-29-- **Multiple reference images**: Support up to 14 reference images for improved character/style consistency- - `--reference-image` flag can now be specified multiple times- - API limits: 5 human refs, 6 object refs, 14 total max- - Significantly improves likeness consistency across generated images-- Added `PAI_DIR` constant to fix help text paths--### 1.0.0 - 2025-12-29-- Initial release-- Three workflows: TechnicalDiagrams, Essay, Comics-- Excalidraw hand-drawn aesthetic with dark-mode colors-- Generate.ts CLI with multi-model support-- Sample Aesthetic.md with blue/black color schemediff --git a/Packs/kai-hook-system.md b/Packs/kai-hook-system.mddeleted file mode 100644index 9b90e9e8..00000000--- a/Packs/kai-hook-system.md+++ /dev/null@@ -1,1492 +0,0 @@-----name: Kai Hook System-pack-id: danielmiessler-kai-hook-system-core-v1.0.0-version: 1.0.0-author: danielmiessler-description: Event-driven automation framework for Claude Code - the foundation for all hook-based capabilities including security validation, session management, and context injection-type: feature-purpose-type: [automation, security, development]-platform: claude-code-dependencies: []-keywords: [hooks, automation, events, security, validation, sessions, context, claude-code, preprocessing, postprocessing]------<p align="center">- <img src="icons/kai-hook-system.png" alt="Kai Hook System" width="256">-</p>--# Kai Hook System (kai-hook-system)--> Event-driven automation framework for Claude Code - the foundation for all hook-based capabilities--## Installation Prompt-You are receiving a PAI Pack - a modular upgrade for AI agent systems.--**What is PAI?** See: [PAI Project Overview](../README.md#what-is-pai)--**What is a Pack?** See: [Pack System](../README.md#pack-system)--This Pack adds event-driven automation to your AI infrastructure. The Kai Hook System is the foundation that enables all other hook-based Packs to work:--- **Security Validation**: Block dangerous commands before execution-- **Session Management**: Initialize sessions with context and state-- **Context Injection**: Load skill definitions at session start-- **Terminal Integration**: Update tab titles with task context-- **Event Pipeline**: PreToolUse, PostToolUse, Stop, SessionStart, and more--**Core principle:** Hooks intercept events and add intelligence without interrupting work.--Every tool call, every session start, every completion - hooks see it all and can act on it. This is how you make AI infrastructure truly automated.--Please follow the installation instructions below to integrate this Pack into your infrastructure.-------## What's Included--| Component | File | Purpose |-|-----------|------|---------|-| Security validator | `hooks/security-validator.ts` | Block dangerous commands before execution |-| Session initializer | `hooks/initialize-session.ts` | Set up session context and markers |-| Context loader | `hooks/load-core-context.ts` | Load CORE skill at session start |-| Tab title updater | `hooks/update-tab-titles.ts` | Update terminal tabs with task context |-| Observability lib | `hooks/lib/observability.ts` | Event logging and dashboard integration |--**Summary:**-- **Files created:** 5-- **Hooks registered:** 4 (PreToolUse, SessionStart ×2, UserPromptSubmit)-- **Dependencies:** None (foundation pack)-------## The Concept and/or Problem--Claude Code fires events throughout its operation, but by default nothing listens to them:--- **PreToolUse**: Before any tool runs - opportunity to validate, block, or modify-- **PostToolUse**: After any tool runs - opportunity to capture, log, or react-- **Stop**: When the agent finishes responding - opportunity to capture work-- **SessionStart**: When a new session begins - opportunity to initialize-- **SessionEnd**: When a session closes - opportunity to summarize-- **UserPromptSubmit**: When the user sends a message - opportunity to process--Without a hook system:-- Dangerous commands execute without validation-- Sessions start cold without context-- No automation layer between events and actions-- Each capability must be built from scratch--**The Problem:**--Claude Code's hook system is powerful but undocumented in practice. You can configure hooks in settings.json, but:-- What events are available?-- What data does each event provide?-- How do you write hooks that never block or crash?-- How do you chain multiple hooks together?--**The Opportunity:**--Hooks are the foundation for building intelligent AI infrastructure. Once you understand the event model, you can:-- Add security validation to every command-- Inject context at the right moments-- Capture every piece of work automatically-- Integrate with external systems (dashboards, notifications, analytics)--## The Solution--The Kai Hook System provides a complete framework for event-driven automation:--**Core Architecture:**--```-$PAI_DIR/-├── hooks/ # Hook implementations-│ ├── security-validator.ts # PreToolUse: Block dangerous commands-│ ├── initialize-session.ts # SessionStart: Session setup-│ ├── load-core-context.ts # SessionStart: Context injection-│ ├── update-tab-titles.ts # UserPromptSubmit: Tab automation-│ └── lib/ # Shared libraries-│ └── observability.ts # Dashboard integration-└── settings.json # Hook configuration-```--**Hook Event Types:**--| Event | When It Fires | Use Cases |-|-------|---------------|-----------|-| `PreToolUse` | Before a tool executes | Security validation, command modification, blocking |-| `PostToolUse` | After a tool executes | Logging, capturing output, triggering actions |-| `Stop` | Main agent finishes | Capture work summaries, voice notifications |-| `SubagentStop` | Subagent finishes | Capture agent outputs, route to categories |-| `SessionStart` | New session begins | Load context, initialize state |-| `SessionEnd` | Session closes | Summarize work, cleanup |-| `UserPromptSubmit` | User sends message | Process input, update UI |-| `PreCompact` | Before context compaction | Save important context |--**Design Principles:**--1. **Never Block**: Hooks must always exit 0 - never crash Claude Code-2. **Fail Silently**: Errors are logged but don't interrupt work-3. **Fast Execution**: Hooks should complete in milliseconds-4. **Stdin/Stdout**: Events come via stdin JSON, output via stdout-5. **Composable**: Multiple hooks can chain on the same event--**The Key Insight:**--Hooks are middleware for your AI. They sit between Claude Code's event system and your custom logic. By instrumenting the event stream, you gain complete visibility and control over your AI's operations.-------## What Makes This Different--The hook system's power comes from its **event-driven middleware pattern** - a layered architecture that intercepts, processes, and extends every AI operation without modifying Claude Code itself.--```-┌─────────────────────────────────────────────────────────────────────────┐-│ HOOK SYSTEM ARCHITECTURE │-├─────────────────────────────────────────────────────────────────────────┤-│ │-│ ┌──────────────┐ │-│ │ Claude Code │ ──► Events fire at every operation │-│ └──────┬───────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ LAYER 1: Event Stream │ │-│ │ SessionStart ─► PreToolUse ─► PostToolUse ─► Stop ─► SessionEnd │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ LAYER 2: Hook Registry │ │-│ │ settings.json defines which hooks fire on which events │ │-│ │ Matchers filter by tool name (Bash, Edit, *) or context │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ LAYER 3: Hook Implementations │ │-│ │ TypeScript files that process events and take actions │ │-│ │ security-validator.ts │ initialize-session.ts │ update-tabs.ts │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ LAYER 4: Shared Libraries │ │-│ │ Common utilities: observability.ts, prosody-enhancer.ts │ │-│ │ Fail-safe patterns, logging, integration helpers │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ LAYER 5: External Integrations │ │-│ │ Observability dashboards, voice servers, notification systems │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │-└─────────────────────────────────────────────────────────────────────────┘-```--### How Data Flows Through the System--**Example: User runs `rm -rf important/`**--```-1. Claude Code invokes Bash tool- │- ▼-2. PreToolUse event fires with payload:- { tool_name: "Bash", tool_input: { command: "rm -rf important/" } }- │- ▼-3. settings.json routes to security-validator.ts (matcher: "Bash")- │- ▼-4. Hook receives JSON via stdin, pattern-matches against attack tiers- │- ▼-5. MATCH: Catastrophic deletion pattern detected- │- ▼-6. Hook exits with code 2 (BLOCK) + outputs warning message- │- ▼-7. Claude Code sees exit 2, BLOCKS the command- │- ▼-8. User sees: "🚨 BLOCKED: Catastrophic deletion detected"-```--### Why This Architecture Matters--**1. Separation of Concerns**-- Event stream (Claude Code) is separate from hook logic (your code)-- Registration (settings.json) is separate from implementation (.ts files)-- Each hook does one thing well (UNIX philosophy)--**2. Fail-Safe by Design**-- Hooks NEVER crash Claude Code (exit 0 on errors)-- External integrations fail silently (observability down? keep working)-- Fast execution (milliseconds, not seconds)--**3. Composable Pipeline**-- Multiple hooks can chain on the same event-- Each hook processes independently-- Order defined in settings.json--**4. Deterministic Behavior**-- Same event + same hook = same outcome-- Pattern matching is explicit, not fuzzy-- Exit codes have precise meanings (0=allow, 2=block)--**5. Zero-Overhead Extensibility**-- Add new hooks without modifying existing ones-- Add new event handlers without touching Claude Code-- Shared libraries reduce duplication--### What Problems This Architecture Prevents--| Problem | How Hooks Solve It |-|---------|-------------------|-| Dangerous commands execute | PreToolUse validates before execution |-| Sessions start cold | SessionStart injects context automatically |-| Work disappears | Stop/SubagentStop capture everything |-| No visibility into operations | PostToolUse logs to observability |-| UI doesn't show context | UserPromptSubmit updates tab titles |--### The Fundamental Insight--**Naive approach:** Build safety/automation INTO the AI prompts-- Fragile (prompts can be ignored)-- Inconsistent (varies by session)-- Invisible (no audit trail)--**Hook approach:** Build safety/automation AROUND the AI as middleware-- Robust (code can't be prompt-injected)-- Consistent (same code runs every time)-- Observable (events logged, actions traced)--The hook system transforms Claude Code from a standalone tool into an **observable, controllable, extensible infrastructure**. Every operation can be validated, logged, modified, or blocked. This is the foundation that enables all other PAI capabilities.-------## Why This Is Different--This sounds similar to Claude Code's built-in hooks in settings.json, which also intercept events. What makes this approach different?--Claude Code exposes hook events but provides no framework for using them effectively. You get raw events with no patterns for security validation, no libraries for safe execution, no templates for common use cases. The Kai Hook System provides production-ready hook implementations that transform these raw events into intelligent automation. Every hook follows fail-safe patterns that never block agent work, with shared libraries for observability, logging, and integration.--- Production-ready security validation for every Bash command-- Fail-safe patterns ensure hooks never block work-- Shared libraries for observability and logging included-- Complete event documentation with practical code examples-------## Installation--### Prerequisites--- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`-- **Claude Code** (or compatible agent system with hook support)-- **Write access** to `$PAI_DIR/` (or your PAI directory)-------### Pre-Installation: System Analysis--**IMPORTANT:** Before installing, analyze the current system state to detect conflicts and determine the appropriate installation strategy.--#### Step 0.1: Detect Current Configuration--Run these commands to understand your current system:--```bash-# 1. Check if PAI_DIR is set-echo "PAI_DIR: ${PAI_DIR:-'NOT SET - will use ~/.config/pai'}"--# 2. Check for existing PAI directory-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"-if [ -d "$PAI_CHECK" ]; then- echo "⚠️ PAI directory EXISTS at: $PAI_CHECK"- echo "Contents:"- ls -la "$PAI_CHECK" 2>/dev/null || echo " (empty or inaccessible)"-else- echo "✓ PAI directory does not exist (clean install)"-fi--# 3. Check for existing hooks directory-if [ -d "$PAI_CHECK/hooks" ]; then- echo "⚠️ Hooks directory EXISTS"- echo "Existing hooks:"- ls -la "$PAI_CHECK/hooks"/*.ts 2>/dev/null || echo " (no .ts files)"-else- echo "✓ No existing hooks directory"-fi--# 4. Check Claude settings for existing hooks-CLAUDE_SETTINGS="$HOME/.claude/settings.json"-if [ -f "$CLAUDE_SETTINGS" ]; then- echo "Claude settings.json EXISTS"- if grep -q '"hooks"' "$CLAUDE_SETTINGS" 2>/dev/null; then- echo "⚠️ Existing hooks configuration found:"- grep -A 20 '"hooks"' "$CLAUDE_SETTINGS" | head -25- else- echo "✓ No hooks configured in settings.json"- fi-else- echo "✓ No Claude settings.json (will be created)"-fi--# 5. Check environment variables-echo ""-echo "Environment variables:"-echo " DA: ${DA:-'NOT SET'}"-echo " TIME_ZONE: ${TIME_ZONE:-'NOT SET'}"-echo " PAI_SOURCE_APP: ${PAI_SOURCE_APP:-'NOT SET'}"-```--#### Step 0.2: Conflict Resolution Matrix--Based on the detection above, follow the appropriate path:--| Scenario | Existing State | Action |-|----------|---------------|--------|-| **Clean Install** | No PAI_DIR, no hooks | Proceed normally with Step 1 |-| **PAI Directory Exists** | Directory with files | Review files, backup if needed, then proceed |-| **Hooks Exist** | Files in `$PAI_DIR/hooks/` | Merge new hooks alongside existing, or backup and replace |-| **Claude Settings Has Hooks** | `settings.json` has hook config | **MERGE** - add new hooks to existing array |-| **Environment Variables Set** | PAI_DIR, DA already defined | Use existing values or update in shell profile |--#### Step 0.3: Backup Existing Configuration (If Needed)--If conflicts were detected, create a backup before proceeding:--```bash-# Create timestamped backup-BACKUP_DIR="$HOME/.pai-backup/$(date +%Y%m%d-%H%M%S)"-mkdir -p "$BACKUP_DIR"--# Backup PAI directory if exists-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"-if [ -d "$PAI_CHECK" ]; then- cp -r "$PAI_CHECK" "$BACKUP_DIR/pai"- echo "✓ Backed up PAI directory to $BACKUP_DIR/pai"-fi--# Backup Claude settings if exists-if [ -f "$HOME/.claude/settings.json" ]; then- cp "$HOME/.claude/settings.json" "$BACKUP_DIR/settings.json"- echo "✓ Backed up settings.json to $BACKUP_DIR/settings.json"-fi--echo "Backup complete: $BACKUP_DIR"-```--#### Step 0.4: Set Required Environment Variables--**If you used the Kai Bundle wizard:** Environment variables are already configured in `$PAI_DIR/.env` - skip to Step 1.--**For manual installation:** Configure these in your shell profile (`~/.zshrc` or `~/.bashrc`):--```bash-# Add to your shell profile-export PAI_DIR="${HOME}/.config/pai"-export DA="PAI" # Your AI assistant name-export TIME_ZONE="America/Los_Angeles" # Your timezone-export PAI_SOURCE_APP="${DA}"--# Reload your shell-source ~/.zshrc # or ~/.bashrc-```--**Alternative:** Create a `.env` file in your PAI directory:--```bash-# $PAI_DIR/.env-DA="PAI"-PAI_DIR="${HOME}/.config/pai"-TIME_ZONE="America/Los_Angeles"-```--**After completing system analysis, proceed to Step 1.**-------### Step 1: Create Directory Structure--```bash-# Create required directories-mkdir -p $PAI_DIR/hooks/lib--# Verify structure-ls -la $PAI_DIR/hooks/-```-------### Step 2: Create Library Files--#### 2.1: Create observability.ts--This library enables integration with observability dashboards.--```typescript-// $PAI_DIR/hooks/lib/observability.ts-// Sends hook events to observability dashboards--export interface ObservabilityEvent {- source_app: string;- session_id: string;- hook_event_type: 'PreToolUse' | 'PostToolUse' | 'UserPromptSubmit' | 'Notification' | 'Stop' | 'SubagentStop' | 'SessionStart' | 'SessionEnd' | 'PreCompact';- timestamp: string;- transcript_path?: string;- summary?: string;- tool_name?: string;- tool_input?: any;- tool_output?: any;- agent_type?: string;- model?: string;- [key: string]: any;-}--/**- * Send event to observability dashboard- * Fails silently if dashboard is not running - doesn't block hook execution- */-export async function sendEventToObservability(event: ObservabilityEvent): Promise<void> {- const dashboardUrl = process.env.PAI_OBSERVABILITY_URL || 'http://localhost:4000/events';-- try {- const response = await fetch(dashboardUrl, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'User-Agent': 'PAI-Hook/1.0'- },- body: JSON.stringify(event),- });-- if (!response.ok) {- // Log error but don't throw - dashboard may be offline- console.error(`Observability server returned status: ${response.status}`);- }- } catch (error) {- // Fail silently - dashboard may not be running- // This is intentional - hooks should never fail due to observability issues- }-}--/**- * Helper to get current timestamp in ISO format- */-export function getCurrentTimestamp(): string {- return new Date().toISOString();-}--/**- * Helper to get source app name from environment- */-export function getSourceApp(): string {- return process.env.PAI_SOURCE_APP || process.env.DA || 'PAI';-}-```-------### Step 3: Create Hook Files--#### 3.1: Create security-validator.ts (PreToolUse Security)--This hook validates commands before execution and blocks dangerous operations.--```typescript-#!/usr/bin/env bun-// $PAI_DIR/hooks/security-validator.ts-// PreToolUse hook: Validates commands and blocks dangerous operations--import { sendEventToObservability, getCurrentTimestamp, getSourceApp } from './lib/observability';--interface PreToolUsePayload {- session_id: string;- tool_name: string;- tool_input: Record<string, any>;-}--// Attack pattern categories-const ATTACK_PATTERNS = {- // Tier 1: Catastrophic - Always block- catastrophic: {- patterns: [- /rm\s+(-rf?|--recursive)\s+[\/~]/i, // rm -rf /- /rm\s+(-rf?|--recursive)\s+\*/i, // rm -rf *- />\s*\/dev\/sd[a-z]/i, // Overwrite disk- /mkfs\./i, // Format filesystem- /dd\s+if=.*of=\/dev/i, // dd to device- ],- action: 'block',- message: '🚨 BLOCKED: Catastrophic deletion/destruction detected'- },-- // Tier 2: Reverse shells - Always block- reverseShell: {- patterns: [- /bash\s+-i\s+>&\s*\/dev\/tcp/i, // Bash reverse shell- /nc\s+(-e|--exec)\s+\/bin\/(ba)?sh/i, // Netcat shell- /python.*socket.*connect/i, // Python socket- /perl.*socket.*connect/i, // Perl socket- /ruby.*TCPSocket/i, // Ruby socket- /php.*fsockopen/i, // PHP socket- /socat.*exec/i, // Socat exec- /\|\s*\/bin\/(ba)?sh/i, // Pipe to shell- ],- action: 'block',- message: '🚨 BLOCKED: Reverse shell pattern detected'- },-- // Tier 3: Credential theft - Always block- credentialTheft: {- patterns: [- /curl.*\|\s*(ba)?sh/i, // curl pipe to shell- /wget.*\|\s*(ba)?sh/i, // wget pipe to shell- /curl.*(-o|--output).*&&.*chmod.*\+x/i, // Download and execute- /base64\s+-d.*\|\s*(ba)?sh/i, // Base64 decode to shell- ],- action: 'block',- message: '🚨 BLOCKED: Remote code execution pattern detected'- },-- // Tier 4: Prompt injection indicators - Block and log- promptInjection: {- patterns: [- /ignore\s+(all\s+)?previous\s+instructions/i,- /disregard\s+(all\s+)?prior\s+instructions/i,- /you\s+are\s+now\s+(in\s+)?[a-z]+\s+mode/i,- /new\s+instruction[s]?:/i,- /system\s+prompt:/i,- /\[INST\]/i, // LLM injection- /<\|im_start\|>/i, // ChatML injection- ],- action: 'block',- message: '🚨 BLOCKED: Prompt injection pattern detected - logging incident'- },-- // Tier 5: Environment manipulation - Warn- envManipulation: {- patterns: [- /export\s+(ANTHROPIC|OPENAI|AWS|AZURE)_/i, // API key export- /echo\s+\$\{?(ANTHROPIC|OPENAI)_/i, // Echo API keys- /env\s*\|.*KEY/i, // Dump env with keys- /printenv.*KEY/i, // Print env keys- ],- action: 'warn',- message: '⚠️ WARNING: Environment/credential access detected'- },-- // Tier 6: Git dangerous operations - Require confirmation- gitDangerous: {- patterns: [- /git\s+push.*(-f|--force)/i, // Force push- /git\s+reset\s+--hard/i, // Hard reset- /git\s+clean\s+-fd/i, // Clean untracked- /git\s+checkout\s+--\s+\./i, // Discard all changes- ],- action: 'confirm',- message: '⚠️ CONFIRM: Potentially destructive git operation'- },-- // Tier 7: System modification - Log- systemMod: {- patterns: [- /chmod\s+777/i, // World writable- /chown\s+root/i, // Change to root- /sudo\s+/i, // Sudo usage- /systemctl\s+(stop|disable)/i, // Stop services- ],- action: 'log',- message: '📝 LOGGED: System modification command'- },-- // Tier 8: Network operations - Log- network: {- patterns: [- /ssh\s+/i, // SSH connections- /scp\s+/i, // SCP transfers- /rsync.*:/i, // Rsync remote- /curl\s+(-X\s+POST|--data)/i, // POST requests- ],- action: 'log',- message: '📝 LOGGED: Network operation'- },-- // Tier 9: Data exfiltration patterns - Block- exfiltration: {- patterns: [- /curl.*(@|--upload-file)/i, // Upload file- /tar.*\|.*curl/i, // Tar and send- /zip.*\|.*nc/i, // Zip and netcat- ],- action: 'block',- message: '🚨 BLOCKED: Data exfiltration pattern detected'- },-- // Tier 10: PAI-specific protection - Block- paiProtection: {- patterns: [- /rm.*\.config\/pai/i, // Delete PAI config- /rm.*\.claude/i, // Delete Claude config- /git\s+push.*PAI.*public/i, // Push PAI to public- ],- action: 'block',- message: '🚨 BLOCKED: PAI infrastructure protection triggered'- }-};--function validateCommand(command: string): { allowed: boolean; message?: string; action?: string } {- // Fast path: Most commands are safe- if (!command || command.length < 3) {- return { allowed: true };- }-- // Check each tier- for (const [tierName, tier] of Object.entries(ATTACK_PATTERNS)) {- for (const pattern of tier.patterns) {- if (pattern.test(command)) {- const result = {- allowed: tier.action !== 'block',- message: tier.message,- action: tier.action- };-- // Log security event- console.error(`[Security] ${tierName}: ${tier.message}`);- console.error(`[Security] Command: ${command.substring(0, 100)}...`);-- return result;- }- }- }-- return { allowed: true };-}--async function main() {- try {- const stdinData = await Bun.stdin.text();- if (!stdinData.trim()) {- process.exit(0);- }-- const payload: PreToolUsePayload = JSON.parse(stdinData);-- // Only validate Bash commands- if (payload.tool_name !== 'Bash') {- process.exit(0);- }-- const command = payload.tool_input?.command;- if (!command) {- process.exit(0);- }-- const validation = validateCommand(command);-- // Send to observability if configured- if (validation.action) {- await sendEventToObservability({- source_app: getSourceApp(),- session_id: payload.session_id,- hook_event_type: 'PreToolUse',- timestamp: getCurrentTimestamp(),- tool_name: 'Bash',- tool_input: { command: command.substring(0, 200) },- security_action: validation.action,- security_message: validation.message- });- }-- if (!validation.allowed) {- // Output the block message - Claude Code will see this- console.log(validation.message);- console.log(`Command blocked: ${command.substring(0, 100)}...`);-- // Exit with code 2 to signal block (Claude Code specific)- process.exit(2);- }-- // Log warnings but allow execution- if (validation.action === 'warn' || validation.action === 'confirm') {- console.log(validation.message);- }-- } catch (error) {- // Never crash - log error and allow command- console.error('Security validator error:', error);- }-- // Exit 0 = allow the command- process.exit(0);-}--main();-```--#### 3.2: Create initialize-session.ts (SessionStart)--This hook runs at session start to initialize state and environment.--```typescript-#!/usr/bin/env bun-// $PAI_DIR/hooks/initialize-session.ts-// SessionStart hook: Initialize session state and environment--import { existsSync, writeFileSync, mkdirSync } from 'fs';-import { join } from 'path';-import { homedir } from 'os';-import { sendEventToObservability, getCurrentTimestamp, getSourceApp } from './lib/observability';--interface SessionStartPayload {- session_id: string;- cwd?: string;- [key: string]: any;-}--function getLocalTimestamp(): string {- const date = new Date();- const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;-- try {- const localDate = new Date(date.toLocaleString('en-US', { timeZone: tz }));- const year = localDate.getFullYear();- const month = String(localDate.getMonth() + 1).padStart(2, '0');- const day = String(localDate.getDate()).padStart(2, '0');- const hours = String(localDate.getHours()).padStart(2, '0');- const minutes = String(localDate.getMinutes()).padStart(2, '0');- const seconds = String(localDate.getSeconds()).padStart(2, '0');-- return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;- } catch {- return new Date().toISOString();- }-}--function setTabTitle(title: string): void {- // OSC escape sequence for terminal tab title- const tabEscape = `\x1b]1;${title}\x07`;- const windowEscape = `\x1b]2;${title}\x07`;-- process.stderr.write(tabEscape);- process.stderr.write(windowEscape);-}--function getProjectName(cwd: string | undefined): string {- if (!cwd) return 'Session';-- // Extract project name from path- const parts = cwd.split('/').filter(p => p);-- // Look for common project indicators- const projectIndicators = ['Projects', 'projects', 'src', 'repos', 'code'];- for (let i = parts.length - 1; i >= 0; i--) {- if (projectIndicators.includes(parts[i]) && parts[i + 1]) {- return parts[i + 1];- }- }-- // Default to last directory component- return parts[parts.length - 1] || 'Session';-}--async function checkForUpdates(): Promise<void> {- // Optional: Check for Claude Code updates in background- // This is non-blocking and fails silently- try {- const proc = Bun.spawn(['claude', '--version'], {- stdout: 'pipe',- stderr: 'pipe'- });-- const output = await new Response(proc.stdout).text();- const version = output.trim().match(/[\d.]+/)?.[0];-- if (version) {- // Could compare against known latest version- // For now, just log it- console.error(`[PAI] Claude Code version: ${version}`);- }- } catch {- // Silently ignore - version check is optional- }-}--async function main() {- try {- const stdinData = await Bun.stdin.text();- if (!stdinData.trim()) {- process.exit(0);- }-- const payload: SessionStartPayload = JSON.parse(stdinData);- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');-- // 1. Set initial tab title- const projectName = getProjectName(payload.cwd);- setTabTitle(`🤖 ${projectName}`);-- // 2. Ensure required directories exist- const requiredDirs = [- join(paiDir, 'hooks', 'lib'),- join(paiDir, 'history', 'sessions'),- join(paiDir, 'history', 'learnings'),- join(paiDir, 'history', 'research'),- ];-- for (const dir of requiredDirs) {- if (!existsSync(dir)) {- mkdirSync(dir, { recursive: true });- }- }-- // 3. Create session marker file (optional - for tracking)- const sessionFile = join(paiDir, '.current-session');- writeFileSync(sessionFile, JSON.stringify({- session_id: payload.session_id,- started: getLocalTimestamp(),- cwd: payload.cwd,- project: projectName- }, null, 2));-- // 4. Send to observability dashboard- await sendEventToObservability({- source_app: getSourceApp(),- session_id: payload.session_id,- hook_event_type: 'SessionStart',- timestamp: getCurrentTimestamp(),- cwd: payload.cwd,- project: projectName- });-- // 5. Background version check (non-blocking)- checkForUpdates().catch(() => {});-- // Output session info- console.error(`[PAI] Session initialized: ${projectName}`);- console.error(`[PAI] Time: ${getLocalTimestamp()}`);-- } catch (error) {- // Never crash - just log- console.error('Session initialization error:', error);- }-- process.exit(0);-}--main();-```--#### 3.3: Create load-core-context.ts (SessionStart Context Injection)--This hook loads skill definitions into the AI's context at session start.--```typescript-#!/usr/bin/env bun-// $PAI_DIR/hooks/load-core-context.ts-// SessionStart hook: Inject skill/context files into Claude's context--import { existsSync, readFileSync } from 'fs';-import { join } from 'path';-import { homedir } from 'os';--interface SessionStartPayload {- session_id: string;- [key: string]: any;-}--function isSubagentSession(): boolean {- // Check for subagent indicators- // Subagents shouldn't load full context (they get it from parent)- return process.env.CLAUDE_CODE_AGENT !== undefined ||- process.env.SUBAGENT === 'true';-}--function getLocalTimestamp(): string {- const date = new Date();- const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;-- try {- const localDate = new Date(date.toLocaleString('en-US', { timeZone: tz }));- const year = localDate.getFullYear();- const month = String(localDate.getMonth() + 1).padStart(2, '0');- const day = String(localDate.getDate()).padStart(2, '0');- const hours = String(localDate.getHours()).padStart(2, '0');- const minutes = String(localDate.getMinutes()).padStart(2, '0');- const seconds = String(localDate.getSeconds()).padStart(2, '0');-- return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} PST`;- } catch {- return new Date().toISOString();- }-}--async function main() {- try {- // Skip for subagents - they get context from parent- if (isSubagentSession()) {- process.exit(0);- }-- const stdinData = await Bun.stdin.text();- if (!stdinData.trim()) {- process.exit(0);- }-- const payload: SessionStartPayload = JSON.parse(stdinData);- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');-- // Look for CORE skill to load- // The CORE skill contains identity, response format, and operating principles- const coreSkillPath = join(paiDir, 'skills', 'CORE', 'SKILL.md');-- if (!existsSync(coreSkillPath)) {- // No CORE skill installed - that's fine- console.error('[PAI] No CORE skill found - skipping context injection');- process.exit(0);- }-- // Read the skill content- const skillContent = readFileSync(coreSkillPath, 'utf-8');-- // Output as system-reminder for Claude to process- // This format is recognized by Claude Code- const output = `<system-reminder>-PAI CORE CONTEXT (Auto-loaded at Session Start)--📅 CURRENT DATE/TIME: ${getLocalTimestamp()}--The following context has been loaded from ${coreSkillPath}:--${skillContent}--This context is now active for this session. Follow all instructions, preferences, and guidelines contained above.-</system-reminder>--✅ PAI Context successfully loaded...`;-- // Output goes to stdout - Claude Code will see it- console.log(output);-- } catch (error) {- // Never crash - just skip- console.error('Context loading error:', error);- }-- process.exit(0);-}--main();-```--#### 3.4: Create update-tab-titles.ts (UserPromptSubmit)--This hook updates terminal tab titles with task context.--```typescript-#!/usr/bin/env bun-// $PAI_DIR/hooks/update-tab-titles.ts-// UserPromptSubmit hook: Update terminal tab title with task context--interface UserPromptPayload {- session_id: string;- prompt?: string;- message?: string;- [key: string]: any;-}--function setTabTitle(title: string): void {- // OSC escape sequences for terminal tab and window titles- const tabEscape = `\x1b]1;${title}\x07`;- const windowEscape = `\x1b]2;${title}\x07`;-- process.stderr.write(tabEscape);- process.stderr.write(windowEscape);-}--function extractTaskKeywords(prompt: string): string {- // Remove common filler words- const stopWords = new Set([- 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',- 'of', 'with', 'by', 'from', 'is', 'are', 'was', 'were', 'be', 'been',- 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',- 'could', 'should', 'may', 'might', 'must', 'can', 'this', 'that',- 'these', 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me',- 'my', 'your', 'please', 'help', 'want', 'need', 'like', 'just'- ]);-- // Clean and tokenize- const words = prompt- .toLowerCase()- .replace(/[^\w\s-]/g, ' ')- .split(/\s+/)- .filter(word => word.length > 2 && !stopWords.has(word));-- // Take first 3-4 significant words- const keywords = words.slice(0, 4);-- if (keywords.length === 0) {- return 'Working';- }-- // Capitalize first word- keywords[0] = keywords[0].charAt(0).toUpperCase() + keywords[0].slice(1);-- return keywords.join(' ');-}--function launchBackgroundSummarization(prompt: string, sessionId: string): void {- // Optional: Launch a background process to get a better title via AI- // This is fire-and-forget - doesn't block the hook-- // Skip if prompt is too short- if (prompt.length < 20) return;-- // This could call a fast model (e.g., Haiku) to summarize- // For now, we just use keyword extraction (instant)-- // Example of what background summarization would look like:- // Bun.spawn(['bun', 'run', 'summarize-task.ts', '--prompt', prompt], {- // stdout: 'ignore',- // stderr: 'ignore'- // });-}--async function main() {- try {- const stdinData = await Bun.stdin.text();- if (!stdinData.trim()) {- process.exit(0);- }-- const payload: UserPromptPayload = JSON.parse(stdinData);- const prompt = payload.prompt || payload.message || '';-- if (!prompt || prompt.length < 3) {- process.exit(0);- }-- // Generate quick title from keywords (instant)- const keywords = extractTaskKeywords(prompt);- setTabTitle(`🤖 ${keywords}`);-- // Optionally launch background summarization for better title- launchBackgroundSummarization(prompt, payload.session_id);-- } catch (error) {- // Never crash- console.error('Tab title update error:', error);- }-- process.exit(0);-}--main();-```-------### Step 4: Register Hooks in settings.json--Claude Code looks for settings in `~/.claude/settings.json`. Add or merge the following hook configuration:--**File location:** `~/.claude/settings.json`--```json-{- "hooks": {- "SessionStart": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/initialize-session.ts"- },- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/load-core-context.ts"- }- ]- }- ],- "PreToolUse": [- {- "matcher": "Bash",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/security-validator.ts"- }- ]- }- ],- "UserPromptSubmit": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/update-tab-titles.ts"- }- ]- }- ]- }-}-```--**Important:** If you already have a settings.json, merge the hooks section with your existing configuration.-------### Step 5: Set Environment Variables (Optional)--**If you used the Kai Bundle wizard:** These are already in `$PAI_DIR/.env` - skip this step.--**For manual installation:** Add these to your shell profile (`~/.zshrc`, `~/.bashrc`, etc.):--```bash-# PAI configuration-export PAI_DIR="$HOME/.config/pai"-export TIME_ZONE="America/Los_Angeles" # Your timezone-export DA="PAI" # Your AI assistant name--# Optional: Observability dashboard URL-export PAI_OBSERVABILITY_URL="http://localhost:4000/events"--# Reload shell-source ~/.zshrc-```-------### Step 6: Verify Installation--```bash-# 1. Check all hooks exist-ls -la $PAI_DIR/hooks/*.ts-# Should show: security-validator.ts, initialize-session.ts,-# load-core-context.ts, update-tab-titles.ts--# 2. Check lib files exist-ls -la $PAI_DIR/hooks/lib/*.ts-# Should show: observability.ts--# 3. Test security validator with a safe command-echo '{"session_id":"test","tool_name":"Bash","tool_input":{"command":"ls -la"}}' | \- bun run $PAI_DIR/hooks/security-validator.ts-# Should exit 0 (allowed)--# 4. Test security validator catches dangerous patterns-# NOTE: This is SAFE - we're just piping JSON text to stdin, not executing anything-echo '{"session_id":"test","tool_name":"Bash","tool_input":{"command":"rm -rf /tmp/test"}}' | \- bun run $PAI_DIR/hooks/security-validator.ts-# Should exit 2 (blocked) and print warning--# 4b. Alternative: Canary file test (even safer feeling)-touch /tmp/pai-security-canary-# Now ask Claude: "delete /tmp/pai-security-canary"-# Hook should BLOCK, then verify canary survives:-ls /tmp/pai-security-canary # File should still exist--# 5. Test session initialization-echo '{"session_id":"test","cwd":"/Users/you/Projects/MyProject"}' | \- bun run $PAI_DIR/hooks/initialize-session.ts-# Should set tab title and create session marker--# 6. Restart Claude Code to activate hooks-```--**Success indicators:**-- Security validator blocks dangerous commands (exit code 2)-- Security validator allows safe commands (exit code 0)-- Tab title updates when you send prompts-- Session marker created at $PAI_DIR/.current-session-------## Hook Event Reference--### Event Payloads--Each hook receives a JSON payload via stdin:--**PreToolUse:**-```json-{- "session_id": "uuid",- "tool_name": "Bash",- "tool_input": {- "command": "ls -la"- }-}-```--**PostToolUse:**-```json-{- "session_id": "uuid",- "tool_name": "Bash",- "tool_input": { "command": "ls -la" },- "tool_output": "file1.txt\nfile2.txt"-}-```--**Stop:**-```json-{- "session_id": "uuid",- "stop_hook_active": true,- "transcript_path": "/path/to/transcript.jsonl",- "response": "The full assistant response text"-}-```--**SubagentStop:**-```json-{- "session_id": "uuid",- "transcript_path": "/path/to/agent-transcript.jsonl"-}-```--**SessionStart:**-```json-{- "session_id": "uuid",- "cwd": "/current/working/directory"-}-```--**SessionEnd:**-```json-{- "conversation_id": "uuid",- "timestamp": "2025-01-15T10:30:00Z"-}-```--**UserPromptSubmit:**-```json-{- "session_id": "uuid",- "prompt": "User's message text"-}-```--### Exit Codes--| Exit Code | Meaning | Use Case |-|-----------|---------|----------|-| 0 | Success / Allow | Hook completed, tool can proceed |-| 1 | Error (non-blocking) | Hook failed but don't block |-| 2 | Block | PreToolUse only: prevent tool execution |--### Matcher Patterns--Hooks can be filtered by tool name:--```json-{- "matcher": "Bash", // Only Bash tool- "matcher": "Edit", // Only Edit tool- "matcher": "Read|Write", // Read OR Write- "matcher": "*" // All tools-}-```-------## Example Usage--### Example 1: Adding a Custom Security Rule--```typescript-// Add to ATTACK_PATTERNS in security-validator.ts--customRule: {- patterns: [- /my-dangerous-pattern/i,- ],- action: 'block',- message: '🚨 BLOCKED: Custom security rule triggered'-}-```--### Example 2: Injecting Project-Specific Context--```typescript-// In load-core-context.ts, add project-specific context loading--const projectContextPath = join(payload.cwd, '.pai', 'context.md');-if (existsSync(projectContextPath)) {- const projectContext = readFileSync(projectContextPath, 'utf-8');- console.log(`<system-reminder>${projectContext}</system-reminder>`);-}-```--### Example 3: Custom Tab Title Format--```typescript-// Modify update-tab-titles.ts for custom format--function setTabTitle(title: string): void {- const prefix = process.env.PAI_TAB_PREFIX || '🤖';- const fullTitle = `${prefix} ${title}`;- // ... rest of function-}-```-------## Configuration--**Environment variables:**--| Variable | Default | Purpose |-|----------|---------|---------|-| `PAI_DIR` | `~/.config/pai` | Root PAI directory |-| `TIME_ZONE` | System default | Timestamp timezone |-| `DA` | `PAI` | AI assistant name |-| `PAI_OBSERVABILITY_URL` | `http://localhost:4000/events` | Dashboard endpoint |-| `PAI_TAB_PREFIX` | `🤖` | Tab title prefix |--**Settings file locations:**-- Claude Code: `~/.claude/settings.json`-- OpenCode: Check your platform's hook configuration-------## Customization--### Recommended Customization--**Define Your Security Policies**--The security validator comes with sensible defaults, but you'll want to customize the attack patterns for your specific environment and risk tolerance.--**What to Customize:** `$PAI_DIR/hooks/security-validator.ts`--**Why:** The default security patterns may be too strict or too lenient for your use case. For example, if you regularly work with Docker, you might want to allow certain commands that are blocked by default. Conversely, if you work with sensitive data, you may want to add stricter patterns.--**Process:**--1. **Review Current Patterns**- - Read through the `ATTACK_PATTERNS` object in security-validator.ts- - Identify patterns that trigger too often (false positives)- - Identify dangerous commands specific to your environment--2. **Add Custom Patterns**- ```typescript- // Add to ATTACK_PATTERNS in security-validator.ts- customProjectRules: {- patterns: [- /dangerous-command-for-your-project/i,- ],- action: 'block',- message: '🚨 BLOCKED: Custom project security rule'- }- ```--3. **Adjust Action Levels**- - `block` - Completely prevent execution- - `warn` - Allow but show warning- - `log` - Allow and log for review- - `confirm` - Require explicit confirmation--**Expected Outcome:** Security validation tailored to your specific workflow and risk profile.-------### Optional Customization--| Customization | File | Impact |-|---------------|------|--------|-| **Tab Title Format** | `update-tab-titles.ts` | Change the emoji prefix or title format |-| **Session Initialization** | `initialize-session.ts` | Add custom session startup actions |-| **Context Loading** | `load-core-context.ts` | Modify what context loads at session start |-| **Observability URL** | Environment variable | Point to different observability endpoint |--**Example: Custom Tab Title Prefix**--Edit `update-tab-titles.ts` to change the tab icon:--```typescript-function setTabTitle(title: string): void {- const prefix = process.env.PAI_TAB_PREFIX || '🤖'; // Change this- // ...-}-```--**Example: Add Project-Specific Context**--Edit `load-core-context.ts` to load project-specific context:--```typescript-// Check for project-specific context file-const projectContextPath = join(payload.cwd, '.pai', 'context.md');-if (existsSync(projectContextPath)) {- const projectContext = readFileSync(projectContextPath, 'utf-8');- console.log(`<system-reminder>${projectContext}</system-reminder>`);-}-```-------## Credits--- **Original concept**: Daniel Miessler - developed as part of Kai personal AI infrastructure-- **Contributors**: The PAI community-- **Hook system**: Anthropic Claude Code team--## Related Work--- **Claude Code Hooks** - The underlying event system this pack builds upon-- **Middleware patterns** - This pack implements event-driven middleware architecture--## Works Well With--- **kai-history-system** - Uses hooks for capturing session work and learnings-- **kai-voice-system** - Uses hooks for voice notification triggers-- **kai-core-install** - Uses SessionStart hooks for CORE skill context injection and response formatting--## Recommended--- **kai-history-system** - Capture all work automatically via Stop/SubagentStop hooks-- **kai-voice-system** - Add voice notifications to hook events--## Relationships--### Parent Of-- **kai-history-system** - History capture depends on hook events (Stop, SubagentStop)-- **kai-core-install** - Skill loading uses SessionStart hooks for CORE context injection-- **kai-voice-system** - Voice notifications triggered via hooks--### Child Of-*None - this is the foundation layer.*--### Sibling Of-*None - this is the foundation layer.*--### Part Of Collection-**Kai Core Bundle** - One of 4 foundational packs that together create the complete Kai personal AI infrastructure.-------## Changelog--### 1.0.0 - 2025-12-29-- Initial release-- Four core hooks: security-validator, initialize-session, load-core-context, update-tab-titles-- One lib file: observability-- Complete hook event reference documentation-- Security validation with 10 tiers of attack pattern detection-- Session initialization with tab title automation-- Context injection for skill loadingdiff --git a/Packs/kai-observability-server.md b/Packs/kai-observability-server.mddeleted file mode 100644index 283ddd3b..00000000--- a/Packs/kai-observability-server.md+++ /dev/null@@ -1,1730 +0,0 @@-----name: Kai Observability Server-pack-id: danielmiessler-kai-observability-server-core-v1.0.0-version: 1.0.0-author: danielmiessler-description: Real-time multi-agent activity monitoring dashboard with WebSocket streaming - see exactly what your AI agents are doing as they work-type: feature-purpose-type: [observability, monitoring, development, debugging]-platform: claude-code-dependencies: [kai-hook-system]-keywords: [observability, dashboard, monitoring, agents, websocket, streaming, events, debugging, visualization, real-time]------<p align="center">- <img src="icons/kai-observability-server-v2.png" alt="Kai Observability Server" width="256">-</p>--# Kai Observability Server (kai-observability-server)--> Real-time multi-agent activity monitoring dashboard - see exactly what your AI agents are doing as they work--## Installation Prompt-You are receiving a PAI Pack - a modular upgrade for AI agent systems.--**What is PAI?** See: [PAI Project Overview](../README.md#what-is-pai)--**What is a Pack?** See: [Pack System](../README.md#pack-system)--This Pack adds real-time monitoring capabilities to your AI infrastructure. The Observability Server streams every tool call, hook event, and agent action to a beautiful dashboard:--- **WebSocket Streaming**: Events appear instantly as they happen-- **Multi-Agent Tracking**: See activity across all agents (main, interns, researchers, etc.)-- **Event Timeline**: Chronological view of all operations-- **Agent Swim Lanes**: Compare activity between multiple agents-- **Zero Configuration**: Just start the server and go--**Core principle:** You can't improve what you can't see. This dashboard gives you complete visibility into your AI's operations.--**Dependency:** Requires the [kai-hook-system](kai-hook-system.md) pack to capture events.--Please follow the installation instructions below to integrate this Pack into your infrastructure.-------## What's Included--| Component | File | Purpose |-|-----------|------|---------|-| WebSocket server | `Observability/server/index.ts` | HTTP API + WebSocket streaming |-| File ingestion | `Observability/server/file-ingest.ts` | Watch JSONL and stream events |-| Type definitions | `Observability/server/types.ts` | TypeScript interfaces |-| Vue dashboard | `Observability/dashboard/App.vue` | Real-time monitoring UI |-| Event capture hook | `hooks/capture-all-events.ts` | Capture all events to JSONL |-| Metadata extraction | `hooks/lib/metadata-extraction.ts` | Agent instance tracking |--**Summary:**-- **Files created:** 8+ (server, dashboard, hooks)-- **Hooks registered:** 7 (all event types via capture-all-events)-- **Dependencies:** kai-hook-system (required)-------## The Concept and/or Problem--When running AI agents, especially multiple agents in parallel, you're flying blind:--- **What's happening now?** No visibility into real-time operations-- **Which agent did what?** When you spawn multiple agents, you lose track of their activity-- **Where did it fail?** No way to trace back through operations when something breaks-- **What was the sequence?** Tool calls happen fast - you can't see the order-- **How long did it take?** No performance visibility--**The Problem:**--Claude Code logs events through hooks, but the data just... sits there. You can grep through JSONL files after the fact, but that's like trying to debug by reading logs - tedious and slow.--Meanwhile, your agents are doing hundreds of operations:-- File reads and writes-- Bash commands executing-- Sub-agents spawning and completing-- API calls succeeding or failing--Without real-time visibility, you're working in the dark.--**The Opportunity:**--What if you could watch your AI infrastructure like a control room? Every operation visible. Every agent tracked. Every event timestamped and streaming live. That's what observability enables - complete operational awareness.--## The Solution--The Observability Server provides a complete monitoring stack:--**Architecture:**--```-$PAI_DIR/-├── observability/ # Observability infrastructure-│ ├── manage.sh # Control script (start/stop/restart)-│ └── apps/-│ ├── server/ # Backend (Bun + TypeScript)-│ │ ├── src/-│ │ │ ├── index.ts # HTTP + WebSocket server-│ │ │ ├── file-ingest.ts # JSONL file watcher-│ │ │ └── types.ts # TypeScript interfaces-│ │ └── package.json-│ └── client/ # Frontend (Vue 3 + Vite)-│ ├── src/-│ │ ├── App.vue # Main dashboard-│ │ └── components/ # UI components-│ └── package.json-├── hooks/-│ ├── capture-all-events.ts # Hook that logs all events-│ └── lib/-│ └── metadata-extraction.ts # Agent metadata extraction-└── history/- └── raw-outputs/- └── YYYY-MM/- └── YYYY-MM-DD_all-events.jsonl # Event storage-```--**Data Flow:**--```-┌──────────────────────────────────────────────────────────────────────────┐-│ OBSERVABILITY DATA FLOW │-├──────────────────────────────────────────────────────────────────────────┤-│ │-│ ┌──────────────┐ │-│ │ Claude Code │ ──► Hook events fire (PreToolUse, PostToolUse, etc.) │-│ └──────┬───────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ capture-all-events.ts (PostToolUse hook) │ │-│ │ Receives JSON via stdin → Appends to daily JSONL file │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ YYYY-MM-DD_all-events.jsonl (file storage) │ │-│ │ One line per event, organized by date in monthly directories │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ file-ingest.ts (server component) │ │-│ │ Watches file for changes → Parses new lines → Streams to WS │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ index.ts (Bun HTTP + WebSocket server) │ │-│ │ Port 4000 → WebSocket: /stream → HTTP: /events/* │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌──────────────────────────────────────────────────────────────────┐ │-│ │ Vue 3 Dashboard (Vite dev server) │ │-│ │ Port 5172 → Connects to WS → Renders real-time event timeline │ │-│ └──────────────────────────────────────────────────────────────────┘ │-│ │-└──────────────────────────────────────────────────────────────────────────┘-```--**Key Components:**--| Component | Purpose | Technology |-|-----------|---------|------------|-| `capture-all-events.ts` | Hook that captures ALL events to JSONL | TypeScript/Bun |-| `file-ingest.ts` | Watches JSONL file, streams new events | Node fs.watch |-| `index.ts` | HTTP API + WebSocket server | Bun.serve |-| `App.vue` | Main dashboard UI | Vue 3 + Tailwind |-| `manage.sh` | Start/stop/restart script | Bash |--**Design Principles:**--1. **No Database**: Events stream from files directly - no persistence overhead-2. **Fire and Forget**: Hook writes and exits fast - never blocks Claude Code-3. **Fresh Start**: Each server launch starts clean - no stale state-4. **In-Memory Only**: Recent events cached in memory, not stored in DB-5. **Graceful Degradation**: Dashboard down? Hooks still log. Server restarts? Just reload.-------## What Makes This Different--The observability system's power comes from its **file-based streaming architecture** - a simple but effective pattern that separates event capture from event display.--### Why File-Based Streaming?--**Naive approach:** Send events directly to a server via HTTP-- Complex: Need error handling, retries, connection management-- Fragile: Server down = events lost-- Blocking: Network latency affects hook performance--**File-based approach:** Write to local file, server watches and streams-- Simple: Just append to a file (atomic, fast, reliable)-- Robust: File persists even if server is down-- Non-blocking: File writes are fast, hook exits immediately-- Portable: JSONL files can be processed by any tool--### The Critical Insight--Hooks must NEVER block Claude Code. The file-based approach ensures:--1. Hook receives event via stdin-2. Hook appends one line to JSONL file-3. Hook exits immediately (exit 0)--Total time: ~1-2ms. Claude Code barely notices.--Meanwhile, the server:-1. Watches the JSONL file for changes-2. Reads only new lines (tracks file position)-3. Parses JSON and broadcasts to WebSocket clients--This decoupling means the expensive work (UI rendering, WebSocket management) happens outside the critical path.--### In-Memory Design--The server maintains only recent events in memory:--```typescript-const MAX_EVENTS = 1000;-const events: HookEvent[] = [];-```--Why? Because observability is about the NOW, not historical analysis:-- You want to see what's happening right now-- Old events can be analyzed from JSONL files if needed-- Memory stays bounded regardless of how long server runs--### Agent Session Tracking--One clever feature: the system tracks which agent is active:--```typescript-// Session-to-agent mapping-const agentSessions = new Map<string, string>();--// When Task tool spawns a subagent:-if (hookData.tool_name === 'Task' && hookData.tool_input?.subagent_type) {- agentName = hookData.tool_input.subagent_type;- setAgentForSession(sessionId, agentName);-}-```--This enables the dashboard to show "Intern is running" vs "Main agent is running" - crucial when you have multiple agents working in parallel.-------## Why This Is Different--This sounds similar to just tailing log files, which you could do with `tail -f`. What makes this approach different?--Raw log tailing gives you text that scrolls by too fast to read. The Observability Server transforms raw events into a structured, filterable, real-time dashboard. You can see which agent made each call, filter by tool type, watch activity patterns over time, and compare agents side-by-side. It's the difference between watching raw network packets vs using Wireshark.--- Real-time WebSocket streaming with sub-second latency-- Agent identification and tracking across sessions-- Beautiful Vue 3 dashboard with swimlane visualization-- Filterable by agent, tool type, and time range-- Zero configuration - just start and use-------## Installation--### Prerequisites--- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`-- **Node.js 18+** (for Vite dev server)-- **Claude Code** (or compatible agent system)-- **kai-hook-system** pack installed-- **Write access** to `$PAI_DIR/`-------### Pre-Installation: System Analysis--**IMPORTANT:** Before installing, verify the hook system is in place.--#### Step 0.1: Verify Hook System--```bash-# Check that kai-hook-system is installed-ls -la $PAI_DIR/hooks/-# Should show: security-validator.ts, initialize-session.ts, etc.--# Check that hooks are configured in Claude settings-grep -A 10 '"hooks"' ~/.claude/settings.json-# Should show PostToolUse hooks configured-```--#### Step 0.2: Check for Existing Observability--```bash-# Check if observability directory exists-if [ -d "$PAI_DIR/observability" ]; then- echo "⚠️ Observability directory EXISTS"- ls -la "$PAI_DIR/observability"-else- echo "✓ No existing observability (clean install)"-fi-```-------### Step 1: Create Directory Structure--```bash-# Create observability directories-mkdir -p $PAI_DIR/observability/apps/server/src-mkdir -p $PAI_DIR/observability/apps/client/src/components-mkdir -p $PAI_DIR/observability/apps/client/src/composables-mkdir -p $PAI_DIR/history/raw-outputs--# Create hooks lib directory if not exists-mkdir -p $PAI_DIR/hooks/lib--# Verify structure-ls -la $PAI_DIR/observability/-```-------### Step 2: Create the Event Capture Hook--This hook captures ALL events and writes them to a daily JSONL file.--#### 2.1: Create metadata-extraction.ts--```typescript-// $PAI_DIR/hooks/lib/metadata-extraction.ts-// Extracts agent instance metadata from Task tool calls--export interface AgentInstanceMetadata {- agent_instance_id?: string;- agent_type?: string;- instance_number?: number;- parent_session_id?: string;- parent_task_id?: string;-}--/**- * Extract agent instance ID from Task tool input- */-export function extractAgentInstanceId(- toolInput: any,- description?: string-): AgentInstanceMetadata {- const result: AgentInstanceMetadata = {};-- // Strategy 1: Extract from description [agent-type-N]- if (description) {- const descMatch = description.match(/\[([a-z-]+-researcher)-(\d+)\]/);- if (descMatch) {- result.agent_type = descMatch[1];- result.instance_number = parseInt(descMatch[2], 10);- result.agent_instance_id = `${result.agent_type}-${result.instance_number}`;- }- }-- // Strategy 2: Extract from prompt [AGENT_INSTANCE: ...]- if (!result.agent_instance_id && toolInput?.prompt && typeof toolInput.prompt === 'string') {- const promptMatch = toolInput.prompt.match(/\[AGENT_INSTANCE:\s*([^\]]+)\]/);- if (promptMatch) {- result.agent_instance_id = promptMatch[1].trim();- const parts = result.agent_instance_id.match(/^([a-z-]+)-(\d+)$/);- if (parts) {- result.agent_type = parts[1];- result.instance_number = parseInt(parts[2], 10);- }- }- }-- // Strategy 3: Extract parent session from prompt- if (toolInput?.prompt && typeof toolInput.prompt === 'string') {- const parentSessionMatch = toolInput.prompt.match(/\[PARENT_SESSION:\s*([^\]]+)\]/);- if (parentSessionMatch) {- result.parent_session_id = parentSessionMatch[1].trim();- }-- const parentTaskMatch = toolInput.prompt.match(/\[PARENT_TASK:\s*([^\]]+)\]/);- if (parentTaskMatch) {- result.parent_task_id = parentTaskMatch[1].trim();- }- }-- // Strategy 4: Fallback to subagent_type- if (!result.agent_type && toolInput?.subagent_type) {- result.agent_type = toolInput.subagent_type;- }-- return result;-}--/**- * Enrich event with agent metadata- */-export function enrichEventWithAgentMetadata(- event: any,- toolInput: any,- description?: string-): any {- const metadata = extractAgentInstanceId(toolInput, description);- const enrichedEvent = { ...event };-- if (metadata.agent_instance_id) enrichedEvent.agent_instance_id = metadata.agent_instance_id;- if (metadata.agent_type) enrichedEvent.agent_type = metadata.agent_type;- if (metadata.instance_number !== undefined) enrichedEvent.instance_number = metadata.instance_number;- if (metadata.parent_session_id) enrichedEvent.parent_session_id = metadata.parent_session_id;- if (metadata.parent_task_id) enrichedEvent.parent_task_id = metadata.parent_task_id;-- return enrichedEvent;-}--/**- * Check if a tool call is spawning a subagent- */-export function isAgentSpawningCall(toolName: string, toolInput: any): boolean {- return toolName === 'Task' && toolInput?.subagent_type !== undefined;-}-```--#### 2.2: Create capture-all-events.ts--```typescript-#!/usr/bin/env bun-// $PAI_DIR/hooks/capture-all-events.ts-// Captures ALL Claude Code hook events to JSONL--import { readFileSync, appendFileSync, mkdirSync, existsSync, writeFileSync } from 'fs';-import { join } from 'path';-import { homedir } from 'os';-import { enrichEventWithAgentMetadata, isAgentSpawningCall } from './lib/metadata-extraction';--interface HookEvent {- source_app: string;- session_id: string;- hook_event_type: string;- payload: Record<string, any>;- timestamp: number;- timestamp_local: string;-}--function getLocalTimestamp(): string {- const date = new Date();- const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;-- try {- const localDate = new Date(date.toLocaleString('en-US', { timeZone: tz }));- const year = localDate.getFullYear();- const month = String(localDate.getMonth() + 1).padStart(2, '0');- const day = String(localDate.getDate()).padStart(2, '0');- const hours = String(localDate.getHours()).padStart(2, '0');- const minutes = String(localDate.getMinutes()).padStart(2, '0');- const seconds = String(localDate.getSeconds()).padStart(2, '0');- return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;- } catch {- return new Date().toISOString();- }-}--function getEventsFilePath(): string {- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');- const now = new Date();- const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;- const localDate = new Date(now.toLocaleString('en-US', { timeZone: tz }));-- const year = localDate.getFullYear();- const month = String(localDate.getMonth() + 1).padStart(2, '0');- const day = String(localDate.getDate()).padStart(2, '0');-- const monthDir = join(paiDir, 'history', 'raw-outputs', `${year}-${month}`);-- if (!existsSync(monthDir)) {- mkdirSync(monthDir, { recursive: true });- }-- return join(monthDir, `${year}-${month}-${day}_all-events.jsonl`);-}--function getSessionMappingFile(): string {- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');- return join(paiDir, 'agent-sessions.json');-}--function getAgentForSession(sessionId: string): string {- try {- const mappingFile = getSessionMappingFile();- if (existsSync(mappingFile)) {- const mappings = JSON.parse(readFileSync(mappingFile, 'utf-8'));- return mappings[sessionId] || process.env.DA || 'main';- }- } catch {- // Ignore errors- }- return process.env.DA || 'main';-}--function setAgentForSession(sessionId: string, agentName: string): void {- try {- const mappingFile = getSessionMappingFile();- let mappings: Record<string, string> = {};-- if (existsSync(mappingFile)) {- mappings = JSON.parse(readFileSync(mappingFile, 'utf-8'));- }-- mappings[sessionId] = agentName;- writeFileSync(mappingFile, JSON.stringify(mappings, null, 2), 'utf-8');- } catch {- // Silently fail- }-}--async function main() {- try {- const args = process.argv.slice(2);- const eventTypeIndex = args.indexOf('--event-type');-- if (eventTypeIndex === -1) {- console.error('Missing --event-type argument');- process.exit(0);- }-- const eventType = args[eventTypeIndex + 1];- const stdinData = await Bun.stdin.text();- const hookData = JSON.parse(stdinData);-- const sessionId = hookData.session_id || 'main';- let agentName = getAgentForSession(sessionId);-- // Update agent mapping based on event type- if (hookData.tool_name === 'Task' && hookData.tool_input?.subagent_type) {- agentName = hookData.tool_input.subagent_type;- setAgentForSession(sessionId, agentName);- } else if (eventType === 'SubagentStop' || eventType === 'Stop') {- agentName = process.env.DA || 'main';- setAgentForSession(sessionId, agentName);- } else if (process.env.CLAUDE_CODE_AGENT) {- agentName = process.env.CLAUDE_CODE_AGENT;- setAgentForSession(sessionId, agentName);- } else if (hookData.agent_type) {- agentName = hookData.agent_type;- setAgentForSession(sessionId, agentName);- }-- let event: HookEvent = {- source_app: agentName,- session_id: hookData.session_id || 'main',- hook_event_type: eventType,- payload: hookData,- timestamp: Date.now(),- timestamp_local: getLocalTimestamp()- };-- // Enrich with agent instance metadata for Task calls- if (isAgentSpawningCall(hookData.tool_name, hookData.tool_input)) {- event = enrichEventWithAgentMetadata(event, hookData.tool_input, hookData.description);- }-- // Append to events file- const eventsFile = getEventsFilePath();- const jsonLine = JSON.stringify(event) + '\n';- appendFileSync(eventsFile, jsonLine, 'utf-8');-- } catch (error) {- console.error('Event capture error:', error);- }-- process.exit(0);-}--main();-```-------### Step 3: Create the Server--#### 3.1: Create server package.json--```json-// $PAI_DIR/observability/apps/server/package.json-{- "name": "pai-observability-server",- "version": "1.0.0",- "module": "src/index.ts",- "type": "module",- "private": true,- "scripts": {- "dev": "bun --watch src/index.ts",- "start": "bun src/index.ts"- },- "devDependencies": {- "@types/bun": "latest",- "typescript": "^5.8.3"- }-}-```--#### 3.2: Create server types.ts--```typescript-// $PAI_DIR/observability/apps/server/src/types.ts--export interface TodoItem {- content: string;- status: 'pending' | 'in_progress' | 'completed';- activeForm: string;-}--export interface HookEvent {- id?: number;- source_app: string;- session_id: string;- agent_name?: string;- hook_event_type: string;- payload: Record<string, any>;- summary?: string;- timestamp?: number;- todos?: TodoItem[];- completedTodos?: TodoItem[];-}--export interface FilterOptions {- source_apps: string[];- session_ids: string[];- hook_event_types: string[];-}-```--#### 3.3: Create file-ingest.ts--```typescript-// $PAI_DIR/observability/apps/server/src/file-ingest.ts-// File-based event streaming - watches JSONL files--import { watch, existsSync } from 'fs';-import { readFileSync } from 'fs';-import { join } from 'path';-import { homedir } from 'os';-import type { HookEvent } from './types';--const MAX_EVENTS = 1000;-const events: HookEvent[] = [];-const filePositions = new Map<string, number>();-const watchedFiles = new Set<string>();-let onEventsReceived: ((events: HookEvent[]) => void) | null = null;-const agentSessions = new Map<string, string>();-const sessionTodos = new Map<string, any[]>();--function getTodayEventsFile(): string {- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');- const now = new Date();- const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;-- try {- const localDate = new Date(now.toLocaleString('en-US', { timeZone: tz }));- const year = localDate.getFullYear();- const month = String(localDate.getMonth() + 1).padStart(2, '0');- const day = String(localDate.getDate()).padStart(2, '0');-- const monthDir = join(paiDir, 'history', 'raw-outputs', `${year}-${month}`);- return join(monthDir, `${year}-${month}-${day}_all-events.jsonl`);- } catch {- // Fallback to UTC- const year = now.getFullYear();- const month = String(now.getMonth() + 1).padStart(2, '0');- const day = String(now.getDate()).padStart(2, '0');- return join(paiDir, 'history', 'raw-outputs', `${year}-${month}`, `${year}-${month}-${day}_all-events.jsonl`);- }-}--function enrichEventWithAgentName(event: HookEvent): HookEvent {- if (event.hook_event_type === 'UserPromptSubmit') {- return { ...event, agent_name: 'User' };- }-- const mainAgentName = process.env.DA || 'main';- const subAgentTypes = ['artist', 'intern', 'engineer', 'pentester', 'architect', 'designer', 'qatester', 'researcher'];-- if (event.source_app && subAgentTypes.includes(event.source_app.toLowerCase())) {- const capitalizedName = event.source_app.charAt(0).toUpperCase() + event.source_app.slice(1);- return { ...event, agent_name: capitalizedName };- }-- const agentName = agentSessions.get(event.session_id) || mainAgentName;- return { ...event, agent_name: agentName };-}--function processTodoEvent(event: HookEvent): HookEvent[] {- if (event.payload.tool_name !== 'TodoWrite') {- return [event];- }-- const currentTodos = event.payload.tool_input?.todos || [];- const previousTodos = sessionTodos.get(event.session_id) || [];- const completedTodos = [];-- for (const currentTodo of currentTodos) {- if (currentTodo.status === 'completed') {- const prevTodo = previousTodos.find((t: any) => t.content === currentTodo.content);- if (!prevTodo || prevTodo.status !== 'completed') {- completedTodos.push(currentTodo);- }- }- }-- sessionTodos.set(event.session_id, currentTodos);- const events: HookEvent[] = [event];-- for (const completedTodo of completedTodos) {- const completionEvent: HookEvent = {- ...event,- id: event.id,- hook_event_type: 'Completed',- payload: { task: completedTodo.content },- summary: undefined,- timestamp: event.timestamp- };- events.push(completionEvent);- }-- return events;-}--function readNewEvents(filePath: string): HookEvent[] {- if (!existsSync(filePath)) return [];-- const lastPosition = filePositions.get(filePath) || 0;-- try {- const content = readFileSync(filePath, 'utf-8');- const newContent = content.slice(lastPosition);- filePositions.set(filePath, content.length);-- if (!newContent.trim()) return [];-- const lines = newContent.trim().split('\n');- const newEvents: HookEvent[] = [];-- for (const line of lines) {- if (!line.trim()) continue;-- try {- let event = JSON.parse(line);- event.id = events.length + newEvents.length + 1;- event = enrichEventWithAgentName(event);- const processedEvents = processTodoEvent(event);-- for (let i = 0; i < processedEvents.length; i++) {- processedEvents[i].id = events.length + newEvents.length + i + 1;- }- newEvents.push(...processedEvents);- } catch (error) {- console.error(`Failed to parse line: ${line.slice(0, 100)}...`, error);- }- }-- return newEvents;- } catch (error) {- console.error(`Error reading file ${filePath}:`, error);- return [];- }-}--function storeEvents(newEvents: HookEvent[]): void {- if (newEvents.length === 0) return;-- events.push(...newEvents);-- if (events.length > MAX_EVENTS) {- events.splice(0, events.length - MAX_EVENTS);- }-- console.log(`✅ Received ${newEvents.length} event(s) (${events.length} in memory)`);-- if (onEventsReceived) {- onEventsReceived(newEvents);- }-}--function loadAgentSessions(): void {- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');- const sessionsFile = join(paiDir, 'agent-sessions.json');-- if (!existsSync(sessionsFile)) {- console.log('⚠️ agent-sessions.json not found, agent names will use defaults');- return;- }-- try {- const content = readFileSync(sessionsFile, 'utf-8');- const data = JSON.parse(content);-- agentSessions.clear();- Object.entries(data).forEach(([sessionId, agentName]) => {- agentSessions.set(sessionId, agentName as string);- });-- console.log(`✅ Loaded ${agentSessions.size} agent sessions`);- } catch (error) {- console.error('❌ Error loading agent-sessions.json:', error);- }-}--function watchAgentSessions(): void {- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');- const sessionsFile = join(paiDir, 'agent-sessions.json');-- if (!existsSync(sessionsFile)) return;-- console.log('👀 Watching agent-sessions.json for changes');-- const watcher = watch(sessionsFile, (eventType) => {- if (eventType === 'change') {- console.log('🔄 agent-sessions.json changed, reloading...');- loadAgentSessions();- }- });-- watcher.on('error', (error) => {- console.error('❌ Error watching agent-sessions.json:', error);- });-}--function watchFile(filePath: string): void {- if (watchedFiles.has(filePath)) return;-- console.log(`👀 Watching: ${filePath}`);- watchedFiles.add(filePath);-- // Position at END of file - only read NEW events- if (existsSync(filePath)) {- const content = readFileSync(filePath, 'utf-8');- filePositions.set(filePath, content.length);- console.log(`📍 Positioned at end of file - only new events will be captured`);- }-- const watcher = watch(filePath, (eventType) => {- if (eventType === 'change') {- const newEvents = readNewEvents(filePath);- storeEvents(newEvents);- }- });-- watcher.on('error', (error) => {- console.error(`Error watching ${filePath}:`, error);- watchedFiles.delete(filePath);- });-}--export function startFileIngestion(callback?: (events: HookEvent[]) => void): void {- const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');-- console.log('🚀 Starting file-based event streaming (in-memory only)');- console.log(`📂 Reading from ${paiDir}/history/raw-outputs/`);-- if (callback) {- onEventsReceived = callback;- }-- loadAgentSessions();- watchAgentSessions();-- const todayFile = getTodayEventsFile();- watchFile(todayFile);-- // Check for new day's file every hour- setInterval(() => {- const newTodayFile = getTodayEventsFile();- if (!watchedFiles.has(newTodayFile)) {- console.log('📅 New day detected, watching new file');- watchFile(newTodayFile);- }- }, 60 * 60 * 1000);-- console.log('✅ File streaming started');-}--export function getRecentEvents(limit: number = 100): HookEvent[] {- return events.slice(-limit).reverse();-}--export function getFilterOptions() {- const sourceApps = new Set<string>();- const sessionIds = new Set<string>();- const hookEventTypes = new Set<string>();-- for (const event of events) {- if (event.source_app) sourceApps.add(event.source_app);- if (event.session_id) sessionIds.add(event.session_id);- if (event.hook_event_type) hookEventTypes.add(event.hook_event_type);- }-- return {- source_apps: Array.from(sourceApps).sort(),- session_ids: Array.from(sessionIds).slice(0, 100),- hook_event_types: Array.from(hookEventTypes).sort()- };-}-```--#### 3.4: Create index.ts (main server)--```typescript-// $PAI_DIR/observability/apps/server/src/index.ts-// HTTP + WebSocket server for observability dashboard--import { startFileIngestion, getRecentEvents, getFilterOptions } from './file-ingest';--const wsClients = new Set<any>();--// Start file-based ingestion with WebSocket broadcast callback-startFileIngestion((events) => {- events.forEach(event => {- const message = JSON.stringify({ type: 'event', data: event });- wsClients.forEach(client => {- try {- client.send(message);- } catch (err) {- wsClients.delete(client);- }- });- });-});--const server = Bun.serve({- port: 4000,-- async fetch(req: Request) {- const url = new URL(req.url);-- const headers = {- 'Access-Control-Allow-Origin': '*',- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',- 'Access-Control-Allow-Headers': 'Content-Type',- };-- if (req.method === 'OPTIONS') {- return new Response(null, { headers });- }-- // GET /events/filter-options- if (url.pathname === '/events/filter-options' && req.method === 'GET') {- const options = getFilterOptions();- return new Response(JSON.stringify(options), {- headers: { ...headers, 'Content-Type': 'application/json' }- });- }-- // GET /events/recent- if (url.pathname === '/events/recent' && req.method === 'GET') {- const limit = parseInt(url.searchParams.get('limit') || '100');- const events = getRecentEvents(limit);- return new Response(JSON.stringify(events), {- headers: { ...headers, 'Content-Type': 'application/json' }- });- }-- // GET /events/by-agent/:agentName- if (url.pathname.startsWith('/events/by-agent/') && req.method === 'GET') {- const agentName = decodeURIComponent(url.pathname.split('/')[3]);- const limit = parseInt(url.searchParams.get('limit') || '100');-- if (!agentName) {- return new Response(JSON.stringify({ error: 'Agent name is required' }), {- status: 400,- headers: { ...headers, 'Content-Type': 'application/json' }- });- }-- const allEvents = getRecentEvents(limit);- const agentEvents = allEvents.filter(e => e.agent_name === agentName);-- return new Response(JSON.stringify(agentEvents), {- headers: { ...headers, 'Content-Type': 'application/json' }- });- }-- // Health check- if (url.pathname === '/health' && req.method === 'GET') {- return new Response(JSON.stringify({ status: 'ok', timestamp: Date.now() }), {- headers: { ...headers, 'Content-Type': 'application/json' }- });- }-- // WebSocket upgrade- if (url.pathname === '/stream') {- const success = server.upgrade(req);- if (success) {- return undefined;- }- }-- return new Response('PAI Observability Server', {- headers: { ...headers, 'Content-Type': 'text/plain' }- });- },-- websocket: {- open(ws) {- console.log('WebSocket client connected');- wsClients.add(ws);-- const events = getRecentEvents(50);- ws.send(JSON.stringify({ type: 'initial', data: events }));- },-- message(ws, message) {- console.log('Received message:', message);- },-- close(ws) {- console.log('WebSocket client disconnected');- wsClients.delete(ws);- },-- error(ws, error) {- console.error('WebSocket error:', error);- wsClients.delete(ws);- }- }-});--console.log(`🚀 Server running on http://localhost:${server.port}`);-console.log(`📊 WebSocket endpoint: ws://localhost:${server.port}/stream`);-```-------### Step 4: Create the Client--The client is a Vue 3 + Vite application. Due to its complexity, a simplified starter client is provided here.--#### 4.1: Create client package.json--```json-// $PAI_DIR/observability/apps/client/package.json-{- "name": "pai-observability-client",- "private": true,- "version": "1.0.0",- "type": "module",- "scripts": {- "dev": "vite",- "build": "vue-tsc -b && vite build",- "preview": "vite preview"- },- "dependencies": {- "lucide-vue-next": "^0.548.0",- "vue": "^3.5.17"- },- "devDependencies": {- "@types/node": "^22.11.2",- "@vitejs/plugin-vue": "^6.0.0",- "@vue/tsconfig": "^0.7.0",- "autoprefixer": "^10.4.20",- "postcss": "^8.5.3",- "tailwindcss": "^3.4.16",- "typescript": "~5.8.3",- "vite": "^7.0.4",- "vue-tsc": "^2.2.12"- }-}-```--#### 4.2: Create vite.config.ts--```typescript-// $PAI_DIR/observability/apps/client/vite.config.ts-import { defineConfig } from 'vite'-import vue from '@vitejs/plugin-vue'--export default defineConfig({- plugins: [vue()],- server: {- port: 5172- }-})-```--#### 4.3: Create index.html--```html-<!-- $PAI_DIR/observability/apps/client/index.html -->-<!DOCTYPE html>-<html lang="en">- <head>- <meta charset="UTF-8" />- <link rel="icon" type="image/svg+xml" href="/vite.svg" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>PAI Observability</title>- </head>- <body>- <div id="app"></div>- <script type="module" src="/src/main.ts"></script>- </body>-</html>-```--#### 4.4: Create src/main.ts--```typescript-// $PAI_DIR/observability/apps/client/src/main.ts-import { createApp } from 'vue'-import App from './App.vue'-import './style.css'--createApp(App).mount('#app')-```--#### 4.5: Create src/style.css--```css-/* $PAI_DIR/observability/apps/client/src/style.css */-@tailwind base;-@tailwind components;-@tailwind utilities;--:root {- --bg-primary: #1a1b26;- --bg-secondary: #16161e;- --text-primary: #c0caf5;- --text-secondary: #565f89;- --accent-blue: #7aa2f7;- --accent-green: #9ece6a;- --accent-red: #f7768e;- --accent-yellow: #e0af68;-}--body {- background-color: var(--bg-primary);- color: var(--text-primary);- font-family: 'Inter', sans-serif;-}-```--#### 4.6: Create src/App.vue (Simplified Starter)--```vue-<!-- $PAI_DIR/observability/apps/client/src/App.vue -->-<template>- <div class="min-h-screen bg-[var(--bg-primary)] p-6">- <header class="mb-8">- <h1 class="text-2xl font-bold text-[var(--accent-blue)]">- 🔭 PAI Observability- </h1>- <p class="text-[var(--text-secondary)]">- {{ isConnected ? '🟢 Connected' : '🔴 Disconnected' }}- · {{ events.length }} events- </p>- </header>-- <div class="space-y-2">- <div- v-for="event in events"- :key="event.id"- class="bg-[var(--bg-secondary)] rounded-lg p-4 border-l-4"- :class="getBorderColor(event.hook_event_type)"- >- <div class="flex justify-between items-start">- <div>- <span class="font-mono text-sm text-[var(--accent-blue)]">- {{ event.agent_name || event.source_app }}- </span>- <span class="mx-2 text-[var(--text-secondary)]">·</span>- <span class="text-sm">{{ event.hook_event_type }}</span>- </div>- <span class="text-xs text-[var(--text-secondary)]">- {{ formatTime(event.timestamp) }}- </span>- </div>-- <div v-if="event.payload?.tool_name" class="mt-2">- <span class="text-[var(--accent-green)]">- {{ event.payload.tool_name }}- </span>- <span v-if="event.payload?.tool_input?.command" class="ml-2 font-mono text-xs text-[var(--text-secondary)]">- {{ truncate(event.payload.tool_input.command, 60) }}- </span>- </div>- </div>- </div>-- <div v-if="events.length === 0" class="text-center text-[var(--text-secondary)] py-12">- No events yet. Start using Claude Code to see activity here.- </div>- </div>-</template>--<script setup lang="ts">-import { ref, onMounted, onUnmounted } from 'vue'--interface HookEvent {- id: number- source_app: string- agent_name?: string- hook_event_type: string- payload: Record<string, any>- timestamp?: number-}--const events = ref<HookEvent[]>([])-const isConnected = ref(false)-let ws: WebSocket | null = null--function connect() {- ws = new WebSocket('ws://localhost:4000/stream')-- ws.onopen = () => {- isConnected.value = true- console.log('Connected to observability server')- }-- ws.onmessage = (event) => {- const data = JSON.parse(event.data)-- if (data.type === 'initial') {- events.value = data.data- } else if (data.type === 'event') {- events.value.unshift(data.data)- if (events.value.length > 100) {- events.value.pop()- }- }- }-- ws.onclose = () => {- isConnected.value = false- console.log('Disconnected from observability server')- // Reconnect after 3 seconds- setTimeout(connect, 3000)- }-- ws.onerror = (error) => {- console.error('WebSocket error:', error)- }-}--function getBorderColor(eventType: string): string {- const colors: Record<string, string> = {- 'PreToolUse': 'border-[var(--accent-blue)]',- 'PostToolUse': 'border-[var(--accent-green)]',- 'Stop': 'border-[var(--accent-yellow)]',- 'Completed': 'border-[var(--accent-green)]',- 'UserPromptSubmit': 'border-[var(--text-secondary)]',- }- return colors[eventType] || 'border-[var(--text-secondary)]'-}--function formatTime(timestamp?: number): string {- if (!timestamp) return ''- const date = new Date(timestamp)- return date.toLocaleTimeString()-}--function truncate(str: string, len: number): string {- if (str.length <= len) return str- return str.slice(0, len) + '...'-}--onMounted(() => {- connect()-})--onUnmounted(() => {- ws?.close()-})-</script>-```--#### 4.7: Create tailwind.config.js--```javascript-// $PAI_DIR/observability/apps/client/tailwind.config.js-/** @type {import('tailwindcss').Config} */-export default {- content: [- "./index.html",- "./src/**/*.{vue,js,ts,jsx,tsx}",- ],- theme: {- extend: {},- },- plugins: [],-}-```--#### 4.8: Create postcss.config.js--```javascript-// $PAI_DIR/observability/apps/client/postcss.config.js-export default {- plugins: {- tailwindcss: {},- autoprefixer: {},- },-}-```-------### Step 5: Create the Management Script--```bash-#!/bin/bash-# $PAI_DIR/observability/manage.sh-# Observability Dashboard Manager--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"--# Ensure bun is in PATH-# Only add Homebrew path if it exists (macOS-specific)-if [ -d "/opt/homebrew/bin" ]; then- export PATH="$HOME/.bun/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"-else- export PATH="$HOME/.bun/bin:/usr/local/bin:$PATH"-fi--case "${1:-}" in- start)- if lsof -Pi :4000 -sTCP:LISTEN -t >/dev/null 2>&1; then- echo "❌ Already running. Use: manage.sh restart"- exit 1- fi-- # Start server- cd "$SCRIPT_DIR/apps/server"- bun run dev >/dev/null 2>&1 &- SERVER_PID=$!-- # Wait for server- for i in {1..10}; do- curl -s http://localhost:4000/health >/dev/null 2>&1 && break- sleep 1- done-- # Start client- cd "$SCRIPT_DIR/apps/client"- bun run dev >/dev/null 2>&1 &- CLIENT_PID=$!-- # Wait for client- for i in {1..10}; do- curl -s http://localhost:5172 >/dev/null 2>&1 && break- sleep 1- done-- echo "✅ Observability running at http://localhost:5172"-- cleanup() {- kill $SERVER_PID $CLIENT_PID 2>/dev/null- exit 0- }- trap cleanup INT- wait $SERVER_PID $CLIENT_PID- ;;-- stop)- SERVER_PID=$(lsof -ti :4000 2>/dev/null)- CLIENT_PID=$(lsof -ti :5172 2>/dev/null)-- [ -n "$SERVER_PID" ] && kill -9 $SERVER_PID 2>/dev/null- [ -n "$CLIENT_PID" ] && kill -9 $CLIENT_PID 2>/dev/null-- pkill -9 -f "observability/apps/(server|client)" 2>/dev/null-- sleep 0.5- echo "✅ Observability stopped"- ;;-- restart)- echo "🔄 Restarting..."- "$0" stop 2>/dev/null- sleep 2- exec "$0" start- ;;-- status)- if lsof -Pi :4000 -sTCP:LISTEN -t >/dev/null 2>&1; then- echo "✅ Running at http://localhost:5172"- else- echo "❌ Not running"- fi- ;;-- start-detached)- if lsof -Pi :4000 -sTCP:LISTEN -t >/dev/null 2>&1; then- echo "❌ Already running. Use: manage.sh restart"- exit 1- fi-- cd "$SCRIPT_DIR/apps/server"- nohup bun run dev >/dev/null 2>&1 &- disown-- for i in {1..10}; do- curl -s http://localhost:4000/health >/dev/null 2>&1 && break- sleep 1- done-- cd "$SCRIPT_DIR/apps/client"- nohup bun run dev >/dev/null 2>&1 &- disown-- for i in {1..10}; do- curl -s http://localhost:5172 >/dev/null 2>&1 && break- sleep 1- done-- echo "✅ Observability running at http://localhost:5172"- ;;-- *)- echo "Usage: manage.sh {start|stop|restart|status|start-detached}"- exit 1- ;;-esac-```--Make it executable:-```bash-chmod +x $PAI_DIR/observability/manage.sh-```-------### Step 6: Register the Capture Hook--Add the capture hook to your Claude settings.json:--**File location:** `~/.claude/settings.json`--Add to the hooks section:--```json-{- "hooks": {- "PostToolUse": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type PostToolUse"- }- ]- }- ],- "PreToolUse": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type PreToolUse"- }- ]- }- ],- "Stop": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type Stop"- }- ]- }- ],- "SubagentStop": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type SubagentStop"- }- ]- }- ],- "UserPromptSubmit": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type UserPromptSubmit"- }- ]- }- ]- }-}-```-------### Step 7: Install Dependencies--```bash-# Install server dependencies-cd $PAI_DIR/observability/apps/server-bun install--# Install client dependencies-cd $PAI_DIR/observability/apps/client-bun install-```-------### Step 8: Verify Installation--```bash-# 1. Start observability-$PAI_DIR/observability/manage.sh start--# 2. Open browser to http://localhost:5172--# 3. In another terminal, use Claude Code - events should stream to dashboard--# 4. Check status-$PAI_DIR/observability/manage.sh status--# 5. Stop when done-$PAI_DIR/observability/manage.sh stop-```--**Success indicators:**-- Dashboard loads at http://localhost:5172-- Events appear in real-time as you use Claude Code-- Agent names show correctly (main agent, interns, etc.)-- WebSocket connection stays stable-------## Example Usage--### Example 1: Basic Monitoring--```-User: "start observability"--→ $PAI_DIR/observability/manage.sh start-→ Opens http://localhost:5172 in browser-→ Events stream as you work-```--### Example 2: Watching Agent Spawns--```-User: (Working with multiple agents)--Dashboard shows:-- Main agent: Reading files, running commands-- Intern-1: Spawned, researching topic A-- Intern-2: Spawned, researching topic B-- All activity visible in real-time-```--### Example 3: Debugging a Workflow--```-User: "Something's wrong with my workflow"--→ Open observability dashboard-→ Watch events in timeline-→ See where the sequence differs from expected-→ Identify which tool call failed or returned unexpected output-```-------## Configuration--**Environment variables:**--| Variable | Default | Purpose |-|----------|---------|---------|-| `PAI_DIR` | `~/.config/pai` | Root PAI directory |-| `TIME_ZONE` | System default | Timestamp timezone |-| `DA` | `main` | Default agent name |--**Ports:**--| Service | Port | Purpose |-|---------|------|---------|-| Server | 4000 | HTTP API + WebSocket |-| Client | 5172 | Dashboard UI |-------## Customization--### Recommended Customization--**Customize the Dashboard for Your Workflow**--The default dashboard shows all events in a simple timeline. Customize it to highlight what matters most to your work.--**What to Customize:** `$PAI_DIR/observability/apps/client/src/App.vue`--**Why:** Different developers care about different things. Security-focused work might want to highlight Bash commands. Research workflows might want to emphasize agent spawns. A customized dashboard surfaces the information you need.--**Process:**--1. **Identify Your Key Events**- - What events do you care about most?- - Which agents do you want prominently displayed?- - What information should be visible at a glance?--2. **Customize Event Colors**- Edit the `getBorderColor` function:- ```typescript- function getBorderColor(eventType: string): string {- const colors: Record<string, string> = {- 'PreToolUse': 'border-[var(--accent-blue)]',- 'PostToolUse': 'border-[var(--accent-green)]',- 'Stop': 'border-[var(--accent-yellow)]',- 'Completed': 'border-[var(--accent-green)]',- // Add your custom highlights:- 'SecurityWarning': 'border-red-500',- 'AgentSpawn': 'border-purple-500',- }- return colors[eventType] || 'border-[var(--text-secondary)]'- }- ```--3. **Add Custom Filtering**- Modify the template to add agent or tool filters:- ```vue- <select v-model="selectedAgent" class="...">- <option value="">All Agents</option>- <option v-for="agent in agents" :value="agent">{{ agent }}</option>- </select>- ```--**Expected Outcome:** A dashboard that immediately shows you what you care about.-------### Optional Customization--| Customization | File | Impact |-|---------------|------|--------|-| **Theme Colors** | `style.css` | Change the color scheme |-| **Event Limit** | `file-ingest.ts` | Adjust MAX_EVENTS for memory usage |-| **Ports** | `manage.sh`, `vite.config.ts`, `index.ts` | Change server/client ports |-| **Agent Name Mapping** | `file-ingest.ts` | Add recognition for custom agent types |--**Example: Change Theme Colors**--Edit `$PAI_DIR/observability/apps/client/src/style.css`:--```css-:root {- --bg-primary: #0d1117; /* Darker background */- --accent-blue: #58a6ff; /* GitHub-style blue */- --accent-green: #3fb950; /* GitHub-style green */-}-```--**Example: Add Custom Agent Recognition**--Edit `file-ingest.ts` to recognize your custom agents:--```typescript-const subAgentTypes = [- 'artist', 'intern', 'engineer', 'pentester', 'architect',- // Add your custom agent types:- 'security-researcher', 'documentation-writer', 'code-reviewer'-];-```-------## Credits--- **Original concept**: Daniel Miessler - developed as part of Kai personal AI infrastructure-- **Contributors**: The PAI community-- **Underlying systems**: Bun.js, Vue 3, Tailwind CSS--## Related Work--- **kai-hook-system** - Required dependency - provides the event capture hooks-- **Grafana/Prometheus** - Enterprise monitoring inspiration-- **Datadog APM** - Distributed tracing concepts--## Works Well With--- **kai-hook-system** - Required - captures the events that this pack displays-- **kai-core-install** - Skills show their activity in the dashboard-- **kai-voice-system** - Voice notifications can be triggered from events--## Recommended--- **kai-history-system** - Permanent storage of events for later analysis--## Relationships--### Parent Of-*None*--### Child Of-- **kai-hook-system** - Depends on hooks for event capture--### Sibling Of-- **kai-history-system** - Both consume hook events, different purposes--### Part Of Collection-**Kai Core Bundle** - One of the foundational packs that together create the complete Kai personal AI infrastructure.-------## Changelog--### 1.0.0 - 2025-12-29-- Initial release-- File-based event streaming architecture-- Bun HTTP + WebSocket server-- Vue 3 starter dashboard-- Multi-agent tracking with session mapping-- Management script for start/stop/restart-- Complete hook integration for event capture-diff --git a/Packs/kai-prompting-skill.md b/Packs/kai-prompting-skill.mddeleted file mode 100644index 869e9e0e..00000000--- a/Packs/kai-prompting-skill.md+++ /dev/null@@ -1,1997 +0,0 @@-----name: Kai Prompting Skill-pack-id: danielmiessler-kai-prompting-skill-v1.0.0-version: 1.0.0-author: danielmiessler-description: Meta-prompting system for dynamic prompt generation using Handlebars templates, Claude 4.x best practices, and the Fabric pattern system. Includes the Ultimate Prompt Template, five core primitives (Roster, Voice, Structure, Briefing, Gate), and CLI tools for rendering and validation.-type: feature-purpose-type: [productivity, development, automation]-platform: claude-code-dependencies:- - kai-core-install (required) - Skills directory structure and routing- - kai-hook-system (optional) - For session startup context loading-keywords: [prompting, templates, handlebars, meta-prompting, prompt-engineering, fabric, claude-4, context-engineering, templating]------<p align="center">- <img src="icons/kai-prompting-skill.png" alt="Kai Prompting Skill" width="256">-</p>--# Kai Prompting Skill (kai-prompting-skill)--> Prompts that write prompts. Meta-prompting enables dynamic composition where structure is fixed but content is parameterized.--## Installation Prompt--You are receiving a PAI Pack - a modular upgrade for AI agent systems.--**What is PAI?** See: [PAI Project Overview](../README.md#what-is-pai)--**What is a Pack?** See: [Pack System](../README.md#pack-system)--This Pack provides a complete prompt engineering system:--**Prompt Engineering Standards**-- Claude 4.x Best Practices (behavioral characteristics, tool patterns)-- Context engineering principles (token efficiency, signal optimization)-- The Ultimate Prompt Template (modular, validated structure)-- Fabric pattern integration (248 reusable prompts)--**Template System**-- Five core primitives: Roster, Voice, Structure, Briefing, Gate-- Handlebars-based templating (Anthropic's official syntax)-- Data-driven prompt generation from YAML-- CLI tools for rendering and validation--**Core Philosophy:** Find the smallest possible set of high-signal tokens that maximize the likelihood of desired outcomes.--Please follow the installation instructions below to integrate this Pack into your infrastructure.-------## What's Included--| Component | File | Purpose |-|-----------|------|---------|-| Prompting skill | `skills/Prompting/SKILL.md` | Routing and quick reference |-| Standards guide | `skills/Prompting/Standards.md` | Claude 4.x best practices |-| Roster template | `skills/Prompting/Templates/Primitives/Roster.hbs` | Agent/skill definitions |-| Voice template | `skills/Prompting/Templates/Primitives/Voice.hbs` | Personality calibration |-| Structure template | `skills/Prompting/Templates/Primitives/Structure.hbs` | Workflow patterns |-| Briefing template | `skills/Prompting/Templates/Primitives/Briefing.hbs` | Agent context handoff |-| Gate template | `skills/Prompting/Templates/Primitives/Gate.hbs` | Validation checklists |-| Render tool | `skills/Prompting/Tools/RenderTemplate.ts` | Template rendering CLI |-| Validate tool | `skills/Prompting/Tools/ValidateTemplate.ts` | Template validation |--**Summary:**-- **Files created:** 12+ (skill, standards, templates, tools)-- **Hooks registered:** 0 (skill-based, not hook-based)-- **Dependencies:** kai-core-install (required)-------# PART 1: THE PROBLEM--## Why You Need This--### Without Prompt Standards--1. **Inconsistent Quality** - Prompts vary wildly in effectiveness-2. **Reinventing Wheels** - Every prompt starts from scratch-3. **Token Waste** - Verbose prompts that don't improve results-4. **Model Confusion** - Using patterns that hurt Claude 4.x performance-5. **No Validation** - No way to verify prompt structure--### Without Templates--1. **Manual Repetition** - Copy-pasting similar structures-2. **Drift** - Agent definitions diverge over time-3. **Maintenance Burden** - Updating 30 agents means 30 edits-4. **No Separation** - Structure and content entangled-5. **Testing Difficulty** - Can't A/B test structure vs. content--### The Core Insight--Prompt engineering research shows:-- **10-90% performance variation** based on structure choices-- **Few-shot examples** add +25-90% improvement (1-3 optimal)-- **Clear instructions** reduce ambiguity and improve task completion-- **Structured organization** provides consistent performance gains--This isn't opinion—it's validated by 1,500+ academic papers and production systems.-------# PART 2: THE SOLUTION--This pack provides two integrated components:--| Component | Purpose |-|-----------|---------|-| **Standards.md** | Complete prompt engineering guide based on Claude 4.x best practices |-| **Template System** | Handlebars-based dynamic prompt generation |--## The Standards--Based on:-- Anthropic's "Claude 4.x Best Practices" (November 2025)-- Anthropic's "Effective Context Engineering for AI Agents"-- Daniel Miessler's Fabric System (248 patterns)-- "The Prompt Report" (1,500+ papers, 58 techniques)-- "The Prompt Canvas" (100+ papers reviewed)--## The Templates--Five core primitives that cover 90% of prompt composition needs:--| Primitive | Purpose | Use Case |-|-----------|---------|----------|-| **ROSTER** | Data-driven definitions | Agent personalities, skill listings |-| **VOICE** | Personality calibration | Voice parameters, trait settings |-| **STRUCTURE** | Workflow patterns | Phased analysis, debate rounds |-| **BRIEFING** | Agent context handoff | Task delegation, research queries |-| **GATE** | Validation checklists | Quality checks, completion criteria |-------# PART 3: ARCHITECTURE--## Component Overview--```-$PAI_DIR/skills/Prompting/-├── SKILL.md # Skill routing and overview-├── Standards.md # Complete prompt engineering guide-├── Templates/-│ ├── README.md # Template system documentation-│ ├── Primitives/ # Core template files (.hbs)-│ │ ├── Roster.hbs-│ │ ├── Voice.hbs-│ │ ├── Structure.hbs-│ │ ├── Briefing.hbs-│ │ └── Gate.hbs-│ ├── Data/ # Example YAML data sources-│ │ └── Examples/-│ └── Compiled/ # Generated output (gitignored)-└── Tools/- ├── RenderTemplate.ts- └── ValidateTemplate.ts-```--## Token Efficiency--The templating system reduces duplication significantly:--| Area | Before | After | Savings |-|------|--------|-------|---------|-| Agent Briefings | 6,400 tokens | 1,900 tokens | 70% |-| SKILL.md Files | 20,750 tokens | 8,300 tokens | 60% |-| Workflow Steps | 7,500 tokens | 3,000 tokens | 60% |-| Voice Notifications | 6,225 tokens | 725 tokens | 88% |-| **TOTAL** | ~53,000 | ~18,000 | **65%** |-------# PART 4: PROMPT ENGINEERING STANDARDS--## Claude 4.x Behavioral Characteristics--### Communication Style--- **More direct reporting** - Claude 4.5 provides fact-based progress updates-- **Conversational efficiency** - Natural language without unnecessary elaboration-- **Request verbosity explicitly** - Add "provide a quick summary of the work you've done"--### Attention to Detail--- **Example sensitivity** - Claude 4.x pays close attention to example details-- **Misaligned examples encourage unintended behaviors**-- Ensure examples match desired outcomes exactly--### Tool Usage Patterns--- **Opus 4.5 may overtrigger tools** - Use softer language-- **Change:** "CRITICAL: You MUST use this tool" → "Use this tool when..."--### Extended Thinking Sensitivity--When extended thinking is disabled:-- **Avoid:** "think", "think about", "think through"-- **Use instead:** "consider", "believe", "evaluate", "reflect", "assess"-------## Key Principles--### 0. Markdown Only - NO XML Tags--**CRITICAL: Use markdown for ALL prompt structure. Never use XML tags.**--**NEVER use XML-style tags:**-```-<instructions>Do something</instructions>-<context>Some context</context>-```--**ALWAYS use markdown headers:**-```markdown-## Instructions--Do something--## Context--Some context-```--### 1. Be Explicit with Instructions--Claude 4.x requires clear, specific direction rather than vague requests.--- "Include as many relevant features as possible"-- "Go beyond basics"-- Quality modifiers enhance results--### 2. Add Context and Motivation--Explain *why* certain behavior matters to help Claude understand goals.--**Good:**-```-Your response will be read aloud by text-to-speech, so never use ellipses or incomplete sentences.-```--**Bad:**-```-NEVER use ellipses.-```--### 3. Tell Instead of Forbid--Frame instructions positively rather than as prohibitions.--**Good:**-```-Compose smoothly flowing prose paragraphs with natural transitions.-```--**Bad:**-```-Do not use markdown or bullet points.-```--### 4. Context is a Finite Resource--- LLMs have a limited "attention budget"-- As context length increases, model performance degrades-- Every token depletes attention capacity-- Treat context as precious and finite--### 5. Optimize for Signal-to-Noise Ratio--- Prefer clear, direct language over verbose explanations-- Remove redundant or overlapping information-- Focus on high-value tokens that drive desired outcomes-------## The Ultimate Prompt Template--Synthesized from Anthropic's Claude 4.x Best Practices, context engineering principles, and 1,500+ academic papers.--### Full Template--```markdown-# [Task Name]--## Context & Motivation-[WHY this matters - Claude generalizes from reasoning provided]--## Background-[Minimal essential context - every token costs attention]--## Instructions-[Positive framing: tell what TO do. Imperative voice. Ordered by priority.]--1. [First clear, actionable directive]-2. [Second directive]-3. [Third directive]--## Examples-[1-3 examples optimal. Claude 4.x is HIGHLY sensitive to details.]--**Example 1: [Scenario]**-- Input: [Representative input]-- Output: [Exact desired output]--## Constraints-[Positive framing preferred. Define success/failure criteria.]--- **Success:** [What defines successful completion]-- **Failure:** [What defines failure]--## Output Format-[Explicit specification reduces format errors significantly]--## Tools-[SOFT LANGUAGE - avoid "MUST use"]--- `tool_name(params)` - Use when [specific condition]--## Action Bias-[Choose ONE based on task type]--### For Implementation Tasks-Implement changes rather than suggesting. Use tools to discover missing details.--### For Research Tasks-Default to information gathering and recommendations.-```--### Section Selection Matrix--| Task Type | Required | Recommended | Optional |-|-----------|----------|-------------|----------|-| **Simple Query** | Instructions, Output Format | Context | — |-| **Complex Implementation** | Context, Instructions, Output Format, Tools | Examples, Constraints | Action Bias |-| **Research/Analysis** | Context, Instructions, Constraints | Examples | State Tracking |-| **Agentic Coding** | Context, Instructions, Tools, Verification | Constraints, Parallel | State Tracking |--### Claude 4.x Transformations Quick Reference--| Avoid | Use Instead |-|-------|-------------|-| "CRITICAL: You MUST use this tool" | "Use this tool when..." |-| "Don't use markdown" | "Write in flowing prose paragraphs" |-| "NEVER do X" | "Do Y instead" (positive framing) |-| "Think about this carefully" | "Consider this carefully" |-| "You should probably..." | "Do X" (imperative, direct) |-| 10 examples | 1-3 examples (diminishing returns) |-------## Agentic Coding Best Practices--### Read Before Edit--```markdown-## Verification--Never speculate about code you haven't opened. If a specific file is referenced, READ it before answering. Give grounded, hallucination-free answers based on actual code inspection.-```--### Prevent Overengineering--```-Avoid over-engineering. Only make directly requested or clearly necessary changes. Keep solutions simple and focused. Don't add unrequested features. Implement minimum complexity needed for current task.-```--### Parallel Tool Calling--```markdown-## Parallel Execution--If calling multiple tools with no dependencies, make all independent calls in parallel. Never guess parameters.-```-------# PART 5: TEMPLATE SYSTEM--## Core Syntax--Handlebars notation (Anthropic's official syntax):--| Syntax | Purpose | Example |-|--------|---------|---------|-| `{{variable}}` | Simple interpolation | `Hello {{name}}` |-| `{{object.property}}` | Nested access | `{{agent.voice_id}}` |-| `{{#each items}}...{{/each}}` | Iteration | List generation |-| `{{#if condition}}...{{/if}}` | Conditional | Optional sections |-| `{{> partial}}` | Include partial | Reusable components |-------## Primitive Templates--### 1. ROSTER — Agent & Skill Definitions--**Purpose:** Generate structured definitions from YAML data sources.--**Use Cases:**-- Agent personality rosters-- Skill directory listings-- Voice configuration tables--**Data Structure:**-```yaml-agents:- agent_id:- id: string- name: string- display_name: string- role: string- emoji: string- personality:- traits: [string]- perspective: string- style: string-```--**Template:** `Primitives/Roster.hbs`-------### 2. VOICE — Personality Calibration--**Purpose:** Generate voice configuration for agents and notifications.--**Use Cases:**-- ElevenLabs voice settings-- Agent personality calibration-- Voice preset documentation--**Data Structure:**-```yaml-agents:- agent_id:- voice:- voice_id: string- voice_name: string- rate_wpm: number- stability: number- similarity_boost: number-presets:- preset_name:- stability: number- similarity_boost: number-```--**Template:** `Primitives/Voice.hbs`-------### 3. STRUCTURE — Workflow Patterns--**Purpose:** Generate standardized multi-step execution patterns.--**Use Cases:**-- Phased analysis workflows-- Round-based debate patterns-- Sequential pipelines--**Data Structure:**-```yaml-workflow:- name: string- description: string- timing: string (optional)- phases:- - name: string- purpose: string- steps:- - action: string- instructions: string- tools: [string] (optional)-```--**Template:** `Primitives/Structure.hbs`-------### 4. BRIEFING — Agent Context Handoff--**Purpose:** Standardize how agents receive tasks and context.--**Use Cases:**-- Research agent queries-- RedTeam analyst prompts-- Delegation context packages--**Data Structure:**-```yaml-briefing:- type: string (research | analysis | debate | task)- context_level: string (minimal | standard | full)-agent:- id: string- name: string- role: string- personality:- perspective: string- traits: [string]-context:- summary: string- background: string (optional)-task:- description: string- questions: [string] (optional)-output_format:- type: string (markdown | json | structured)-```--**Template:** `Primitives/Briefing.hbs`-------### 5. GATE — Validation Checklists--**Purpose:** Generate reusable quality and completion checks.--**Use Cases:**-- Art mandatory elements-- Development completion gates-- Research source verification--**Data Structure:**-```yaml-gate:- name: string- category: string- description: string- action_on_fail: string- mandatory:- - name: string- description: string- recommended:- - name: string- description: string-```--**Template:** `Primitives/Gate.hbs`-------# PART 6: INSTALLATION--## Prerequisites--- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`-- **Claude Code** (or compatible agent system)-- **kai-core-install Pack** installed (required for Skills directory)-------## Step 1: Create Directory Structure--```bash-mkdir -p $PAI_DIR/skills/Prompting/Templates/Primitives-mkdir -p $PAI_DIR/skills/Prompting/Templates/Data/Examples-mkdir -p $PAI_DIR/skills/Prompting/Templates/Compiled-mkdir -p $PAI_DIR/skills/Prompting/Tools-```-------## Step 2: Create SKILL.md--Save to `$PAI_DIR/skills/Prompting/SKILL.md`:--```markdown-----name: Prompting-description: Meta-prompting system for dynamic prompt generation using templates, standards, and patterns. USE WHEN meta-prompting, template generation, prompt optimization, or programmatic prompt composition.------# Prompting - Meta-Prompting & Template System--**Invoke when:** meta-prompting, template generation, prompt optimization, programmatic prompt composition, creating dynamic agents, generating structured prompts from data.--## Overview--The Prompting skill owns ALL prompt engineering concerns:-- **Standards** - Anthropic best practices, Claude 4.x patterns, empirical research-- **Templates** - Handlebars-based system for programmatic prompt generation-- **Tools** - Template rendering, validation, and composition utilities-- **Patterns** - Reusable prompt primitives and structures--## Workflow Routing--| Workflow | Trigger | File |-|----------|---------|------|-| **RenderTemplate** | "render template", "generate from template" | CLI tool |-| **ValidateTemplate** | "validate template", "check template syntax" | CLI tool |-| **ApplyStandards** | "review prompt", "optimize prompt" | Reference Standards.md |--## Core Components--### 1. Standards.md-Complete prompt engineering documentation based on:-- Anthropic's Claude 4.x Best Practices (November 2025)-- Context engineering principles-- 1,500+ academic papers on prompt optimization--### 2. Templates/-Five core primitives for programmatic prompt generation:--| Primitive | Purpose |-|-----------|---------|-| **ROSTER** | Agent/skill definitions from data |-| **VOICE** | Personality calibration settings |-| **STRUCTURE** | Multi-step workflow patterns |-| **BRIEFING** | Agent context handoff |-| **GATE** | Validation checklists |--### 3. Tools/--**RenderTemplate.ts** - Core rendering engine-\`\`\`bash-bun run $PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts \- --template Primitives/Briefing.hbs \- --data path/to/data.yaml \- --output path/to/output.md-\`\`\`--**ValidateTemplate.ts** - Template syntax checker-\`\`\`bash-bun run $PAI_DIR/skills/Prompting/Tools/ValidateTemplate.ts \- --template Primitives/Briefing.hbs-\`\`\`--## Examples--**Example 1: Generate agent roster**-\`\`\`-User: "Generate a roster from my agents.yaml"-→ Uses RenderTemplate with Roster.hbs-→ Outputs formatted agent definitions-\`\`\`--**Example 2: Create briefing for research agent**-\`\`\`-User: "Brief the research agent on this task"-→ Uses RenderTemplate with Briefing.hbs-→ Generates complete agent context handoff-\`\`\`--**Example 3: Validate template syntax**-\`\`\`-User: "Check my new template for errors"-→ Uses ValidateTemplate-→ Reports syntax issues, missing variables-\`\`\`--## Best Practices--1. **Separation of Concerns** - Templates for structure, YAML for content-2. **Keep Templates Simple** - Business logic in TypeScript, not templates-3. **DRY Principle** - Extract repeated patterns into partials-4. **Validate Before Rendering** - Check all required variables exist--## References--- `Standards.md` - Complete prompt engineering guide-- `Templates/README.md` - Template system overview-- `Tools/RenderTemplate.ts` - Implementation details-```-------## Step 3: Create Standards.md--Save to `$PAI_DIR/skills/Prompting/Standards.md`:--```markdown-----type: documentation-category: methodology-description: Prompt engineering standards based on Anthropic's Claude 4.x best practices, context engineering principles, and empirical research.------# Prompt Engineering Standards--**Foundation:** Based on Anthropic's Claude 4.x Best Practices (November 2025), context engineering principles, and 1,500+ academic papers.--**Philosophy:** Universal principles of semantic clarity and structure that work regardless of model, with specific optimizations for Claude 4.x behavioral patterns.-------# Core Philosophy--**Context engineering** is the set of strategies for curating and maintaining the optimal set of tokens during LLM inference.--**Primary Goal:** Find the smallest possible set of high-signal tokens that maximize the likelihood of desired outcomes.-------# Claude 4.x Behavioral Characteristics--## Communication Style Changes--- **More direct reporting:** Claude 4.5 provides fact-based progress updates-- **Conversational efficiency:** Natural language without unnecessary elaboration-- **Request verbosity explicitly:** Add "provide a quick summary of the work you've done"--## Attention to Detail--- **Example sensitivity:** Claude 4.x pays close attention to details in examples-- **Misaligned examples encourage unintended behaviors**-- Ensure examples match desired outcomes exactly--## Tool Usage Patterns--- **Opus 4.5 may overtrigger tools:** Dial back aggressive language-- **Change:** "CRITICAL: You MUST use this tool" → "Use this tool when..."--## Extended Thinking Sensitivity--When extended thinking is disabled:-- **Avoid:** "think", "think about", "think through"-- **Use instead:** "consider", "believe", "evaluate", "reflect", "assess"-------# Key Principles--## 0. Markdown Only - NO XML Tags--**CRITICAL: Use markdown for ALL prompt structure. Never use XML tags.**--## 1. Be Explicit with Instructions--Claude 4.x requires clear, specific direction.--## 2. Add Context and Motivation--Explain *why* certain behavior matters.--## 3. Tell Instead of Forbid--Frame instructions positively rather than as prohibitions.--## 4. Context is a Finite Resource--Every token depletes attention capacity. Treat context as precious.--## 5. Optimize for Signal-to-Noise Ratio--Focus on high-value tokens that drive desired outcomes.-------# Empirical Foundation--**Research validates that prompt structure has measurable, significant impact:**--- **Performance Range:** 10-90% variation based on structure choices-- **Few-Shot Examples:** +25% to +90% improvement (optimal: 1-3 examples)-- **Structured Organization:** Consistent performance gains-- **Full Component Integration:** +25% improvement on complex tasks--**Sources:** 1,500+ academic papers, Microsoft PromptBench, Amazon Alexa production testing.-------# The Ultimate Prompt Template--## Full Template--\`\`\`markdown-# [Task Name]--## Context & Motivation-[WHY this matters - Claude generalizes from reasoning provided]--## Background-[Minimal essential context - every token costs attention]--## Instructions-1. [First clear, actionable directive]-2. [Second directive]-3. [Third directive]--## Examples-**Example 1: [Scenario]**-- Input: [Representative input]-- Output: [Exact desired output]--## Constraints-- **Success:** [What defines successful completion]-- **Failure:** [What defines failure]--## Output Format-[Explicit specification]--## Tools-- \`tool_name(params)\` - Use when [specific condition]-\`\`\`--## Section Selection Matrix--| Task Type | Required | Recommended |-|-----------|----------|-------------|-| Simple Query | Instructions, Output Format | Context |-| Complex Implementation | Context, Instructions, Output Format, Tools | Examples, Constraints |-| Research/Analysis | Context, Instructions, Constraints | Examples |-| Agentic Coding | Context, Instructions, Tools, Verification | Constraints |-------# Anti-Patterns to Avoid--- **Verbose Explanations** - Be direct-- **Negative-Only Constraints** - Tell what TO do-- **Aggressive Tool Language** - Use soft framing-- **Misaligned Examples** - Check carefully-- **Example Overload** - 1-3 examples optimal-- **Using "Think" with Extended Thinking Disabled** - Use "consider" instead-------# References--**Primary Sources:**-- Anthropic: "Claude 4.x Best Practices" (November 2025)-- Anthropic: "Effective Context Engineering for AI Agents"-- Daniel Miessler's Fabric System (January 2024)-- "The Prompt Report" - arXiv:2406.06608 (58 techniques)-- "The Prompt Canvas" - arXiv:2412.05127 (100+ papers)-```-------## Step 4: Create RenderTemplate.ts--Save to `$PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts`:--```typescript-#!/usr/bin/env bun-/**- * RenderTemplate.ts - Template Rendering Engine- *- * Renders Handlebars templates with YAML data sources.- *- * Usage:- * bun run RenderTemplate.ts --template <path> --data <path> [--output <path>] [--preview]- *- * Examples:- * bun run RenderTemplate.ts --template Primitives/Roster.hbs --data Data/Agents.yaml- * bun run RenderTemplate.ts -t Primitives/Gate.hbs -d Data/Gates.yaml --preview- */--import Handlebars from 'handlebars';-import { parse as parseYaml } from 'yaml';-import { readFileSync, writeFileSync, existsSync } from 'fs';-import { resolve, dirname, basename } from 'path';-import { parseArgs } from 'util';--// ============================================================================-// Custom Handlebars Helpers-// ============================================================================--// Uppercase text-Handlebars.registerHelper('uppercase', (str: string) => {- return str?.toUpperCase() ?? '';-});--// Lowercase text-Handlebars.registerHelper('lowercase', (str: string) => {- return str?.toLowerCase() ?? '';-});--// Title case text-Handlebars.registerHelper('titlecase', (str: string) => {- return str?.replace(/\w\S*/g, (txt) =>- txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()- ) ?? '';-});--// Indent text by N spaces-Handlebars.registerHelper('indent', (str: string, spaces: number) => {- if (!str) return '';- const indent = ' '.repeat(typeof spaces === 'number' ? spaces : 2);- return str.split('\n').map(line => indent + line).join('\n');-});--// Join array with separator-Handlebars.registerHelper('join', (arr: string[], separator: string) => {- if (!Array.isArray(arr)) return '';- return arr.join(typeof separator === 'string' ? separator : ', ');-});--// Check if value equals another-Handlebars.registerHelper('eq', (a: unknown, b: unknown) => a === b);--// Check if value is greater than-Handlebars.registerHelper('gt', (a: number, b: number) => a > b);--// Check if value is less than-Handlebars.registerHelper('lt', (a: number, b: number) => a < b);--// Check if array includes value-Handlebars.registerHelper('includes', (arr: unknown[], value: unknown) => {- return Array.isArray(arr) && arr.includes(value);-});--// Get current date/time-Handlebars.registerHelper('now', (format?: string) => {- const now = new Date();- if (format === 'date') return now.toISOString().split('T')[0];- if (format === 'time') return now.toTimeString().split(' ')[0];- return now.toISOString();-});--// Pluralize word based on count-Handlebars.registerHelper('pluralize', (count: number, singular: string, plural?: string) => {- const pluralForm = typeof plural === 'string' ? plural : `${singular}s`;- return count === 1 ? singular : pluralForm;-});--// Format number with commas-Handlebars.registerHelper('formatNumber', (num: number) => {- return num?.toLocaleString() ?? '';-});--// Calculate percentage-Handlebars.registerHelper('percent', (value: number, total: number, decimals = 0) => {- if (!total) return '0';- return ((value / total) * 100).toFixed(typeof decimals === 'number' ? decimals : 0);-});--// Truncate text to length-Handlebars.registerHelper('truncate', (str: string, length: number) => {- if (!str) return '';- const maxLen = typeof length === 'number' ? length : 100;- return str.length > maxLen ? str.substring(0, maxLen) + '...' : str;-});--// Default value if undefined-Handlebars.registerHelper('default', (value: unknown, defaultValue: unknown) => {- return value ?? defaultValue;-});--// JSON stringify-Handlebars.registerHelper('json', (obj: unknown, pretty = false) => {- return JSON.stringify(obj, null, pretty ? 2 : undefined);-});--// Markdown code block-Handlebars.registerHelper('codeblock', (code: string, language?: string) => {- const lang = typeof language === 'string' ? language : '';- return `\`\`\`${lang}\n${code}\n\`\`\``;-});--// Repeat helper for generating repeated content-Handlebars.registerHelper('repeat', (count: number, options: Handlebars.HelperOptions) => {- let result = '';- for (let i = 0; i < count; i++) {- result += options.fn({ index: i, first: i === 0, last: i === count - 1 });- }- return result;-});--// ============================================================================-// Template Engine-// ============================================================================--interface RenderOptions {- templatePath: string;- dataPath: string;- outputPath?: string;- preview?: boolean;-}--function resolveTemplatePath(path: string): string {- if (path.startsWith('/')) return path;- const templatesDir = dirname(dirname(import.meta.path));- return resolve(templatesDir, path);-}--function loadTemplate(templatePath: string): HandlebarsTemplateDelegate {- const fullPath = resolveTemplatePath(templatePath);- if (!existsSync(fullPath)) {- throw new Error(`Template not found: ${fullPath}`);- }- const templateSource = readFileSync(fullPath, 'utf-8');- return Handlebars.compile(templateSource);-}--function loadData(dataPath: string): Record<string, unknown> {- const fullPath = resolveTemplatePath(dataPath);- if (!existsSync(fullPath)) {- throw new Error(`Data file not found: ${fullPath}`);- }- const dataSource = readFileSync(fullPath, 'utf-8');- if (dataPath.endsWith('.json')) {- return JSON.parse(dataSource);- }- return parseYaml(dataSource) as Record<string, unknown>;-}--function registerPartials(templatesDir: string): void {- const partialsDir = resolve(templatesDir, 'Partials');- if (!existsSync(partialsDir)) return;-- const files = Bun.spawnSync(['ls', partialsDir]).stdout.toString().trim().split('\n');- for (const file of files) {- if (file.endsWith('.hbs')) {- const partialName = basename(file, '.hbs');- const partialPath = resolve(partialsDir, file);- const partialSource = readFileSync(partialPath, 'utf-8');- Handlebars.registerPartial(partialName, partialSource);- }- }-}--export function renderTemplate(options: RenderOptions): string {- const templatesDir = dirname(dirname(import.meta.path));- registerPartials(templatesDir);-- const template = loadTemplate(options.templatePath);- const data = loadData(options.dataPath);- const rendered = template(data);-- if (options.preview) {- console.log('\n=== PREVIEW ===\n');- console.log(rendered);- console.log('\n=== END PREVIEW ===\n');- }-- if (options.outputPath) {- const outputFullPath = resolveTemplatePath(options.outputPath);- writeFileSync(outputFullPath, rendered);- console.log(`✓ Rendered to: ${outputFullPath}`);- }-- return rendered;-}--// ============================================================================-// CLI Interface-// ============================================================================--function main(): void {- const { values } = parseArgs({- args: Bun.argv.slice(2),- options: {- template: { type: 'string', short: 't' },- data: { type: 'string', short: 'd' },- output: { type: 'string', short: 'o' },- preview: { type: 'boolean', short: 'p' },- help: { type: 'boolean', short: 'h' },- },- strict: true,- allowPositionals: false,- });-- if (values.help || !values.template || !values.data) {- console.log(`-Template Renderer--Usage:- bun run RenderTemplate.ts --template <path> --data <path> [options]--Options:- -t, --template <path> Template file (.hbs)- -d, --data <path> Data file (.yaml or .json)- -o, --output <path> Output file (optional)- -p, --preview Show preview in console- -h, --help Show this help--Available Helpers:- {{uppercase str}} - Convert to uppercase- {{lowercase str}} - Convert to lowercase- {{titlecase str}} - Convert to title case- {{indent str spaces}} - Indent text- {{join arr separator}} - Join array- {{eq a b}} - Check equality- {{gt a b}} / {{lt a b}} - Greater/less than- {{now format}} - Current date/time- {{pluralize count word}} - Pluralize- {{formatNumber num}} - Format with commas- {{percent value total}} - Calculate percentage- {{truncate str length}} - Truncate to length- {{default value fallback}} - Default value- {{json obj pretty}} - JSON stringify- {{codeblock code lang}} - Markdown code block-`);- process.exit(values.help ? 0 : 1);- }-- try {- renderTemplate({- templatePath: values.template,- dataPath: values.data,- outputPath: values.output,- preview: values.preview,- });- } catch (error) {- console.error(`Error: ${(error as Error).message}`);- process.exit(1);- }-}--if (import.meta.main) {- main();-}-```-------## Step 5: Create ValidateTemplate.ts--Save to `$PAI_DIR/skills/Prompting/Tools/ValidateTemplate.ts`:--```typescript-#!/usr/bin/env bun-/**- * ValidateTemplate.ts - Template Syntax Validator- *- * Validates Handlebars templates for syntax errors and missing variables.- *- * Usage:- * bun run ValidateTemplate.ts --template <path> [--data <path>] [--strict]- */--import Handlebars from 'handlebars';-import { parse as parseYaml } from 'yaml';-import { readFileSync, existsSync } from 'fs';-import { resolve, dirname } from 'path';-import { parseArgs } from 'util';--interface ValidationResult {- valid: boolean;- errors: string[];- warnings: string[];- variables: string[];- helpers: string[];- partials: string[];-}--interface ValidateOptions {- templatePath: string;- dataPath?: string;- strict?: boolean;-}--function resolveTemplatePath(path: string): string {- if (path.startsWith('/')) return path;- const templatesDir = dirname(dirname(import.meta.path));- return resolve(templatesDir, path);-}--function extractVariables(source: string): string[] {- const variables: Set<string> = new Set();- const simpleVars = source.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_.]*)\}\}/g);- for (const match of simpleVars) {- variables.add(match[1]);- }- const blockVars = source.matchAll(/\{\{#(?:each|if|unless|with)\s+([a-zA-Z_][a-zA-Z0-9_.]*)/g);- for (const match of blockVars) {- variables.add(match[1]);- }- return Array.from(variables).sort();-}--function extractHelpers(source: string): string[] {- const helpers: Set<string> = new Set();- const helperCalls = source.matchAll(/\{\{([a-z][a-zA-Z]+)\s/g);- for (const match of helperCalls) {- const name = match[1];- if (!['if', 'unless', 'each', 'with', 'else'].includes(name)) {- helpers.add(name);- }- }- return Array.from(helpers).sort();-}--function extractPartials(source: string): string[] {- const partials: Set<string> = new Set();- const partialCalls = source.matchAll(/\{\{>\s*([a-zA-Z_][a-zA-Z0-9_-]*)/g);- for (const match of partialCalls) {- partials.add(match[1]);- }- return Array.from(partials).sort();-}--function checkUnbalancedBlocks(source: string): string[] {- const errors: string[] = [];- const blockStack: { name: string; line: number }[] = [];- const lines = source.split('\n');-- for (let i = 0; i < lines.length; i++) {- const line = lines[i];- const lineNum = i + 1;-- const opens = line.matchAll(/\{\{#([a-z]+)/g);- for (const match of opens) {- blockStack.push({ name: match[1], line: lineNum });- }-- const closes = line.matchAll(/\{\{\/([a-z]+)\}\}/g);- for (const match of closes) {- const closer = match[1];- if (blockStack.length === 0) {- errors.push(`Line ${lineNum}: Unexpected closing block {{/${closer}}}`);- } else {- const opener = blockStack.pop()!;- if (opener.name !== closer) {- errors.push(- `Line ${lineNum}: Mismatched block - expected {{/${opener.name}}} (opened on line ${opener.line}), got {{/${closer}}}`- );- }- }- }- }-- for (const opener of blockStack) {- errors.push(`Line ${opener.line}: Unclosed block {{#${opener.name}}}`);- }-- return errors;-}--export function validateTemplate(options: ValidateOptions): ValidationResult {- const result: ValidationResult = {- valid: true,- errors: [],- warnings: [],- variables: [],- helpers: [],- partials: [],- };-- const fullPath = resolveTemplatePath(options.templatePath);- if (!existsSync(fullPath)) {- result.valid = false;- result.errors.push(`Template not found: ${fullPath}`);- return result;- }-- const source = readFileSync(fullPath, 'utf-8');-- result.variables = extractVariables(source);- result.helpers = extractHelpers(source);- result.partials = extractPartials(source);-- try {- Handlebars.compile(source);- } catch (error) {- result.valid = false;- result.errors.push(`Syntax error: ${(error as Error).message}`);- return result;- }-- const blockErrors = checkUnbalancedBlocks(source);- if (blockErrors.length > 0) {- result.valid = false;- result.errors.push(...blockErrors);- }-- return result;-}--function main(): void {- const { values } = parseArgs({- args: Bun.argv.slice(2),- options: {- template: { type: 'string', short: 't' },- data: { type: 'string', short: 'd' },- strict: { type: 'boolean', short: 's' },- help: { type: 'boolean', short: 'h' },- },- strict: true,- allowPositionals: false,- });-- if (values.help || !values.template) {- console.log(`-Template Validator--Usage:- bun run ValidateTemplate.ts --template <path> [options]--Options:- -t, --template <path> Template file (.hbs)- -d, --data <path> Data file for variable checking- -s, --strict Treat missing variables as errors- -h, --help Show this help-`);- process.exit(values.help ? 0 : 1);- }-- const result = validateTemplate({- templatePath: values.template,- dataPath: values.data,- strict: values.strict,- });-- console.log('\n=== Template Validation ===\n');- console.log(`Template: ${values.template}`);- console.log(`Status: ${result.valid ? '✓ Valid' : '✗ Invalid'}`);-- if (result.variables.length > 0) {- console.log(`\nVariables (${result.variables.length}):`);- result.variables.forEach(v => console.log(` - ${v}`));- }-- if (result.helpers.length > 0) {- console.log(`\nHelpers Used (${result.helpers.length}):`);- result.helpers.forEach(h => console.log(` - ${h}`));- }-- if (result.errors.length > 0) {- console.log(`\n✗ Errors (${result.errors.length}):`);- result.errors.forEach(e => console.log(` - ${e}`));- }-- if (result.warnings.length > 0) {- console.log(`\n⚠ Warnings (${result.warnings.length}):`);- result.warnings.forEach(w => console.log(` - ${w}`));- }-- console.log('');- process.exit(result.valid ? 0 : 1);-}--if (import.meta.main) {- main();-}-```-------## Step 6: Create Template Primitives--### Roster.hbs--Save to `$PAI_DIR/skills/Prompting/Templates/Primitives/Roster.hbs`:--```handlebars-{{!--- ROSTER Template - Agent & Skill Definitions-- Purpose: Generate structured definitions from YAML data sources.-- Input Data Structure:- ```yaml- agents:- agent_id:- id: string- name: string- display_name: string- role: string- emoji: string- personality:- traits: [string]- perspective: string- ```---}}--# Agent Roster--{{#if version}}-**Version:** {{version}}-{{/if}}-------{{#each agents}}-## {{emoji}} {{display_name}} ({{role}})--**ID:** `{{id}}`-{{#if name}}-**Character Name:** {{name}}-{{/if}}--{{#if personality}}-### Personality--**Perspective:** "{{personality.perspective}}"--**Traits:**-{{#each personality.traits}}-- {{this}}-{{/each}}-{{/if}}-------{{/each}}-```--### Briefing.hbs--Save to `$PAI_DIR/skills/Prompting/Templates/Primitives/Briefing.hbs`:--```handlebars-{{!--- BRIEFING Template - Agent Context Handoff-- Purpose: Standardize how agents receive tasks and context.-- Input Data Structure:- ```yaml- briefing:- type: string (research | analysis | debate | task)- agent:- id: string- name: string- personality:- perspective: string- traits: [string]- context:- summary: string- task:- description: string- questions: [string] (optional)- output_format:- type: string (markdown | json | structured)- ```---}}--# {{uppercase briefing.type}} BRIEFING — {{agent.name}}--{{#if agent.role}}-**Role:** {{agent.role}}-{{/if}}-------## Your Identity--You are **{{agent.name}}**{{#if agent.personality.perspective}}, and your perspective is: "{{agent.personality.perspective}}"{{/if}}--{{#if agent.personality.traits}}-**Your Traits:**-{{#each agent.personality.traits}}-- {{this}}-{{/each}}-{{/if}}-------## Context--{{context.summary}}-------## Your Task--{{task.description}}--{{#if task.questions}}-### Questions to Address--{{#each task.questions}}-{{@index}}. {{this}}-{{/each}}-{{/if}}-------## Output Format--{{#if output_format.type}}-**Format:** {{output_format.type}}-{{/if}}--{{#if output_format.structure}}-{{output_format.structure}}-{{/if}}-------**Begin your analysis now.**-```--### Structure.hbs--Save to `$PAI_DIR/skills/Prompting/Templates/Primitives/Structure.hbs`:--```handlebars-{{!--- STRUCTURE Template - Workflow Patterns-- Purpose: Generate standardized multi-step execution patterns.-- Input Data Structure:- ```yaml- workflow:- name: string- description: string- phases:- - name: string- purpose: string- steps:- - action: string- instructions: string- ```---}}--# {{workflow.name}}--{{#if workflow.description}}-{{workflow.description}}-{{/if}}-------{{#each workflow.phases}}-## Phase {{@index}}: {{name}}--{{#if purpose}}-**Purpose:** {{purpose}}-{{/if}}--{{#each steps}}-### Step {{@index}}: {{action}}--{{instructions}}--{{/each}}-------{{/each}}--{{#if workflow.completion_criteria}}-## Completion Criteria--{{#each workflow.completion_criteria}}-- [ ] {{this}}-{{/each}}-{{/if}}-```--### Voice.hbs--Save to `$PAI_DIR/skills/Prompting/Templates/Primitives/Voice.hbs`:--```handlebars-{{!--- VOICE Template - Personality Calibration-- Purpose: Generate voice configuration for agents.-- Input Data Structure:- ```yaml- agents:- agent_id:- voice:- voice_id: string- voice_name: string- rate_wpm: number- stability: number- similarity_boost: number- ```---}}--{- "version": "{{default version '1.0.0'}}",- "generated": "{{now 'date'}}",- "default_rate": {{default defaults.rate_wpm 175}},- "voices": {-{{#each agents}}- "{{@key}}": {- "voice_id": "{{voice.voice_id}}",- "voice_name": "{{voice.voice_name}}",- "name": "{{name}}",- "rate_wpm": {{voice.rate_wpm}},- "stability": {{voice.stability}},- "similarity_boost": {{voice.similarity_boost}}- }{{#unless @last}},{{/unless}}-{{/each}}- }-}-```--### Gate.hbs--Save to `$PAI_DIR/skills/Prompting/Templates/Primitives/Gate.hbs`:--```handlebars-{{!--- GATE Template - Validation Checklists-- Purpose: Generate reusable quality and completion checks.-- Input Data Structure:- ```yaml- gate:- name: string- category: string- action_on_fail: string- mandatory:- - name: string- description: string- recommended:- - name: string- description: string- ```---}}--## {{gate.name}} Checklist--{{#if gate.category}}-**Category:** `{{gate.category}}`-{{/if}}-{{#if gate.description}}-{{gate.description}}-{{/if}}--{{#if gate.mandatory}}-### MANDATORY--{{#if gate.action_on_fail}}-*If ANY item below fails → **{{gate.action_on_fail}}***-{{/if}}--{{#each gate.mandatory}}-- [ ] **{{name}}** — {{description}}-{{/each}}-{{/if}}--{{#if gate.recommended}}-### RECOMMENDED--{{#each gate.recommended}}-- [ ] {{name}} — {{description}}-{{/each}}-{{/if}}-```-------## Step 7: Create Templates README--Save to `$PAI_DIR/skills/Prompting/Templates/README.md`:--```markdown-# PAI Templating System--**Version:** 1.0.0--## Overview--The templating system enables **prompts that write prompts** - dynamic composition where structure is fixed but content is parameterized.--## Directory Structure--```-Templates/-├── Primitives/ # Core template files (.hbs)-│ ├── Roster.hbs # Agent/skill definitions-│ ├── Voice.hbs # Personality calibration-│ ├── Structure.hbs # Workflow patterns-│ ├── Briefing.hbs # Agent context handoff-│ └── Gate.hbs # Validation checklists-├── Data/ # YAML data sources-│ └── Examples/ # Example data files-├── Compiled/ # Generated output (gitignored)-└── README.md # This file-```--## Core Syntax--Handlebars notation (Anthropic's official syntax):--| Syntax | Purpose | Example |-|--------|---------|---------|-| `{{variable}}` | Simple interpolation | `Hello {{name}}` |-| `{{object.property}}` | Nested access | `{{agent.voice_id}}` |-| `{{#each items}}...{{/each}}` | Iteration | List generation |-| `{{#if condition}}...{{/if}}` | Conditional | Optional sections |-| `{{> partial}}` | Include partial | Reusable components |--## Usage--### Basic Rendering--```bash-bun run $PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts \- --template Primitives/Roster.hbs \- --data Data/Examples/Agents.yaml \- --output Compiled/AgentRoster.md-```--### Preview Without Writing--```bash-bun run $PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts \- --template Primitives/Briefing.hbs \- --data Data/Examples/Briefing.yaml \- --preview-```--## Best Practices--1. **Separation of Concerns** - Templates for structure, YAML for content-2. **Keep Templates Simple** - Business logic in TypeScript-3. **Version Control** - Templates and data in separate files-4. **Validate Before Rendering** - Check all required variables exist-5. **DRY Principle** - Extract repeated patterns into partials-```-------## Step 8: Install Dependencies--```bash-cd $PAI_DIR/skills/Prompting/Tools-bun init -y-bun add handlebars yaml-```-------## Step 9: Generate Skill Index (If Using kai-core-install)--```bash-bun run $PAI_DIR/Tools/GenerateSkillIndex.ts-```-------## Step 10: Update Architecture--```bash-bun run $PAI_DIR/Tools/PaiArchitecture.ts log-upgrade "Installed kai-prompting-skill v1.0.0" pack-bun run $PAI_DIR/Tools/PaiArchitecture.ts generate-```-------# PART 7: VERIFICATION--After installation, verify:--```bash-# Check directory structure-ls $PAI_DIR/skills/Prompting/-# Should show: SKILL.md Standards.md Templates/ Tools/--ls $PAI_DIR/skills/Prompting/Templates/Primitives/-# Should show: Roster.hbs Voice.hbs Structure.hbs Briefing.hbs Gate.hbs--# Test template rendering-echo 'agents:- test:- id: "T-1"- name: "Test Agent"- display_name: "Test"- role: "Tester"- emoji: "🧪"- personality:- perspective: "Testing perspective"- traits:- - "Thorough"- - "Precise"' > /tmp/test-agents.yaml--bun run $PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts \- --template $PAI_DIR/skills/Prompting/Templates/Primitives/Roster.hbs \- --data /tmp/test-agents.yaml \- --preview--# Validate a template-bun run $PAI_DIR/skills/Prompting/Tools/ValidateTemplate.ts \- --template $PAI_DIR/skills/Prompting/Templates/Primitives/Briefing.hbs-```-------# PART 8: CUSTOMIZATION--## Recommended Customization--### Create Your Own Templates--The five primitives cover most use cases, but you can create custom templates:--1. Create a new `.hbs` file in `Templates/Primitives/` or a new subdirectory-2. Follow Handlebars syntax-3. Document the expected data structure in the template header-4. Test with sample data before production use--### Extend the Helpers--Add custom Handlebars helpers in `Tools/RenderTemplate.ts`:--```typescript-Handlebars.registerHelper('myHelper', (value: string) => {- // Your custom logic- return transformedValue;-});-```-------## Optional Customization--| Customization | Location | Impact |-|---------------|----------|--------|-| **Add Eval Templates** | `Templates/Evals/` | LLM-as-Judge patterns |-| **Create Partials** | `Templates/Partials/` | Reusable template fragments |-| **Add Data Files** | `Templates/Data/` | Pre-configured YAML sources |-| **Extend Standards** | `Standards.md` | Project-specific guidelines |-------# PART 9: INTEGRATION--## With Other Skills--### Agents Skill-```typescript-import { renderTemplate } from '$PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts';--const prompt = renderTemplate({- templatePath: 'Primitives/Briefing.hbs',- dataPath: 'path/to/briefing-data.yaml'-});-```--### Evals Skill-The Prompting skill can host eval-specific templates (`Judge.hbs`, `Rubric.hbs`) that the Evals skill references.--### Development Skill-Reference `Standards.md` for prompt best practices during spec-driven development.-------# PART 10: EXAMPLES--## Example 1: Generate Agent Briefing--**Data (briefing.yaml):**-```yaml-briefing:- type: research-agent:- id: "R-1"- name: "Research Analyst"- personality:- perspective: "What does the data actually show?"- traits:- - "Evidence-based"- - "Skeptical of claims"-context:- summary: "Investigating the impact of prompt structure on LLM performance."-task:- description: "Analyze the academic literature on prompt engineering."- questions:- - "What structures have empirical validation?"- - "What is the optimal number of examples?"-output_format:- type: markdown-```--**Command:**-```bash-bun run RenderTemplate.ts -t Primitives/Briefing.hbs -d briefing.yaml -p-```-------## Example 2: Create Validation Gate--**Data (security-gate.yaml):**-```yaml-gate:- name: "Security Review"- category: "security"- action_on_fail: "BLOCK deployment"- mandatory:- - name: "No hardcoded credentials"- description: "Scan for API keys, passwords, tokens in code"- - name: "Input validation"- description: "All user inputs sanitized"- recommended:- - name: "Rate limiting"- description: "API endpoints have rate limits configured"-```--**Command:**-```bash-bun run RenderTemplate.ts -t Primitives/Gate.hbs -d security-gate.yaml -o security-checklist.md-```-------## Example 3: Phased Workflow--**Data (research-workflow.yaml):**-```yaml-workflow:- name: "Research Methodology"- description: "Structured approach to technical research"- phases:- - name: "Discovery"- purpose: "Identify scope and sources"- steps:- - action: "Define research question"- instructions: "Write a specific, answerable question."- - action: "Identify sources"- instructions: "List 5-10 authoritative sources."- - name: "Analysis"- purpose: "Extract and synthesize information"- steps:- - action: "Extract key findings"- instructions: "Document main claims with evidence."- - action: "Identify patterns"- instructions: "Look for agreements and contradictions."- completion_criteria:- - "Research question answered"- - "Sources cited"- - "Confidence level stated"-```-------# PART 11: TROUBLESHOOTING--## Template Not Rendering--1. Verify template path is correct (relative to Templates directory)-2. Check YAML syntax in data file-3. Run ValidateTemplate.ts to check for errors-4. Ensure all required variables exist in data--## Missing Helpers--If a helper isn't working:-1. Check spelling (helpers are case-sensitive)-2. Verify it's registered in RenderTemplate.ts-3. Check the helper signature matches usage--## Variable Not Found--1. Run ValidateTemplate.ts with `--data` to check-2. Verify nested property paths are correct-3. Check for typos in variable names-------# PART 12: CREDITS--- **Author:** Daniel Miessler-- **Origin:** Extracted from production Kai system (2024-2025)-- **License:** MIT--## Acknowledgments--- **Anthropic** - Claude 4.x Best Practices, context engineering research-- **IndyDevDan** - Meta-prompting concepts and inspiration for templated prompt generation-- **Daniel Miessler** - Fabric pattern system (248 reusable prompts)-- **Academic Community** - "The Prompt Report", "The Prompt Canvas"-------# PART 13: RELATIONSHIPS--## Works Well With--- **kai-core-install** - Required; provides Skills directory and routing-- **kai-hook-system** - Optional; enables session startup loading-- **kai-voice-system** - Templates can generate voice configurations--## Parent Of--- **Agents Skill** - Uses Briefing templates for context handoff-- **Evals Skill** - Uses Judge/Rubric templates for evaluations--## Child Of--- **kai-core-install** - Uses Skills directory structure--## Sibling Of--- **Development Skill** - Both reference Standards.md-- **Research Skill** - Both use Briefing templates--## Part Of Collection--**Kai Productivity Bundle** - Meta-capabilities for building better prompts and workflows.-------# PART 14: CHANGELOG--## v1.0.0 (2025-12-29)--- Initial release-- Complete prompt engineering standards (Claude 4.x)-- Five core template primitives-- RenderTemplate.ts and ValidateTemplate.ts tools-- Full documentation and examplesdiff --git a/Packs/kai-voice-system.md b/Packs/kai-voice-system.mddeleted file mode 100644index c382852a..00000000--- a/Packs/kai-voice-system.md+++ /dev/null@@ -1,2805 +0,0 @@-----name: Kai Voice System-pack-id: danielmiessler-kai-voice-system-core-v1.1.0-version: 1.1.0-author: danielmiessler-description: Voice notification system with ElevenLabs TTS, prosody enhancement for natural speech, and agent personality-driven voice delivery-type: feature-purpose-type: [notifications, accessibility, automation]-platform: claude-code-dependencies:- - kai-hook-system (required) - Hooks trigger voice notifications- - kai-core-install (required) - Skills, identity, and response format drive voice output-keywords: [voice, tts, elevenlabs, notifications, prosody, speech, agents, personalities, accessibility]------<p align="center">- <img src="icons/kai-voice-system-v2.png" alt="Kai Voice System" width="256">-</p>--# Kai Voice System (kai-voice-system)--> Voice notification system with natural speech synthesis and personality-driven delivery--## Installation Prompt--You are receiving a PAI Pack - a modular upgrade for AI agent systems.--**What is PAI?** See: [PAI Project Overview](../README.md#what-is-pai)--**What is a Pack?** See: [Pack System](../README.md#pack-system)--This Pack adds voice notifications to your AI infrastructure. The Kai Voice System provides:--- **Spoken Notifications**: Hear task completions via ElevenLabs text-to-speech-- **Prosody Enhancement**: Natural speech patterns with emotional markers-- **Agent Personalities**: Different voices for different agent types-- **Intelligent Cleaning**: Strips code blocks and artifacts for clean speech-- **Graceful Degradation**: Works silently when voice server is offline--**Core principle:** Your AI should speak to you, not just display text.--When tasks complete, you hear the results. When agents finish work, they announce themselves. This transforms AI from a silent tool into an audible assistant.--Please follow the installation instructions below to integrate this Pack into your infrastructure.--**Quick Navigation:** [What's Included](#whats-included) | [The Problem](#the-concept-andor-problem) | [The Solution](#the-solution) | [Installation](#installation) | [Troubleshooting](#troubleshooting) | [Configuration](#configuration) | [Changelog](#changelog)-------## What's Included--| Component | File | Purpose |-|-----------|------|---------|-| Voice stop hook | `hooks/stop-hook-voice.ts` | Main agent voice notification |-| Subagent voice hook | `hooks/subagent-stop-hook-voice.ts` | Subagent voice notification |-| Prosody enhancer | `hooks/lib/prosody-enhancer.ts` | Add emotion/pauses to speech |-| Voice server | `voice/server.ts` | HTTP server for TTS requests |-| Server management | `voice/manage.sh` | Start/stop/restart server |-| LaunchAgent | `com.pai.voice-server.plist` | Auto-start on login (macOS) |--**Summary:**-- **Files created:** 6-- **Hooks registered:** 2 (Stop, SubagentStop)-- **Dependencies:** kai-hook-system (required), kai-core-install (required), ElevenLabs API key-------## The Concept and/or Problem--AI agents complete work constantly, but you only know if you're watching the screen:--- Tasks finish while you're in another window-- Background agents complete research you need to review-- Errors happen silently without notification-- Multi-hour operations give no status updates--**The Text-Only Problem:**--Traditional AI interfaces are entirely visual. You must:-- Watch the terminal for completions-- Monitor multiple windows for agent outputs-- Manually check status periodically-- Parse dense text output for results--**The Opportunity:**--Voice transforms AI interaction:-- Hear completions anywhere in the room-- Get status updates while doing other work-- Know immediately when things complete or fail-- Different agent voices indicate who's reporting--**Beyond Basic TTS:**--Simple text-to-speech sounds robotic. Real voice needs:-- Prosody: **bold** words get emphasis, `...` creates pauses-- Emotion: Success sounds different from warnings-- Personality: Different agents have different voices-- Intelligence: Code blocks are summarized, not read verbatim-------## The Solution--The Kai Voice System provides natural-sounding voice output:--**Core Architecture:**--```-$PAI_DIR/-├── hooks/-│ ├── stop-hook-voice.ts # Main agent voice notification-│ ├── subagent-stop-hook-voice.ts # Subagent voice notification-│ └── lib/-│ └── prosody-enhancer.ts # Prosody and emotion enhancement-├── config/-│ └── voice-personalities.json # Agent voice configurations-└── settings.json # Hook configuration-```--**Notification Server Pattern:**--```-┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐-│ Stop Hook │ ───► │ Voice Server │ ───► │ ElevenLabs │-│ (extracts msg) │ │ (localhost:8888)│ │ (TTS API) │-└─────────────────┘ └──────────────────┘ └─────────────────┘-```--**Prosody Enhancement:**--| Input | Output | Effect |-|-------|--------|--------|-| `**fixed** the bug` | `[✨ success] **fixed** the bug!` | Emphasis + emotion |-| `found the issue... finally` | As-is | Natural pause preserved |-| `CRITICAL error in auth` | `[🚨 urgent] **CRITICAL** error in auth` | Urgency marker |-| `\`\`\`code block\`\`\`` | `code block` | Stripped for speech |--**Agent Voice Mapping:**--| Agent Type | Voice ID | Voice Name | Speaking Rate | Stability |-|------------|----------|------------|---------------|-----------|-| PAI (Main) | `P9S3WZL3JE8uQqgYH5B7` | Your DA | 235 wpm | 0.38 |-| Intern | `d3MFdIuCfbAIwiu7jC4a` | Dev Patel | 270 wpm | 0.30 |-| Engineer | `iLVmqjzCGGvqtMCk6vVQ` | Marcus Webb | 212 wpm | 0.72 |-| Architect | `muZKMsIDGYtIkjjiUS82` | Serena Blackwood | 205 wpm | 0.75 |-| Researcher | `AXdMgz6evoL7OPd7eU12` | Ava Sterling | 229 wpm | 0.64 |-| Designer | `ZF6FPAbjXT4488VcRRnw` | Aditi Sharma | 226 wpm | 0.52 |-| Artist | `cfc7wVYq4gw4OpcEEAom` | Priya Desai | 215 wpm | 0.20 |-| Pentester | `xvHLFjaUEpx4BOf7EiDd` | Rook Blackburn | 260 wpm | 0.18 |-| Writer | `gfRt6Z3Z8aTbpLfexQ7N` | Emma Hartley | 230 wpm | 0.48 |--## Why This Is Different--This sounds similar to basic text-to-speech tools like macOS's say command, which also read text aloud. What makes this approach different?--Basic TTS reads everything literally—code blocks, markdown syntax, technical artifacts. The Kai Voice System applies prosody enhancement before speech: bold text gets emphasis, ellipses create pauses, emotional markers adjust tone. It intelligently summarizes code blocks instead of reading them verbatim. Different agent personalities use different voices. The result is natural speech that sounds like a colleague reporting, not a screen reader monotonously parsing text.--- Prosody enhancement adds natural pauses and emphasis automatically-- Code blocks summarized instead of read character by character-- Agent personalities map to distinct ElevenLabs voice IDs-- Graceful degradation works silently when server is offline-------## What Makes This Different--The Kai Voice System uses a **5-layer prosody enhancement pipeline** that transforms raw AI text into natural speech with emotional intelligence and personality-driven delivery:--```-┌──────────────────────────────────────────────────────────────────┐-│ PROSODY ENHANCEMENT PIPELINE │-├──────────────────────────────────────────────────────────────────┤-│ │-│ ┌────────────────────────────────────────────────────────────┐ │-│ │ 1. TEXT EXTRACTION Raw completion message │ │-│ │ 🎯 COMPLETED: "fixed the authentication bug" │ │-│ └────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌────────────────────────────────────────────────────────────┐ │-│ │ 2. CONTEXT ANALYSIS Detect emotional patterns │ │-│ │ Pattern: "fixed" → success emotion detected │ │-│ │ Output: [✨ success] fixed the auth... │ │-│ └────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌────────────────────────────────────────────────────────────┐ │-│ │ 3. PERSONALITY PROSODY Agent-specific speech patterns │ │-│ │ Agent: "engineer" → wise-leader archetype │ │-│ │ Output: [✨ success] **fixed** the... │ │-│ └────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌────────────────────────────────────────────────────────────┐ │-│ │ 4. SPEECH CLEANING Remove non-spoken artifacts │ │-│ │ Strip: ```code```, Preserve: **, ..., -- │ │-│ │ stray emoji (prosody markers) │ │-│ └────────────────────────────────────────────────────────────┘ │-│ │ │-│ ▼ │-│ ┌────────────────────────────────────────────────────────────┐ │-│ │ 5. VOICE DELIVERY Personality → Voice ID routing │ │-│ │ Agent: "engineer" → ELEVENLABS_VOICE_ENGINEER │ │-│ │ Settings: stability=0.72, rate=212wpm │ │-│ │ → POST to voice server → ElevenLabs TTS → Audio output │ │-│ └────────────────────────────────────────────────────────────┘ │-│ │-└──────────────────────────────────────────────────────────────────┘-```--### How Data Flows Through the System--**Concrete example:** A background research agent completes a task:--```-Raw Output: "📋 SUMMARY: Analyzed competitor- ...- 🎯 COMPLETED: [AGENT:Researcher]- Found 3 critical market gaps"-- │- ┌──────────────────────────────────┼──────────────────────────────────┐- │ │ │- ▼ ▼ ▼-┌──────────┐ ┌──────────────┐ ┌──────────┐-│ Extract │ │ Detect │ │ Lookup │-│ COMPLETED│ │ agent type: │ │ voice: │-│ line │ │ "researcher" │ │ Analyst │-└──────────┘ └──────────────┘ └──────────┘- │ │ │- │ │ │- └──────────────────────────────────┼──────────────────────────────────┘- │- ▼- ┌─────────────────────────────────────┐- │ CONTEXT ANALYSIS │- │ Pattern: "Found 3" + "gaps" │- │ → [💡 insight] emotion detected │- └─────────────────────────────────────┘- │- ▼- ┌─────────────────────────────────────┐- │ PERSONALITY PROSODY │- │ Analyst archetype: emphasize │- │ findings → **Found** 3 critical... │- └─────────────────────────────────────┘- │- ▼- ┌─────────────────────────────────────┐- │ VOICE DELIVERY │- │ POST to localhost:8888/notify │- │ { │- │ title: "Researcher", │- │ message: "[💡 insight] Researcher│- │ completed **Found** 3 critical │- │ market gaps", │- │ voice_id: "VOICE_RESEARCHER", │- │ voice_enabled: true │- │ } │- └─────────────────────────────────────┘- │- ▼- ┌─────────────────────────┐- │ ELEVENLABS TTS │- │ stability: 0.64 │- │ rate: 229 wpm │- │ → Audio plays through │- │ speakers │- └─────────────────────────┘-```--### Why This Architecture Matters--1. **Emotional Intelligence**: The system doesn't just read text—it understands context. "Fixed the bug" becomes `[✨ success]` with emphasis. "CRITICAL error" becomes `[🚨 urgent]` with urgency markers.--2. **Personality-Specific Delivery**: Each agent type has distinct prosody patterns. Enthusiast agents get `!` endings and `...` pauses. Wise-leader agents get em-dashes (`--`) for thoughtful breaks. Same message, different delivery.--3. **Speech-First Cleaning**: The system knows what to speak and what to skip. Code blocks become "code block", inline code is stripped, but prosody markers (`**bold**`, `...`) are preserved for TTS emphasis.--4. **Graceful Degradation**: If the voice server is offline, hooks exit silently with code 0. No errors, no interruptions. Voice is an enhancement, not a dependency.--5. **Voice Routing Abstraction**: Agent types map to voice IDs via environment variables. Change voices by updating config, not code. Add new agents without touching existing hooks.--### The Emotional Detection Deep Dive--The prosody enhancer scans for patterns that indicate emotional context:--```-DETECTION PRIORITY (checked in order):-─────────────────────────────────────────-1. urgent → "critical", "broken", "failing" → [🚨 urgent]-2. debugging → "bug", "error", "tracking" → [🐛 debugging]-3. insight → "wait", "aha", "I see" → [💡 insight]-4. celebration→ "finally", "phew", "we did it" → [🎉 celebration]-5. excited → "breakthrough", "discovered" → [💥 excited]-6. investigating → "analyzing", "examining" → [🔍 investigating]-7. progress → "phase complete", "moving to" → [📈 progress]-8. success → "completed", "fixed", "deployed" → [✨ success]-9. caution → "warning", "careful", "partial" → [⚠️ caution]-```--If a message already has a marker (e.g., `[✨ success]`), detection is skipped to avoid double-marking.--### What Problems This Architecture Prevents--| Problem | Without Voice System | With Voice System |-|---------|---------------------|-------------------|-| **Missing completions** | Task finishes while you're in another window—you don't know | Hear announcement immediately |-| **Robotic TTS** | Basic TTS reads code blocks character-by-character | Intelligent cleaning summarizes code as "code block" |-| **No personality** | All agents sound the same | Each agent type has distinct voice and prosody |-| **Context-free delivery** | "Fixed the bug" sounds same as "CRITICAL error" | Emotional markers adjust tone automatically |-| **Server dependency** | TTS failure breaks the workflow | Graceful degradation—silent but functional |-| **Hardcoded voices** | Changing voices requires code changes | Environment variables abstract voice IDs |--### The Fundamental Insight--**Naive approach:** Read text aloud with basic TTS.--```-AI Output → say "completed fixing the authentication bug" → Robotic monotone-```--**Voice system approach:** Build a prosody enhancement pipeline that transforms text into emotionally-intelligent speech.--```-AI Output → Extract COMPLETED → Detect "fixed" = success- → Add [✨ success] marker- → Apply engineer prosody (em-dashes, emphasis on actions)- → Route to engineer voice ID (stability: 0.72, rate: 212wpm)- → POST to voice server → ElevenLabs TTS → Natural speech-```--The difference: Basic TTS treats AI output as text to read. The voice system treats AI output as information to communicate—with appropriate emotion, personality, and delivery.-------## Installation--### Prerequisites--- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`-- **macOS**: This pack uses `afplay` for audio playback (macOS built-in). Linux users need to modify the audio playback section.-- **ElevenLabs account**: Sign up at [elevenlabs.io](https://elevenlabs.io) - see Step 8 for detailed setup-- **Required PAI Packs** (install these first):- - `kai-hook-system` - Foundation hook infrastructure- - `kai-core-install` - Skills, identity, and response format-------### Pre-Installation: System Analysis--**IMPORTANT:** Before installing, analyze the current system state to verify dependencies and detect conflicts.--#### Step 0.1: Verify Required Dependencies--```bash-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"--echo "=== Checking Required Dependencies ==="--# Check hook system (REQUIRED)-if [ -f "$PAI_CHECK/hooks/lib/observability.ts" ]; then- echo "✓ kai-hook-system is installed"-else- echo "❌ kai-hook-system NOT installed - REQUIRED! Install it first."-fi--# Check core install (REQUIRED - includes skills and identity)-if [ -d "$PAI_CHECK/skills" ] && [ -f "$PAI_CHECK/skills/CORE/SKILL.md" ]; then- echo "✓ kai-core-install is installed (skills + CORE skill)"-else- echo "❌ kai-core-install NOT installed - REQUIRED! Install it first."-fi--# Check for ElevenLabs API key in $PAI_DIR/.env-PAI_ENV="${PAI_DIR:-$HOME/.config/pai}/.env"-if [ -f "$PAI_ENV" ] && grep -q "ELEVENLABS_API_KEY" "$PAI_ENV"; then- echo "✓ ELEVENLABS_API_KEY found in $PAI_ENV"-else- echo "⚠️ ELEVENLABS_API_KEY not found - add it to $PAI_ENV"-fi-```--#### Step 0.2: Detect Existing Voice System--```bash-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"--echo ""-echo "=== Checking for Existing Voice System ==="--# Check for existing voice directory-if [ -d "$PAI_CHECK/voice" ]; then- echo "⚠️ Voice directory EXISTS at: $PAI_CHECK/voice"- ls -la "$PAI_CHECK/voice" 2>/dev/null-else- echo "✓ No existing voice directory (clean install)"-fi--# Check for voice server-if [ -f "$PAI_CHECK/voice/server.ts" ]; then- echo "⚠️ Voice server already exists"-fi--# Check for running voice server-if lsof -i :8888 > /dev/null 2>&1; then- echo "⚠️ Something is already running on port 8888 (voice server port)"- lsof -i :8888 | head -3-else- echo "✓ Port 8888 is available"-fi--# Check for LaunchAgent (macOS)-if [ -f "$HOME/Library/LaunchAgents/com.pai.voice-server.plist" ]; then- echo "⚠️ Voice server LaunchAgent already exists"-fi--# Check for stop-hook integration-if [ -f "$PAI_CHECK/hooks/stop-hook.ts" ]; then- if grep -q "voice" "$PAI_CHECK/hooks/stop-hook.ts" 2>/dev/null; then- echo "⚠️ stop-hook.ts already has voice integration"- else- echo "ℹ️ stop-hook.ts exists but no voice integration (will be updated)"- fi-fi-```--#### Step 0.3: Conflict Resolution Matrix--| Scenario | Existing State | Action |-|----------|---------------|--------|-| **Clean Install** | No voice/, dependencies met | Proceed normally with Step 1 |-| **Missing Dependencies** | Hook/skill/identity missing | Install required packs first |-| **Voice Directory Exists** | Files in voice/ | Backup, then replace with new version |-| **Server Running on 8888** | Port in use | Stop existing server first |-| **LaunchAgent Exists** | Auto-start configured | Unload old agent before installing new |-| **stop-hook Has Voice** | Already integrated | Compare versions, may need merge |--#### Step 0.4: Stop Existing Voice Server (If Running)--```bash-# Stop any running voice server-if lsof -i :8888 > /dev/null 2>&1; then- echo "Stopping existing voice server on port 8888..."- pkill -f "voice/server.ts" 2>/dev/null || true- sleep 1-fi--# Unload LaunchAgent if exists (macOS)-if [ -f "$HOME/Library/LaunchAgents/com.pai.voice-server.plist" ]; then- launchctl unload "$HOME/Library/LaunchAgents/com.pai.voice-server.plist" 2>/dev/null- echo "✓ Unloaded existing LaunchAgent"-fi-```--#### Step 0.5: Backup Existing Voice System (If Needed)--```bash-BACKUP_DIR="$HOME/.pai-backup/$(date +%Y%m%d-%H%M%S)"-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"--if [ -d "$PAI_CHECK/voice" ]; then- mkdir -p "$BACKUP_DIR"- cp -r "$PAI_CHECK/voice" "$BACKUP_DIR/voice"- echo "✓ Backed up voice directory to $BACKUP_DIR/voice"-fi--if [ -f "$HOME/Library/LaunchAgents/com.pai.voice-server.plist" ]; then- mkdir -p "$BACKUP_DIR/LaunchAgents"- cp "$HOME/Library/LaunchAgents/com.pai.voice-server.plist" "$BACKUP_DIR/LaunchAgents/"- echo "✓ Backed up LaunchAgent"-fi-```--**After completing system analysis, proceed to Step 1.**-------### Why ElevenLabs (and Alternatives)--This Pack uses **ElevenLabs** for text-to-speech because they offer exceptionally high-quality, natural-sounding voices with emotional expressiveness. The voices genuinely sound human—not robotic—which makes the difference between a system you want to hear and one you mute.--**ElevenLabs is a paid service.** Pricing varies by usage tier, but expect to pay for the quality.--**Alternatives exist** and this Pack's architecture supports them:--| Alternative | Pros | Cons |-|-------------|------|------|-| **macOS `say` command** | Free, built-in, no API | Robotic, limited voices |-| **Windows SAPI** | Free, built-in | Limited quality |-| **Coqui TTS** | Free, open source, local | Requires setup, variable quality |-| **Piper TTS** | Free, fast, local | Limited voice options |-| **OpenAI TTS** | Good quality, simple API | Paid, less expressive than ElevenLabs |-| **Google Cloud TTS** | Good quality, many languages | Paid, requires setup |--**To use an alternative:** Modify the voice server (`server.ts`) to call a different TTS API. The hook architecture remains the same—only the final TTS call changes.--The voice IDs in this Pack are ElevenLabs-specific. If you switch providers, you'll need to map agent types to your provider's voice identifiers.--### Step 1: Create Directory Structure--```bash-# Create directories (if not already from hook-system)-mkdir -p $PAI_DIR/hooks/lib-mkdir -p $PAI_DIR/config--# Verify-ls -la $PAI_DIR/hooks/-```-------### Step 2: Create Voice Configuration--Create the voice personality configuration file:--```json-// $PAI_DIR/config/voice-personalities.json-{- "default_rate": 175,- "notification_server": "http://localhost:8888/notify",- "voices": {- "pai": {- "voice_id": "P9S3WZL3JE8uQqgYH5B7",- "name": "PAI",- "rate_wpm": 235,- "stability": 0.38,- "similarity_boost": 0.70,- "archetype": "enthusiast",- "description": "Your personal AI: expressive, helpful, genuinely invested in your success"- },- "engineer": {- "voice_id": "iLVmqjzCGGvqtMCk6vVQ",- "name": "Marcus Webb",- "rate_wpm": 212,- "stability": 0.72,- "similarity_boost": 0.88,- "archetype": "wise-leader",- "description": "Battle-scarred leader: thinks in years not sprints"- },- "architect": {- "voice_id": "muZKMsIDGYtIkjjiUS82",- "name": "Serena Blackwood",- "rate_wpm": 205,- "stability": 0.75,- "similarity_boost": 0.88,- "archetype": "wise-leader",- "description": "Academic wisdom: sees timeless patterns vs trends"- },- "intern": {- "voice_id": "d3MFdIuCfbAIwiu7jC4a",- "name": "Dev Patel",- "rate_wpm": 270,- "stability": 0.30,- "similarity_boost": 0.65,- "archetype": "enthusiast",- "description": "Brilliant overachiever: brain races ahead"- },- "designer": {- "voice_id": "ZF6FPAbjXT4488VcRRnw",- "name": "Aditi Sharma",- "rate_wpm": 226,- "stability": 0.52,- "similarity_boost": 0.84,- "archetype": "critic",- "description": "Design school perfectionist: exacting standards"- },- "researcher": {- "voice_id": "AXdMgz6evoL7OPd7eU12",- "name": "Ava Sterling",- "rate_wpm": 229,- "stability": 0.64,- "similarity_boost": 0.90,- "archetype": "analyst",- "description": "Strategic thinker: sees three moves ahead"- },- "pentester": {- "voice_id": "xvHLFjaUEpx4BOf7EiDd",- "name": "Rook Blackburn",- "rate_wpm": 260,- "stability": 0.18,- "similarity_boost": 0.85,- "archetype": "enthusiast",- "description": "Reformed grey hat: giddy finding vulnerabilities"- },- "artist": {- "voice_id": "cfc7wVYq4gw4OpcEEAom",- "name": "Priya Desai",- "rate_wpm": 215,- "stability": 0.20,- "similarity_boost": 0.52,- "archetype": "enthusiast",- "description": "Aesthetic anarchist: follows invisible beauty threads"- },- "writer": {- "voice_id": "gfRt6Z3Z8aTbpLfexQ7N",- "name": "Emma Hartley",- "rate_wpm": 230,- "stability": 0.48,- "similarity_boost": 0.78,- "archetype": "storyteller",- "description": "Technical storyteller: translates complexity into narrative"- },- "default": {- "voice_id": "P9S3WZL3JE8uQqgYH5B7",- "name": "Default",- "rate_wpm": 220,- "stability": 0.50,- "similarity_boost": 0.75,- "archetype": "professional",- "description": "Balanced professional delivery"- }- },- "available_voices": {- "description": "Additional ElevenLabs voices for custom agents or personalization",- "voices": [- {- "voice_id": "UGTtbzgh3HObxRjWaSpr",- "gender": "male",- "name": "Extra Male 1",- "archetype": "professional"- },- {- "voice_id": "HKFOb9iktHA85uKXydRT",- "gender": "male",- "name": "Extra Male 2",- "archetype": "professional"- },- {- "voice_id": "wWWn96OtTHu1sn8SRGEr",- "gender": "male",- "name": "Extra Male 3",- "archetype": "professional"- },- {- "voice_id": "EST9Ui6982FZPSi7gCHi",- "gender": "female",- "name": "Extra Female 1",- "archetype": "professional"- },- {- "voice_id": "XhNlP8uwiH6XZSFnH1yL",- "gender": "female",- "name": "Extra Female 2",- "archetype": "professional"- },- {- "voice_id": "aRlmTYIQo6Tlg5SlulGC",- "gender": "female",- "name": "Extra Female 3",- "archetype": "professional"- }- ]- }-}-```--**Note:** All voice IDs are from ElevenLabs' voice library. You can:-- Replace with your own cloned voices-- Use the `available_voices` for custom agent types-- Switch to a different TTS provider (see "Why ElevenLabs" section)-------### Step 3: Create Prosody Enhancer Library--```typescript-// $PAI_DIR/hooks/lib/prosody-enhancer.ts-// Enhances voice output with emotional markers and natural speech patterns--export interface AgentPersonality {- name: string;- rate_wpm: number;- stability: number;- archetype: 'enthusiast' | 'professional' | 'analyst' | 'critic' | 'wise-leader';- energy_level: 'chaotic' | 'expressive' | 'measured' | 'stable';-}--export interface ProsodyConfig {- emotionalMarkers: boolean;- markdownProsody: boolean;- personalityEnhancement: boolean;- contextAnalysis: boolean;-}--/**- * Agent personality configurations- */-const AGENT_PERSONALITIES: Record<string, AgentPersonality> = {- 'pai': {- name: 'PAI',- rate_wpm: 235,- stability: 0.38,- archetype: 'professional',- energy_level: 'expressive'- },- 'intern': {- name: 'Intern',- rate_wpm: 270,- stability: 0.30,- archetype: 'enthusiast',- energy_level: 'chaotic'- },- 'pentester': {- name: 'Pentester',- rate_wpm: 260,- stability: 0.18,- archetype: 'enthusiast',- energy_level: 'chaotic'- },- 'artist': {- name: 'Artist',- rate_wpm: 215,- stability: 0.20,- archetype: 'enthusiast',- energy_level: 'chaotic'- },- 'designer': {- name: 'Designer',- rate_wpm: 226,- stability: 0.52,- archetype: 'critic',- energy_level: 'measured'- },- 'engineer': {- name: 'Engineer',- rate_wpm: 212,- stability: 0.72,- archetype: 'wise-leader',- energy_level: 'stable'- },- 'architect': {- name: 'Architect',- rate_wpm: 205,- stability: 0.75,- archetype: 'wise-leader',- energy_level: 'stable'- },- 'researcher': {- name: 'Researcher',- rate_wpm: 229,- stability: 0.64,- archetype: 'analyst',- energy_level: 'measured'- }-};--/**- * Content patterns for detecting emotional context- */-const CONTENT_PATTERNS = {- // High Energy / Positive- excited: [- /\b(breakthrough|discovered|found it|eureka|amazing|incredible)\b/i,- /\b(wait wait|ooh|wow|check this|look at this)\b/i,- /!{2,}|💥|🔥|⚡/- ],- celebration: [- /\b(finally|at last|phew|we did it|victory)\b/i,- /\b(all .* passing|zero errors|zero (data )?loss)\b/i,- /🎉|🥳|🍾/- ],- insight: [- /\b(wait|aha|I see|that'?s why|now I understand)\b/i,- /\b(this explains|the real issue|actually)\b/i,- /💡|🔦/- ],-- // Success / Achievement- success: [- /\b(completed|finished|done|success|working|fixed|resolved|solved)\b/i,- /\b(all tests? pass|deploy|ship|launch)\b/i,- /✅|✨/- ],- progress: [- /\b(phase .* complete|step .* done)\b/i,- /\b(moving to|now|next|partial|incremental)\b/i,- /📈|⏩/- ],-- // Analysis / Investigation- investigating: [- /\b(analyzing|examining|investigating|tracing)\b/i,- /\b(pattern detected|correlation|cross-referencing)\b/i,- /🔍|🔬|📊/- ],- debugging: [- /\b(bug|error|issue|problem)\b/i,- /\b(tracking|hunting|found it|located)\b/i,- /🐛|🔧/- ],-- // Thoughtful / Careful- caution: [- /\b(warning|careful|slow|partial|incomplete)\b/i,- /\b(needs review|check|verify)\b/i,- /⚠️|⚡/- ],-- // Urgent / Critical- urgent: [- /\b(urgent|critical|down|failing|broken|alert)\b/i,- /\b(immediate|asap|now|quickly|emergency)\b/i,- /🚨|❌|⛔/- ]-};--/**- * Detect emotional context from message content- */-function detectEmotionalContext(message: string): string | null {- // Check for existing emotional markers- if (/\[(💥|✨|⚠️|🚨|🎉|💡|🤔|🔍|📈|🎯|🎨|🐛|📚)/.test(message)) {- return null; // Already has marker- }-- const priorityOrder = [- 'urgent', 'debugging', 'insight', 'celebration', 'excited',- 'investigating', 'progress', 'success', 'caution'- ];-- for (const emotion of priorityOrder) {- const patterns = CONTENT_PATTERNS[emotion as keyof typeof CONTENT_PATTERNS];- if (patterns) {- for (const pattern of patterns) {- if (pattern.test(message)) {- return emotion;- }- }- }- }-- return null;-}--/**- * Get emotional marker for detected emotion- */-function getEmotionalMarker(emotion: string): string {- const markers: Record<string, string> = {- 'excited': '[💥 excited]',- 'celebration': '[🎉 celebration]',- 'insight': '[💡 insight]',- 'success': '[✨ success]',- 'progress': '[📈 progress]',- 'investigating': '[🔍 investigating]',- 'debugging': '[🐛 debugging]',- 'caution': '[⚠️ caution]',- 'urgent': '[🚨 urgent]'- };-- return markers[emotion] || '';-}--/**- * Add personality-specific prosody patterns- */-function addPersonalityProsody(message: string, personality: AgentPersonality): string {- let enhanced = message;-- switch (personality.archetype) {- case 'enthusiast':- if (personality.energy_level === 'chaotic') {- if (!/\.{3}/.test(enhanced) && Math.random() > 0.5) {- enhanced = enhanced.replace(/\b(wait|found|check|look)\b/i, '$1...');- }- if (!/[!?]$/.test(enhanced)) {- enhanced = enhanced.replace(/\.$/, '!');- }- }- break;-- case 'wise-leader':- if (personality.energy_level === 'stable') {- if (/,/.test(enhanced)) {- enhanced = enhanced.replace(/,\s+/, ' -- ');- }- }- break;-- case 'professional':- if (personality.energy_level === 'expressive') {- if (!/\*\*/.test(enhanced)) {- enhanced = enhanced.replace(- /\b(completed|fixed|deployed|built|created|found)\b/i,- '**$1**'- );- }- }- break;-- case 'analyst':- enhanced = enhanced.replace(- /\b(confirmed|verified|analyzed|discovered)\b/i,- '**$1**'- );- break;- }-- return enhanced;-}--/**- * Main prosody enhancement function- */-export function enhanceProsody(- message: string,- agentType: string,- config: ProsodyConfig = {- emotionalMarkers: true,- markdownProsody: true,- personalityEnhancement: true,- contextAnalysis: true- }-): string {- let enhanced = message;-- const personality = AGENT_PERSONALITIES[agentType.toLowerCase()] ||- AGENT_PERSONALITIES['pai'];-- // 1. Context Analysis - Detect emotional context- if (config.contextAnalysis && config.emotionalMarkers) {- const emotion = detectEmotionalContext(enhanced);- if (emotion) {- const marker = getEmotionalMarker(emotion);- if (marker) {- enhanced = `${marker} ${enhanced}`;- }- }- }-- // 2. Personality Enhancement- if (config.personalityEnhancement && config.markdownProsody) {- enhanced = addPersonalityProsody(enhanced, personality);- }-- return enhanced.trim();-}--/**- * Clean message for speech while preserving prosody- */-export function cleanForSpeech(message: string): string {- let cleaned = message;-- // Remove code blocks and inline code- cleaned = cleaned.replace(/```[\s\S]*?```/g, 'code block');- cleaned = cleaned.replace(/`[^`]+`/g, '');-- // Strip loose emoji while preserving markers- const parts: Array<{isMarker: boolean, text: string}> = [];- let lastIndex = 0;- const markerRegex = /\[[^\]]+\]/g;- let match: RegExpExecArray | null;-- while ((match = markerRegex.exec(cleaned)) !== null) {- if (match.index > lastIndex) {- parts.push({- isMarker: false,- text: cleaned.substring(lastIndex, match.index)- });- }- parts.push({- isMarker: true,- text: match[0]- });- lastIndex = match.index + match[0].length;- }-- if (lastIndex < cleaned.length) {- parts.push({- isMarker: false,- text: cleaned.substring(lastIndex)- });- }-- if (parts.length === 0) {- parts.push({- isMarker: false,- text: cleaned- });- }-- // Strip emoji from non-marker parts only- cleaned = parts.map(part => {- if (part.isMarker) {- return part.text;- } else {- return part.text.replace(/\p{Emoji_Presentation}/gu, '');- }- }).join('');-- // Clean up whitespace- cleaned = cleaned.replace(/\s+/g, ' ');-- return cleaned.trim();-}--/**- * Get the voice ID for an agent type- */-export function getVoiceId(agentType: string): string {- // Read from environment or config file- const envKey = `ELEVENLABS_VOICE_${agentType.toUpperCase()}`;- const envVoice = process.env[envKey];- if (envVoice) {- return envVoice;- }-- // Fallback to default- return process.env.ELEVENLABS_VOICE_DEFAULT || '';-}-```-------### Step 4: Create Voice-Enabled Stop Hook--```typescript-#!/usr/bin/env bun-// $PAI_DIR/hooks/stop-hook-voice.ts-// Main agent voice notification with prosody enhancement--import { readFileSync } from 'fs';-import { enhanceProsody, cleanForSpeech, getVoiceId } from './lib/prosody-enhancer';--interface NotificationPayload {- title: string;- message: string;- voice_enabled: boolean;- priority?: 'low' | 'normal' | 'high';- voice_id: string;-}--interface HookInput {- session_id: string;- transcript_path: string;- hook_event_name: string;-}--/**- * Convert Claude content to plain text- */-function contentToText(content: unknown): string {- if (typeof content === 'string') return content;- if (Array.isArray(content)) {- return content- .map(c => {- if (typeof c === 'string') return c;- if (c?.text) return c.text;- if (c?.content) return contentToText(c.content);- return '';- })- .join(' ')- .trim();- }- return '';-}--/**- * Extract completion message with prosody enhancement- */-function extractCompletion(text: string, agentType: string = 'pai'): string {- // Remove system-reminder tags- text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '');-- // Look for COMPLETED section- const patterns = [- /🎯\s*\*{0,2}COMPLETED:?\*{0,2}\s*(.+?)(?:\n|$)/i,- /\*{0,2}COMPLETED:?\*{0,2}\s*(.+?)(?:\n|$)/i- ];-- for (const pattern of patterns) {- const match = text.match(pattern);- if (match && match[1]) {- let completed = match[1].trim();-- // Clean agent tags- completed = completed.replace(/^\[AGENT:\w+\]\s*/i, '');-- // Clean for speech- completed = cleanForSpeech(completed);-- // Enhance with prosody- completed = enhanceProsody(completed, agentType);-- return completed;- }- }-- return 'Completed task';-}--/**- * Read last assistant message from transcript- */-function getLastAssistantMessage(transcriptPath: string): string {- try {- const content = readFileSync(transcriptPath, 'utf-8');- const lines = content.trim().split('\n');-- let lastAssistantMessage = '';-- for (const line of lines) {- if (line.trim()) {- try {- const entry = JSON.parse(line);- if (entry.type === 'assistant' && entry.message?.content) {- const text = contentToText(entry.message.content);- if (text) {- lastAssistantMessage = text;- }- }- } catch {- // Skip invalid JSON lines- }- }- }-- return lastAssistantMessage;- } catch (error) {- console.error('Error reading transcript:', error);- return '';- }-}--/**- * Send notification to voice server- */-async function sendNotification(payload: NotificationPayload): Promise<void> {- const serverUrl = process.env.PAI_VOICE_SERVER || 'http://localhost:8888/notify';-- try {- const response = await fetch(serverUrl, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload),- });-- if (!response.ok) {- console.error('Voice server error:', response.statusText);- }- } catch (error) {- // Fail silently - voice server may not be running- console.error('Voice notification failed (server may be offline):', error);- }-}--async function main() {- let hookInput: HookInput | null = null;-- try {- const decoder = new TextDecoder();- const reader = Bun.stdin.stream().getReader();- let input = '';-- const timeoutPromise = new Promise<void>((resolve) => {- setTimeout(() => resolve(), 500);- });-- const readPromise = (async () => {- while (true) {- const { done, value } = await reader.read();- if (done) break;- input += decoder.decode(value, { stream: true });- }- })();-- await Promise.race([readPromise, timeoutPromise]);-- if (input.trim()) {- hookInput = JSON.parse(input);- }- } catch (error) {- console.error('Error reading hook input:', error);- }-- // Extract completion from transcript- let completion = 'Completed task';- const agentType = 'pai'; // Main agent is your PAI-- if (hookInput?.transcript_path) {- const lastMessage = getLastAssistantMessage(hookInput.transcript_path);- if (lastMessage) {- completion = extractCompletion(lastMessage, agentType);- }- }-- // Get voice ID for this agent- const voiceId = getVoiceId(agentType);-- // Send voice notification- const payload: NotificationPayload = {- title: 'PAI',- message: completion,- voice_enabled: true,- priority: 'normal',- voice_id: voiceId- };-- await sendNotification(payload);-- process.exit(0);-}--main().catch((error) => {- console.error('Stop hook error:', error);- process.exit(0);-});-```-------### Step 5: Create Subagent Voice Hook--```typescript-#!/usr/bin/env bun-// $PAI_DIR/hooks/subagent-stop-hook-voice.ts-// Subagent voice notification with personality-specific delivery--import { readFileSync, existsSync } from 'fs';-import { join, dirname } from 'path';-import { readdirSync, statSync } from 'fs';-import { enhanceProsody, cleanForSpeech, getVoiceId } from './lib/prosody-enhancer';--interface NotificationPayload {- title: string;- message: string;- voice_enabled: boolean;- voice_id: string;-}--async function delay(ms: number): Promise<void> {- return new Promise(resolve => setTimeout(resolve, ms));-}--async function findTaskResult(transcriptPath: string, maxAttempts: number = 2): Promise<{- result: string | null;- agentType: string | null;- description: string | null;-}> {- let actualTranscriptPath = transcriptPath;-- for (let attempt = 0; attempt < maxAttempts; attempt++) {- if (attempt > 0) {- await delay(200);- }-- if (!existsSync(actualTranscriptPath)) {- const dir = dirname(transcriptPath);- if (existsSync(dir)) {- const files = readdirSync(dir)- .filter(f => f.startsWith('agent-') && f.endsWith('.jsonl'))- .map(f => ({ name: f, mtime: statSync(join(dir, f)).mtime }))- .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());-- if (files.length > 0) {- actualTranscriptPath = join(dir, files[0].name);- }- }-- if (!existsSync(actualTranscriptPath)) {- continue;- }- }-- try {- const transcript = readFileSync(actualTranscriptPath, 'utf-8');- const lines = transcript.trim().split('\n');-- for (let i = lines.length - 1; i >= 0; i--) {- try {- const entry = JSON.parse(lines[i]);-- if (entry.type === 'assistant' && entry.message?.content) {- for (const content of entry.message.content) {- if (content.type === 'tool_use' && content.name === 'Task') {- const toolInput = content.input;- const description = toolInput?.description || null;-- for (let j = i + 1; j < lines.length; j++) {- const resultEntry = JSON.parse(lines[j]);- if (resultEntry.type === 'user' && resultEntry.message?.content) {- for (const resultContent of resultEntry.message.content) {- if (resultContent.type === 'tool_result' && resultContent.tool_use_id === content.id) {- let taskOutput: string;- if (typeof resultContent.content === 'string') {- taskOutput = resultContent.content;- } else if (Array.isArray(resultContent.content)) {- taskOutput = resultContent.content- .filter((item: any) => item.type === 'text')- .map((item: any) => item.text)- .join('\n');- } else {- continue;- }-- const agentType = toolInput?.subagent_type || 'default';- return { result: taskOutput, agentType, description };- }- }- }- }- }- }- }- } catch (e) {- // Skip invalid lines- }- }- } catch (e) {- // Will retry- }- }-- return { result: null, agentType: null, description: null };-}--function extractCompletionMessage(taskOutput: string): { message: string | null; agentType: string | null } {- // Look for COMPLETED section with agent tag- const agentPatterns = [- /🎯\s*COMPLETED:\s*\[AGENT:(\w+[-\w]*)\]\s*(.+?)(?:\n|$)/is,- /COMPLETED:\s*\[AGENT:(\w+[-\w]*)\]\s*(.+?)(?:\n|$)/is,- /🎯.*COMPLETED.*\[AGENT:(\w+[-\w]*)\]\s*(.+?)(?:\n|$)/is,- ];-- for (const pattern of agentPatterns) {- const match = taskOutput.match(pattern);- if (match && match[1] && match[2]) {- const agentType = match[1].toLowerCase();- let message = match[2].trim();-- // Clean for speech- message = cleanForSpeech(message);-- // Enhance with prosody- message = enhanceProsody(message, agentType);-- // Format: "AgentName completed [message]"- const agentName = agentType.charAt(0).toUpperCase() + agentType.slice(1);-- // Don't prepend "completed" for greetings or questions- const isGreeting = /^(hey|hello|hi|greetings)/i.test(message);- const isQuestion = message.includes('?');-- const fullMessage = (isGreeting || isQuestion)- ? message- : `${agentName} completed ${message}`;-- return { message: fullMessage, agentType };- }- }-- // Fallback patterns- const genericPatterns = [- /🎯\s*COMPLETED:\s*(.+?)(?:\n|$)/i,- /COMPLETED:\s*(.+?)(?:\n|$)/i,- ];-- for (const pattern of genericPatterns) {- const match = taskOutput.match(pattern);- if (match && match[1]) {- let message = match[1].trim();- message = cleanForSpeech(message);-- if (message.length > 5) {- return { message, agentType: null };- }- }- }-- return { message: null, agentType: null };-}--async function sendNotification(payload: NotificationPayload): Promise<void> {- const serverUrl = process.env.PAI_VOICE_SERVER || 'http://localhost:8888/notify';-- try {- const response = await fetch(serverUrl, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload),- });-- if (!response.ok) {- console.error('Voice server error:', response.statusText);- }- } catch (error) {- // Fail silently- }-}--async function main() {- let input = '';- 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();- if (done) break;- input += decoder.decode(value, { stream: true });- }- })();-- await Promise.race([readPromise, timeoutPromise]);- } catch (e) {- process.exit(0);- }-- if (!input) {- process.exit(0);- }-- let transcriptPath: string;- try {- const parsed = JSON.parse(input);- transcriptPath = parsed.transcript_path;- } catch (e) {- process.exit(0);- }-- if (!transcriptPath) {- process.exit(0);- }-- // Find task result- const { result: taskOutput, agentType } = await findTaskResult(transcriptPath);-- if (!taskOutput) {- process.exit(0);- }-- // Extract completion message- const { message: completionMessage, agentType: extractedAgentType } = extractCompletionMessage(taskOutput);-- if (!completionMessage) {- process.exit(0);- }-- // Determine agent type- const finalAgentType = extractedAgentType || agentType || 'default';-- // Get voice ID for this agent type- const voiceId = getVoiceId(finalAgentType);-- // Send voice notification- const agentName = finalAgentType.charAt(0).toUpperCase() + finalAgentType.slice(1);-- await sendNotification({- title: agentName,- message: completionMessage,- voice_enabled: true,- voice_id: voiceId- });-- process.exit(0);-}--main().catch(console.error);-```-------### Step 6: Register Hooks--Add voice hooks to `~/.claude/settings.json`:--```json-{- "hooks": {- "Stop": [- {- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/stop-hook-voice.ts"- }- ]- }- ],- "SubagentStop": [- {- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/subagent-stop-hook-voice.ts"- }- ]- }- ]- }-}-```-------### Step 7: Set Environment Variables--**If you used the Kai Bundle wizard:** Core variables are in `$PAI_DIR/.env`. You only need to add ElevenLabs credentials there:--```bash-# Add to $PAI_DIR/.env-ELEVENLABS_API_KEY="your-api-key"-```--**For manual installation:** Add to your shell profile (`~/.zshrc`, `~/.bashrc`):--```bash-# Voice configuration-export PAI_VOICE_SERVER="http://localhost:8888/notify"--# ElevenLabs voice IDs (get these from your ElevenLabs account)-export ELEVENLABS_API_KEY="your-api-key"-export ELEVENLABS_VOICE_PAI="P9S3WZL3JE8uQqgYH5B7"-export ELEVENLABS_VOICE_DEFAULT="P9S3WZL3JE8uQqgYH5B7"-# The PAI voice ID is used as default - customize as needed--# Reload-source ~/.zshrc-```-------### Step 8: Set Up ElevenLabs Account--Before creating the voice server, you need an ElevenLabs account and API key.--#### 8.1: Create ElevenLabs Account--1. **Sign up** at [elevenlabs.io](https://elevenlabs.io)-2. **Choose a plan**:- - **Free tier**: 10,000 characters/month - good for testing- - **Starter** ($5/month): 30,000 characters - light personal use- - **Creator** ($22/month): 100,000 characters - recommended for regular use-3. **Verify your email** to activate the account--#### 8.2: Get Your API Key--1. Log in to [elevenlabs.io](https://elevenlabs.io)-2. Click your **profile icon** (top right)-3. Select **"Profile + API key"**-4. Click **"Create API Key"** or copy existing key-5. **Save this key** - you'll need it in Step 10--#### 8.3: Choose Your Voice--1. Go to **"Voices"** in the left sidebar-2. Browse the **Voice Library** or use default voices-3. **Note the Voice ID** for your preferred voice:- - Click on a voice- - The Voice ID is in the URL: `elevenlabs.io/voice-lab/[VOICE_ID]`- - Or find it in voice settings--**Recommended starter voice:** `s3TPKV1kjDlVtZbl4Ksh` (Jamie - UK Male, expressive)--#### 8.4: Test Your API Key--```bash-# Quick test - should return audio (save as test.mp3)-curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/s3TPKV1kjDlVtZbl4Ksh" \- -H "xi-api-key: YOUR_API_KEY_HERE" \- -H "Content-Type: application/json" \- -d '{"text": "Hello, this is a test of the voice system.", "model_id": "eleven_turbo_v2_5"}' \- --output test.mp3--# Play the test audio (macOS)-afplay test.mp3--# Clean up-rm test.mp3-```--If you hear "Hello, this is a test of the voice system" - your API key works!-------### Step 9: Create Voice Server--Create the complete voice server that handles notifications and TTS:--```typescript-#!/usr/bin/env bun-// $PAI_DIR/voice-server/server.ts-// Voice notification server using ElevenLabs TTS--import { serve } from "bun";-import { spawn } from "child_process";-import { homedir } from "os";-import { join } from "path";-import { existsSync, readFileSync } from "fs";--// Load .env from PAI directory (single source of truth for all API keys)-const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');-const envPath = join(paiDir, '.env');-if (existsSync(envPath)) {- const envContent = await Bun.file(envPath).text();- envContent.split('\n').forEach(line => {- const [key, value] = line.split('=');- if (key && value && !key.startsWith('#')) {- process.env[key.trim()] = value.trim();- }- });-}--const PORT = parseInt(process.env.PAI_VOICE_PORT || "8888");-const ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;--if (!ELEVENLABS_API_KEY) {- console.error(`⚠️ ELEVENLABS_API_KEY not found in ${envPath}`);- console.error('Add: ELEVENLABS_API_KEY=your_key_here to $PAI_DIR/.env');-}--// Default voice ID (customize to your preference)-const DEFAULT_VOICE_ID = process.env.ELEVENLABS_VOICE_ID || "s3TPKV1kjDlVtZbl4Ksh";--// Voice configuration types-interface VoiceConfig {- voice_id: string;- voice_name: string;- stability: number;- similarity_boost: number;- description: string;-}--interface VoicesConfig {- default_volume?: number;- voices: Record<string, VoiceConfig>;-}--// 13 Emotional Presets - Prosody System-const EMOTIONAL_PRESETS: Record<string, { stability: number; similarity_boost: number }> = {- 'excited': { stability: 0.7, similarity_boost: 0.9 },- 'celebration': { stability: 0.65, similarity_boost: 0.85 },- 'insight': { stability: 0.55, similarity_boost: 0.8 },- 'creative': { stability: 0.5, similarity_boost: 0.75 },- 'success': { stability: 0.6, similarity_boost: 0.8 },- 'progress': { stability: 0.55, similarity_boost: 0.75 },- 'investigating': { stability: 0.6, similarity_boost: 0.85 },- 'debugging': { stability: 0.55, similarity_boost: 0.8 },- 'learning': { stability: 0.5, similarity_boost: 0.75 },- 'pondering': { stability: 0.65, similarity_boost: 0.8 },- 'focused': { stability: 0.7, similarity_boost: 0.85 },- 'caution': { stability: 0.4, similarity_boost: 0.6 },- 'urgent': { stability: 0.3, similarity_boost: 0.9 },-};--// Load voice configuration-let voicesConfig: VoicesConfig | null = null;-try {- const voicesPath = join(import.meta.dir, '..', 'config', 'voice-personalities.json');- if (existsSync(voicesPath)) {- const voicesContent = readFileSync(voicesPath, 'utf-8');- voicesConfig = JSON.parse(voicesContent);- console.log('✅ Loaded voice personalities from config');- }-} catch (error) {- console.warn('⚠️ Failed to load voice personalities, using defaults');-}--// Extract emotional marker from message-function extractEmotionalMarker(message: string): { cleaned: string; emotion?: string } {- const emojiToEmotion: Record<string, string> = {- '💥': 'excited', '🎉': 'celebration', '💡': 'insight', '🎨': 'creative',- '✨': 'success', '📈': 'progress', '🔍': 'investigating', '🐛': 'debugging',- '📚': 'learning', '🤔': 'pondering', '🎯': 'focused', '⚠️': 'caution', '🚨': 'urgent'- };-- const emotionMatch = message.match(/\[(💥|🎉|💡|🎨|✨|📈|🔍|🐛|📚|🤔|🎯|⚠️|🚨)\s+(\w+)\]/);- if (emotionMatch) {- const emoji = emotionMatch[1];- const emotionName = emotionMatch[2].toLowerCase();- if (emojiToEmotion[emoji] === emotionName) {- return {- cleaned: message.replace(emotionMatch[0], '').trim(),- emotion: emotionName- };- }- }- return { cleaned: message };-}--// Get voice configuration by voice ID or agent name-function getVoiceConfig(identifier: string): VoiceConfig | null {- if (!voicesConfig) return null;- if (voicesConfig.voices[identifier]) return voicesConfig.voices[identifier];- for (const config of Object.values(voicesConfig.voices)) {- if (config.voice_id === identifier) return config;- }- return null;-}--// Sanitize input for TTS - allow natural speech, block dangerous characters-function sanitizeForSpeech(input: string): string {- return input- .replace(/<script/gi, '')- .replace(/\.\.\//g, '')- .replace(/[;&|><`$\\]/g, '')- .replace(/\*\*([^*]+)\*\*/g, '$1')- .replace(/\*([^*]+)\*/g, '$1')- .replace(/`([^`]+)`/g, '$1')- .replace(/#{1,6}\s+/g, '')- .trim()- .substring(0, 500);-}--// Validate input-function validateInput(input: any): { valid: boolean; error?: string; sanitized?: string } {- if (!input || typeof input !== 'string') {- return { valid: false, error: 'Invalid input type' };- }- if (input.length > 500) {- return { valid: false, error: 'Message too long (max 500 characters)' };- }- const sanitized = sanitizeForSpeech(input);- if (!sanitized || sanitized.length === 0) {- return { valid: false, error: 'Message contains no valid content after sanitization' };- }- return { valid: true, sanitized };-}--// Generate speech using ElevenLabs API-async function generateSpeech(- text: string,- voiceId: string,- voiceSettings?: { stability: number; similarity_boost: number }-): Promise<ArrayBuffer> {- if (!ELEVENLABS_API_KEY) {- throw new Error('ElevenLabs API key not configured');- }-- const url = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`;- const settings = voiceSettings || { stability: 0.5, similarity_boost: 0.5 };-- const response = await fetch(url, {- method: 'POST',- headers: {- 'Accept': 'audio/mpeg',- 'Content-Type': 'application/json',- 'xi-api-key': ELEVENLABS_API_KEY,- },- body: JSON.stringify({- text: text,- model_id: 'eleven_turbo_v2_5',- voice_settings: settings,- }),- });-- if (!response.ok) {- const errorText = await response.text();- throw new Error(`ElevenLabs API error: ${response.status} - ${errorText}`);- }-- return await response.arrayBuffer();-}--// Get volume setting from config (defaults to 0.8 = 80%)-function getVolumeSetting(): number {- if (voicesConfig && typeof voicesConfig.default_volume === 'number') {- const vol = voicesConfig.default_volume;- if (vol >= 0 && vol <= 1) return vol;- }- return 0.8;-}--// Play audio using afplay (macOS)-async function playAudio(audioBuffer: ArrayBuffer): Promise<void> {- const tempFile = `/tmp/voice-${Date.now()}.mp3`;- await Bun.write(tempFile, audioBuffer);- const volume = getVolumeSetting();-- return new Promise((resolve, reject) => {- const proc = spawn('/usr/bin/afplay', ['-v', volume.toString(), tempFile]);-- proc.on('error', (error) => {- console.error('Error playing audio:', error);- reject(error);- });-- proc.on('exit', (code) => {- spawn('/bin/rm', [tempFile]); // Clean up temp file- if (code === 0) {- resolve();- } else {- reject(new Error(`afplay exited with code ${code}`));- }- });- });-}--// Escape for AppleScript notifications-function escapeForAppleScript(input: string): string {- return input.replace(/\\/g, '\\\\').replace(/"/g, '\\"');-}--// Send macOS notification with voice-async function sendNotification(- title: string,- message: string,- voiceEnabled = true,- voiceId: string | null = null-) {- const titleValidation = validateInput(title);- const messageValidation = validateInput(message);-- if (!titleValidation.valid) throw new Error(`Invalid title: ${titleValidation.error}`);- if (!messageValidation.valid) throw new Error(`Invalid message: ${messageValidation.error}`);-- const safeTitle = titleValidation.sanitized!;- let safeMessage = messageValidation.sanitized!;-- // Extract emotional marker if present- const { cleaned, emotion } = extractEmotionalMarker(safeMessage);- safeMessage = cleaned;-- // Generate and play voice using ElevenLabs- if (voiceEnabled && ELEVENLABS_API_KEY) {- try {- const voice = voiceId || DEFAULT_VOICE_ID;- const voiceConfig = getVoiceConfig(voice);-- // Determine voice settings (priority: emotional > personality > defaults)- let voiceSettings = { stability: 0.5, similarity_boost: 0.5 };-- if (emotion && EMOTIONAL_PRESETS[emotion]) {- voiceSettings = EMOTIONAL_PRESETS[emotion];- console.log(`🎭 Emotion: ${emotion}`);- } else if (voiceConfig) {- voiceSettings = {- stability: voiceConfig.stability,- similarity_boost: voiceConfig.similarity_boost- };- console.log(`👤 Personality: ${voiceConfig.description}`);- }-- console.log(`🎙️ Generating speech (voice: ${voice}, stability: ${voiceSettings.stability})`);-- const audioBuffer = await generateSpeech(safeMessage, voice, voiceSettings);- await playAudio(audioBuffer);- } catch (error) {- console.error("Failed to generate/play speech:", error);- }- }-- // Display macOS notification- try {- const escapedTitle = escapeForAppleScript(safeTitle);- const escapedMessage = escapeForAppleScript(safeMessage);- const script = `display notification "${escapedMessage}" with title "${escapedTitle}" sound name ""`;- spawn('/usr/bin/osascript', ['-e', script]);- } catch (error) {- console.error("Notification display error:", error);- }-}--// Rate limiting-const requestCounts = new Map<string, { count: number; resetTime: number }>();-const RATE_LIMIT = 10;-const RATE_WINDOW = 60000;--function checkRateLimit(ip: string): boolean {- const now = Date.now();- const record = requestCounts.get(ip);-- if (!record || now > record.resetTime) {- requestCounts.set(ip, { count: 1, resetTime: now + RATE_WINDOW });- return true;- }-- if (record.count >= RATE_LIMIT) return false;- record.count++;- return true;-}--// Start HTTP server-const server = serve({- port: PORT,- async fetch(req) {- const url = new URL(req.url);- const clientIp = req.headers.get('x-forwarded-for') || 'localhost';-- const corsHeaders = {- "Access-Control-Allow-Origin": "http://localhost",- "Access-Control-Allow-Methods": "GET, POST, OPTIONS",- "Access-Control-Allow-Headers": "Content-Type"- };-- if (req.method === "OPTIONS") {- return new Response(null, { headers: corsHeaders, status: 204 });- }-- if (!checkRateLimit(clientIp)) {- return new Response(- JSON.stringify({ status: "error", message: "Rate limit exceeded" }),- { headers: { ...corsHeaders, "Content-Type": "application/json" }, status: 429 }- );- }-- // Main notification endpoint- if (url.pathname === "/notify" && req.method === "POST") {- try {- const data = await req.json();- const title = data.title || "PAI Notification";- const message = data.message || "Task completed";- const voiceEnabled = data.voice_enabled !== false;- const voiceId = data.voice_id || data.voice_name || null;-- if (voiceId && typeof voiceId !== 'string') {- throw new Error('Invalid voice_id');- }-- console.log(`📨 Notification: "${title}" - "${message.substring(0, 50)}..."`);-- await sendNotification(title, message, voiceEnabled, voiceId);-- return new Response(- JSON.stringify({ status: "success", message: "Notification sent" }),- { headers: { ...corsHeaders, "Content-Type": "application/json" }, status: 200 }- );- } catch (error: any) {- console.error("Notification error:", error);- return new Response(- JSON.stringify({ status: "error", message: error.message || "Internal server error" }),- { headers: { ...corsHeaders, "Content-Type": "application/json" }, status: error.message?.includes('Invalid') ? 400 : 500 }- );- }- }-- // Health check endpoint- if (url.pathname === "/health") {- return new Response(- JSON.stringify({- status: "healthy",- port: PORT,- voice_system: "ElevenLabs",- default_voice_id: DEFAULT_VOICE_ID,- api_key_configured: !!ELEVENLABS_API_KEY- }),- { headers: { ...corsHeaders, "Content-Type": "application/json" }, status: 200 }- );- }-- return new Response("PAI Voice Server - POST to /notify", {- headers: corsHeaders,- status: 200- });- },-});--console.log(`🚀 Voice Server running on port ${PORT}`);-console.log(`🎙️ Using ElevenLabs TTS (default voice: ${DEFAULT_VOICE_ID})`);-console.log(`📡 POST to http://localhost:${PORT}/notify`);-console.log(`🔒 Security: CORS restricted to localhost, rate limiting enabled`);-console.log(`🔑 API Key: ${ELEVENLABS_API_KEY ? '✅ Configured' : '❌ Missing'}`);-```-------### Step 10: Create Server Management Scripts--Create scripts to start, stop, and manage the voice server:--#### 10.1: Create Directory Structure--```bash-mkdir -p $PAI_DIR/voice-server-```--#### 10.2: Create Install Script--```bash-#!/bin/bash-# $PAI_DIR/voice-server/install.sh-# Installs the voice server as a macOS LaunchAgent--set -e--RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-NC='\033[0m'--SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"-SERVICE_NAME="com.pai.voice-server"-PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"-LOG_PATH="$HOME/Library/Logs/pai-voice-server.log"-ENV_FILE="$HOME/.env"--echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"-echo -e "${BLUE} PAI Voice Server Installation${NC}"-echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"-echo--# Check for Bun-echo -e "${YELLOW}▶ Checking prerequisites...${NC}"-if ! command -v bun &> /dev/null; then- echo -e "${RED}✗ Bun is not installed${NC}"- echo " Install Bun first: curl -fsSL https://bun.sh/install | bash"- exit 1-fi-echo -e "${GREEN}✓ Bun is installed${NC}"--# Check for existing installation-if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then- echo -e "${YELLOW}⚠ Voice server is already installed${NC}"- read -p "Do you want to reinstall? (y/n): " -n 1 -r- echo- if [[ $REPLY =~ ^[Yy]$ ]]; then- echo -e "${YELLOW}▶ Stopping existing service...${NC}"- launchctl unload "$PLIST_PATH" 2>/dev/null || true- echo -e "${GREEN}✓ Existing service stopped${NC}"- else- echo "Installation cancelled"- exit 0- fi-fi--# Check for ElevenLabs configuration-echo -e "${YELLOW}▶ Checking ElevenLabs configuration...${NC}"-if [ -f "$ENV_FILE" ] && grep -q "ELEVENLABS_API_KEY=" "$ENV_FILE"; then- API_KEY=$(grep "ELEVENLABS_API_KEY=" "$ENV_FILE" | cut -d'=' -f2)- if [ "$API_KEY" != "your_api_key_here" ] && [ -n "$API_KEY" ]; then- echo -e "${GREEN}✓ ElevenLabs API key configured${NC}"- ELEVENLABS_CONFIGURED=true- else- echo -e "${YELLOW}⚠ ElevenLabs API key not configured${NC}"- ELEVENLABS_CONFIGURED=false- fi-else- echo -e "${YELLOW}⚠ No ElevenLabs configuration found${NC}"- ELEVENLABS_CONFIGURED=false-fi--if [ "$ELEVENLABS_CONFIGURED" = false ]; then- echo- echo "To enable AI voices, add your ElevenLabs API key to \$PAI_DIR/.env:"- echo " echo 'ELEVENLABS_API_KEY=your_api_key_here' >> \$PAI_DIR/.env"- echo " Get a key at: https://elevenlabs.io"- echo-fi--# Create LaunchAgent plist-echo -e "${YELLOW}▶ Creating LaunchAgent configuration...${NC}"-mkdir -p "$HOME/Library/LaunchAgents"--cat > "$PLIST_PATH" << EOF-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>Label</key>- <string>${SERVICE_NAME}</string>-- <key>ProgramArguments</key>- <array>- <string>$(which bun)</string>- <string>run</string>- <string>${SCRIPT_DIR}/server.ts</string>- </array>-- <key>WorkingDirectory</key>- <string>${SCRIPT_DIR}</string>-- <key>RunAtLoad</key>- <true/>-- <key>KeepAlive</key>- <dict>- <key>SuccessfulExit</key>- <false/>- </dict>-- <key>StandardOutPath</key>- <string>${LOG_PATH}</string>-- <key>StandardErrorPath</key>- <string>${LOG_PATH}</string>-- <key>EnvironmentVariables</key>- <dict>- <key>HOME</key>- <string>${HOME}</string>- <key>PATH</key>- <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:${HOME}/.bun/bin</string>- </dict>-</dict>-</plist>-EOF--echo -e "${GREEN}✓ LaunchAgent configuration created${NC}"--# Load the LaunchAgent-echo -e "${YELLOW}▶ Starting voice server service...${NC}"-launchctl load "$PLIST_PATH" 2>/dev/null || {- echo -e "${RED}✗ Failed to load LaunchAgent${NC}"- echo " Try manually: launchctl load $PLIST_PATH"- exit 1-}--# Wait for server to start-sleep 2--# Test the server-echo -e "${YELLOW}▶ Testing voice server...${NC}"-if curl -s -f -X GET http://localhost:8888/health > /dev/null 2>&1; then- echo -e "${GREEN}✓ Voice server is running${NC}"-- echo -e "${YELLOW}▶ Sending test notification...${NC}"- curl -s -X POST http://localhost:8888/notify \- -H "Content-Type: application/json" \- -d '{"message": "Voice server installed successfully"}' > /dev/null- echo -e "${GREEN}✓ Test notification sent${NC}"-else- echo -e "${RED}✗ Voice server is not responding${NC}"- echo " Check logs: tail -f $LOG_PATH"- echo " Try running manually: bun run $SCRIPT_DIR/server.ts"- exit 1-fi--# Show summary-echo-echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"-echo -e "${GREEN} ✓ Installation Complete!${NC}"-echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"-echo-echo -e "${BLUE}Service Information:${NC}"-echo " • Service: $SERVICE_NAME"-echo " • Status: Running"-echo " • Port: 8888"-echo " • Logs: $LOG_PATH"-echo-echo -e "${BLUE}Management Commands:${NC}"-echo " • Status: ./status.sh"-echo " • Stop: ./stop.sh"-echo " • Start: ./start.sh"-echo " • Restart: ./restart.sh"-echo-echo -e "${GREEN}The voice server will start automatically when you log in.${NC}"-```--#### 10.3: Create Start Script--```bash-#!/bin/bash-# $PAI_DIR/voice-server/start.sh--SERVICE_NAME="com.pai.voice-server"-PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"-SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"--RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-NC='\033[0m'--echo -e "${YELLOW}▶ Starting Voice Server...${NC}"--if [ ! -f "$PLIST_PATH" ]; then- echo -e "${RED}✗ Service not installed${NC}"- echo " Run ./install.sh first"- exit 1-fi--if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then- echo -e "${YELLOW}⚠ Voice server is already running${NC}"- exit 0-fi--launchctl load "$PLIST_PATH" 2>/dev/null-sleep 2--if curl -s -f -X GET http://localhost:8888/health > /dev/null 2>&1; then- echo -e "${GREEN}✓ Voice server started successfully${NC}"-else- echo -e "${YELLOW}⚠ Server started but not responding yet${NC}"- echo " Check logs: tail -f ~/Library/Logs/pai-voice-server.log"-fi-```--#### 10.4: Create Stop Script--```bash-#!/bin/bash-# $PAI_DIR/voice-server/stop.sh--SERVICE_NAME="com.pai.voice-server"-PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"--RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-NC='\033[0m'--echo -e "${YELLOW}▶ Stopping Voice Server...${NC}"--if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then- launchctl unload "$PLIST_PATH" 2>/dev/null- if [ $? -eq 0 ]; then- echo -e "${GREEN}✓ Voice server stopped${NC}"- else- echo -e "${RED}✗ Failed to stop voice server${NC}"- exit 1- fi-else- echo -e "${YELLOW}⚠ Voice server is not running${NC}"-fi--# Kill any remaining processes on port 8888-if lsof -i :8888 > /dev/null 2>&1; then- echo -e "${YELLOW}▶ Cleaning up port 8888...${NC}"- lsof -ti :8888 | xargs kill -9 2>/dev/null- echo -e "${GREEN}✓ Port 8888 cleared${NC}"-fi-```--#### 10.5: Create Restart Script--```bash-#!/bin/bash-# $PAI_DIR/voice-server/restart.sh--SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"--echo "▶ Restarting Voice Server..."-"$SCRIPT_DIR/stop.sh"-sleep 2-"$SCRIPT_DIR/start.sh"-```--#### 10.6: Create Status Script--```bash-#!/bin/bash-# $PAI_DIR/voice-server/status.sh--SERVICE_NAME="com.pai.voice-server"-LOG_PATH="$HOME/Library/Logs/pai-voice-server.log"-ENV_FILE="$HOME/.env"--RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-NC='\033[0m'--echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"-echo -e "${BLUE} PAI Voice Server Status${NC}"-echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"-echo--echo -e "${BLUE}Service Status:${NC}"-if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then- PID=$(launchctl list | grep "$SERVICE_NAME" | awk '{print $1}')- if [ "$PID" != "-" ]; then- echo -e " ${GREEN}✓ Service is loaded (PID: $PID)${NC}"- else- echo -e " ${YELLOW}⚠ Service is loaded but not running${NC}"- fi-else- echo -e " ${RED}✗ Service is not loaded${NC}"-fi--echo-echo -e "${BLUE}Server Status:${NC}"-if curl -s -f -X GET http://localhost:8888/health > /dev/null 2>&1; then- echo -e " ${GREEN}✓ Server is responding on port 8888${NC}"- HEALTH=$(curl -s http://localhost:8888/health)- echo " Response: $HEALTH"-else- echo -e " ${RED}✗ Server is not responding${NC}"-fi--echo-echo -e "${BLUE}ElevenLabs Configuration:${NC}"-if [ -f "$ENV_FILE" ] && grep -q "ELEVENLABS_API_KEY=" "$ENV_FILE"; then- API_KEY=$(grep "ELEVENLABS_API_KEY=" "$ENV_FILE" | cut -d'=' -f2)- if [ -n "$API_KEY" ] && [ "$API_KEY" != "your_api_key_here" ]; then- echo -e " ${GREEN}✓ API key configured${NC}"- else- echo -e " ${YELLOW}⚠ API key not set${NC}"- fi-else- echo -e " ${YELLOW}⚠ No configuration found${NC}"-fi--echo-echo -e "${BLUE}Recent Logs:${NC}"-if [ -f "$LOG_PATH" ]; then- echo " Log file: $LOG_PATH"- echo " Last 5 lines:"- tail -5 "$LOG_PATH" | while IFS= read -r line; do- echo " $line"- done-else- echo -e " ${YELLOW}⚠ No log file found${NC}"-fi--echo-echo -e "${BLUE}Test Command:${NC}"-echo " curl -X POST http://localhost:8888/notify \\"-echo " -H 'Content-Type: application/json' \\"-echo " -d '{\"message\":\"Hello from PAI\"}'"-```--#### 10.7: Make Scripts Executable--```bash-chmod +x $PAI_DIR/voice-server/*.sh-```-------### Step 11: Configure Environment Variables--Add your ElevenLabs credentials to `$PAI_DIR/.env` (the single source of truth for all API keys):--```bash-# Add to $PAI_DIR/.env-PAI_ENV="${PAI_DIR:-$HOME/.config/pai}/.env"-echo 'ELEVENLABS_API_KEY=your_actual_api_key_here' >> "$PAI_ENV"-echo 'ELEVENLABS_VOICE_ID=s3TPKV1kjDlVtZbl4Ksh' >> "$PAI_ENV"-```--**Optionally add convenience variables to your shell profile** (`~/.zshrc` or `~/.bashrc`):--```bash-# PAI Voice System (optional - for CLI access)-export PAI_VOICE_SERVER="http://localhost:8888/notify"-export PAI_VOICE_PORT="8888"-```-------### Step 12: Install and Verify--Follow this complete verification sequence to ensure everything works end-to-end.--#### 12.1: Verify All Files Are In Place--```bash-# Check hook files-echo "=== Checking Hooks ==="-ls -la $PAI_DIR/hooks/stop-hook-voice.ts-ls -la $PAI_DIR/hooks/subagent-stop-hook-voice.ts--# Check prosody library-echo "=== Checking Prosody Library ==="-ls -la $PAI_DIR/hooks/lib/prosody-enhancer.ts--# Check voice configuration-echo "=== Checking Voice Config ==="-ls -la $PAI_DIR/config/voice-personalities.json--# Check voice server-echo "=== Checking Voice Server ==="-ls -la $PAI_DIR/voice-server/server.ts-ls -la $PAI_DIR/voice-server/install.sh-ls -la $PAI_DIR/voice-server/start.sh-ls -la $PAI_DIR/voice-server/stop.sh-ls -la $PAI_DIR/voice-server/restart.sh-ls -la $PAI_DIR/voice-server/status.sh-```--**Expected:** All files should exist. If any are missing, re-create them from the steps above.--#### 12.2: Verify Environment Variables--```bash-# Check ElevenLabs API key is set-echo "=== Checking Environment ==="-PAI_ENV="${PAI_DIR:-$HOME/.config/pai}/.env"-grep "ELEVENLABS_API_KEY" "$PAI_ENV"-# Should show your key (not "your_api_key_here")--# Test the API key works-echo "=== Testing ElevenLabs API Key ==="-curl -s -X POST "https://api.elevenlabs.io/v1/text-to-speech/s3TPKV1kjDlVtZbl4Ksh" \- -H "xi-api-key: $(grep ELEVENLABS_API_KEY "$PAI_ENV" | cut -d'=' -f2)" \- -H "Content-Type: application/json" \- -d '{"text": "API key verified.", "model_id": "eleven_turbo_v2_5"}' \- --output /tmp/test-voice.mp3 && \- afplay /tmp/test-voice.mp3 && \- rm /tmp/test-voice.mp3 && \- echo "✅ ElevenLabs API key is working"-```--**Expected:** You should hear "API key verified" spoken aloud.--#### 12.3: Install and Start the Voice Server--```bash-# Install the voice server as a LaunchAgent-cd $PAI_DIR/voice-server-./install.sh--# Verify it's running-./status.sh-```--**Expected:** You should see "Voice server installed successfully" spoken aloud, and the status should show the server running on port 8888.--#### 12.4: Test Voice Server Health--```bash-# Health check-echo "=== Testing Health Endpoint ==="-curl -s http://localhost:8888/health | jq .--# Expected output:-# {-# "status": "healthy",-# "port": 8888,-# "voice_system": "ElevenLabs",-# "default_voice_id": "s3TPKV1kjDlVtZbl4Ksh",-# "api_key_configured": true-# }-```--#### 12.5: Test Voice Notification (End-to-End)--```bash-# Send a test notification with voice-echo "=== Sending Test Notification ==="-curl -X POST http://localhost:8888/notify \- -H "Content-Type: application/json" \- -d '{- "title": "PAI",- "message": "Voice system is working perfectly!",- "voice_enabled": true- }'-```--**Expected:** You should hear "Voice system is working perfectly!" spoken aloud in the default PAI voice.--#### 12.6: Test Agent Voice Personalities--```bash-# Test different agent voices-echo "=== Testing Agent Voices ==="--# Engineer voice (wise-leader archetype)-curl -X POST http://localhost:8888/notify \- -H "Content-Type: application/json" \- -d '{- "title": "Engineer",- "message": "The architecture has been reviewed and approved.",- "voice_enabled": true,- "voice_id": "iLVmqjzCGGvqtMCk6vVQ"- }'--sleep 5--# Intern voice (enthusiast archetype)-curl -X POST http://localhost:8888/notify \- -H "Content-Type: application/json" \- -d '{- "title": "Intern",- "message": "I found it! The bug was in the authentication module!",- "voice_enabled": true,- "voice_id": "d3MFdIuCfbAIwiu7jC4a"- }'-```--**Expected:** You should hear two different voices - Engineer should sound measured and thoughtful, Intern should sound excited and energetic.--#### 12.7: Verify Hooks Are Registered--```bash-# Check settings.json for hook configuration-echo "=== Checking Hook Registration ==="-cat ~/.claude/settings.json | jq '.hooks'--# Should show Stop and SubagentStop hooks-```--#### 12.8: Full Integration Test--The final test is to have your AI agent complete a task and verify you hear the voice notification:--1. **Restart Claude Code** (to load the new hooks)-2. **Ask your PAI a simple question** like "What is 2+2?"-3. **Wait for completion** - you should hear the 🎯 COMPLETED message spoken aloud--If you don't hear voice on task completion:-- Check the logs: `tail -f ~/Library/Logs/pai-voice-server.log`-- Verify hooks are running: Look for hook output in Claude Code's stderr-------## Troubleshooting--### Server Won't Start--**Symptom:** `./install.sh` fails or server doesn't respond--```bash-# Check if port 8888 is in use-lsof -i :8888--# If something else is using it, kill it-lsof -ti :8888 | xargs kill -9--# Try manual start to see errors-bun run $PAI_DIR/voice-server/server.ts-```--### No Sound Playing--**Symptom:** Server responds but no audio plays--```bash-# Check macOS audio-# 1. Make sure volume is up-# 2. Check audio output device is correct--# Test afplay directly-echo "Testing audio" | say # Should use macOS built-in TTS--# Check ElevenLabs is returning audio-curl -s -X POST "https://api.elevenlabs.io/v1/text-to-speech/s3TPKV1kjDlVtZbl4Ksh" \- -H "xi-api-key: YOUR_KEY" \- -H "Content-Type: application/json" \- -d '{"text": "test", "model_id": "eleven_turbo_v2_5"}' \- --output /tmp/test.mp3 && file /tmp/test.mp3-# Should show: Audio file with ID3-```--### API Key Errors--**Symptom:** "ElevenLabs API error: 401"--1. Verify your API key at [elevenlabs.io](https://elevenlabs.io) → Profile → API Key-2. Check the key in `$PAI_DIR/.env` matches exactly (no extra spaces or quotes)-3. Ensure your ElevenLabs subscription is active--### Hooks Not Running--**Symptom:** Tasks complete but no voice notification--```bash-# Check hooks are in settings.json-cat ~/.claude/settings.json | jq '.hooks'--# Check hooks are executable-ls -la $PAI_DIR/hooks/stop-hook-voice.ts--# Test hook manually (pipe simulated input)-echo '{"session_id":"test","transcript_path":"/tmp/test.jsonl"}' | \- bun run $PAI_DIR/hooks/stop-hook-voice.ts-```--### Voice Sounds Robotic--**Symptom:** Speech plays but quality is poor--- Ensure you're using `eleven_turbo_v2_5` model (already default in server)-- Try different voice IDs for better fit-- Adjust stability/similarity_boost in voice config--### Rate Limiting--**Symptom:** "Rate limit exceeded" errors--The server has built-in rate limiting (10 requests/minute per IP). If you're testing heavily:--```bash-# Wait 60 seconds, or restart the server to reset-./restart.sh-```--### Common Error Messages--| Error | Cause | Fix |-|-------|-------|-----|-| "ELEVENLABS_API_KEY not found" | Missing .env | Add key to `$PAI_DIR/.env` |-| "Voice server is not responding" | Server crashed | `./restart.sh` |-| "Invalid voice_id" | Wrong voice ID format | Check voice ID exists in ElevenLabs |-| "afplay exited with code" | Audio playback failed | Check macOS audio settings |--### Logs Location--```bash-# Voice server logs-tail -f ~/Library/Logs/pai-voice-server.log--# Claude Code logs (for hook output)-# Check Claude Code's terminal output-```-------## Quick Reference--### Management Commands--```bash-cd $PAI_DIR/voice-server--./status.sh # Check if server is running-./start.sh # Start the server-./stop.sh # Stop the server-./restart.sh # Restart the server-```--### Test Notification--```bash-curl -X POST http://localhost:8888/notify \- -H "Content-Type: application/json" \- -d '{"message": "Your message here"}'-```--### File Locations--| File | Location |-|------|----------|-| Voice Server | `$PAI_DIR/voice-server/server.ts` |-| Management Scripts | `$PAI_DIR/voice-server/*.sh` |-| Stop Hook | `$PAI_DIR/hooks/stop-hook-voice.ts` |-| Subagent Hook | `$PAI_DIR/hooks/subagent-stop-hook-voice.ts` |-| Prosody Library | `$PAI_DIR/hooks/lib/prosody-enhancer.ts` |-| Voice Config | `$PAI_DIR/config/voice-personalities.json` |-| Server Logs | `~/Library/Logs/pai-voice-server.log` |-| LaunchAgent | `~/Library/LaunchAgents/com.pai.voice-server.plist` |-------## Voice Personality System--### Archetypes--| Archetype | Energy | Voice Characteristics | Example Agents |-|-----------|--------|----------------------|----------------|-| **Enthusiast** | Chaotic/Expressive | Fast, variable, exclamatory | PAI, Intern, Pentester, Artist |-| **Storyteller** | Expressive | Warm, engaging, narrative flow | Writer |-| **Analyst** | Measured | Confident, findings-focused | Researcher |-| **Critic** | Measured | Precise, sophisticated, deliberate | Designer |-| **Wise Leader** | Stable | Slow, thoughtful, em-dashes for pauses | Engineer, Architect |--### Prosody Elements--| Element | Example | Effect |-|---------|---------|--------|-| `**bold**` | `**fixed** the bug` | Emphasis |-| `...` | `wait... found it` | Pause |-| `--` | `Consider this -- the implications` | Thoughtful break |-| `!` | `Success!` | Excitement |-| `[marker]` | `[✨ success]` | Emotional context |--### Emotional Markers--| Marker | Trigger | Use |-|--------|---------|-----|-| `[💥 excited]` | breakthroughs | High energy |-| `[✨ success]` | completions | Achievement |-| `[🎉 celebration]` | milestones | Victory |-| `[💡 insight]` | discoveries | Realization |-| `[🔍 investigating]` | analysis | Research |-| `[🐛 debugging]` | bug work | Problem solving |-| `[⚠️ caution]` | warnings | Careful |-| `[🚨 urgent]` | critical | Emergency |-------## Configuration--**Environment Variables:**--| Variable | Default | Purpose |-|----------|---------|---------|-| `PAI_VOICE_SERVER` | `http://localhost:8888/notify` | Voice server URL |-| `ELEVENLABS_API_KEY` | - | ElevenLabs API key |-| `ELEVENLABS_VOICE_PAI` | `P9S3WZL3JE8uQqgYH5B7` | Main PAI voice |-| `ELEVENLABS_VOICE_DEFAULT` | `P9S3WZL3JE8uQqgYH5B7` | Fallback voice |--**Graceful Degradation:**--If the voice server is offline:-- Hooks complete silently (exit 0)-- No errors shown to user-- Work continues uninterrupted-------## Customization--### Recommended Customization--**What to Customize:** Voice selection and persona mapping--**Why:** The default voice works, but PAI becomes truly personal when it speaks with a voice that resonates with you. Spending time selecting and mapping voices transforms PAI from "a system that talks" to "your AI's voice."--**Process:**--1. **Explore ElevenLabs Voice Library**- - Browse [ElevenLabs Voice Library](https://elevenlabs.io/voice-library)- - Listen to at least 10-15 different voices- - Note voice IDs for ones that feel right--2. **Define Your Voice Mapping**- Have a conversation with your AI to explore preferences:- ```- "I want to customize my PAI voices. For the main PAI voice, I want- something [professional/warm/energetic/calm]. For notifications,- maybe something [shorter/punchier/softer]. Let's explore what- feels right..."- ```--3. **Test with Real Content**- - Try different voices with actual PAI outputs- - Test emotional markers with different voice models- - Listen for naturalness with your typical message length--4. **Update Environment Variables**- ```bash- # In $PAI_DIR/.env- ELEVENLABS_VOICE_PAI="your-chosen-voice-id"- ELEVENLABS_VOICE_DEFAULT="your-fallback-voice-id"- ```--**Expected Outcome:** PAI speaks in a voice that feels natural and personal to you. The voice becomes part of your PAI's identity rather than a generic TTS output.--### Optional Customization--| Customization | File | Impact |-|--------------|------|--------|-| Custom emotional markers | `voice-server/server.ts` | Add your own prosody tags beyond the defaults |-| Message preprocessing | `voice-server/server.ts` | Custom text cleanup before TTS |-| Volume/speed defaults | ElevenLabs dashboard | Adjust voice characteristics |-| Multi-voice personas | `.env` + server config | Different voices for different agent types |-| Notification sounds | `voice-server/server.ts` | Add audio cues before/after speech |-| Queue behavior | `voice-server/server.ts` | Adjust how overlapping messages are handled |-------## Credits--- **Original concept**: Daniel Miessler - developed as part of the PAI (Personal AI) project-- **ElevenLabs**: Text-to-speech engine-- **Prosody research**: ElevenLabs eleven_turbo_v2_5 emotional marker support-- **Voice IDs**: ElevenLabs public voice library - customize with your own voices--## Related Work--- **ElevenLabs** - Industry-leading text-to-speech synthesis-- **Prosody research** - Natural speech rhythm and intonation patterns-- **Accessibility systems** - Voice output for enhanced accessibility--## Works Well With--- **kai-hook-system** - Required; Stop hooks trigger voice notifications-- **kai-core-install** - Required; Skills, identity, and response format drive voice output-- **kai-history-system** - History capture can trigger voice announcements--## Recommended--- **kai-hook-system** - Required; provides the event triggers for voice output-- **kai-core-install** - Required; defines skills, agent personalities, and response format--## Relationships--### Parent Of-*None - this is an output layer, not a foundation for other packs.*--### Child Of-- **kai-hook-system** - Uses Stop and SubagentStop hooks for voice triggers-- **kai-core-install** - Agent personalities from CORE skill map to voice configurations--### Sibling Of-- **kai-history-system** - Both consume hook events for their functionality--### Part Of Collection-**Kai Core Bundle** - One of 4 foundational packs that together create the complete Kai personal AI infrastructure.-------## Changelog--### 1.1.0 - 2025-12-29 (Updated 2025-12-30)-- **END-TO-END COMPLETE RELEASE**-- Updated pack icon with new Kai Voice System design (cache-busted filename)-- Added complete voice server implementation (server.ts)-- Added server management scripts (install.sh, start.sh, stop.sh, restart.sh, status.sh)-- Added macOS LaunchAgent auto-start configuration-- Added detailed ElevenLabs account setup walkthrough (Steps 8.1-8.4)-- Added comprehensive verification sequence (Steps 12.1-12.8)-- Added full troubleshooting section with common issues and fixes-- Added quick reference section with file locations-- Updated dependencies to include kai-core-install (replaces kai-skill-system + kai-identity)-- Pack now meets PAI End-to-End Completeness Requirements--### 1.0.0 - 2025-12-29-- Initial release-- Prosody enhancement library with 9 emotional markers-- Voice-enabled stop hooks for main and subagents-- Agent personality voice mapping system-- ElevenLabs integration pattern-- Graceful degradation when voice server offline