Skip to content

⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.

feat: Migrate all packs to directory-based structure (v2.0)

Daniel Miessler1c34d06e5944
diff --git a/Bundles/Kai/README.md b/Bundles/Kai/README.md
index 32e20e35..bdf4fc32 100644
--- a/Bundles/Kai/README.md
+++ b/Bundles/Kai/README.md
@@ -2,10 +2,72 @@
<img src="kai.png" alt="The Official PAI (Kai) Bundle" width="256">
</p>
-# The Official PAI (Kai) Bundle v1.2.0
+# The Official PAI (Kai) Bundle v2.0.0
> **FOR AI AGENTS:** You are about to install the complete Kai bundle. Run the wizard, then install each pack in order.
+---
+
+## 🚨 CRITICAL: Full Implementation Required (For AI Agents)
+
+> **MANDATORY: Read this section before installing ANY pack in this bundle.**
+
+### The Problem
+
+AI agents systematically create "simplified" versions of pack implementations. Instead of the full 268-line specification, they create 50-line "equivalents." **This breaks the system and wastes the user's time.**
+
+### The Rules for This Bundle
+
+1. **EVERY PACK = FULL IMPLEMENTATION** - No shortcuts, no simplification
+2. **EVERY FILE SPECIFIED = EVERY FILE CREATED** - Count them
+3. **EVERY LINE OF CODE = EVERY LINE OF CODE** - Don't summarize
+4. **IF YOU CAN'T DO IT FULLY, STOP AND SAY SO** - Don't create partial implementations
+
+### Per-Pack Installation Checklist
+
+**For EACH pack you install, confirm:**
+
+```markdown
+## Pack: [pack-name] Installation Verification
+
+- [ ] All directories created as specified
+- [ ] All files created (counted: X of Y)
+- [ ] Code files contain COMPLETE implementations
+- [ ] YAML/JSON files contain ALL entries
+- [ ] Verification commands passed
+- [ ] No "simplified" or "equivalent" versions created
+```
+
+### Full Bundle Completion Checklist
+
+**After ALL packs are installed, confirm:**
+
+```markdown
+## Kai Bundle Installation Complete
+
+### Pack Status
+- [ ] kai-hook-system - FULLY installed, verified
+- [ ] kai-history-system - FULLY installed, verified
+- [ ] kai-core-install - FULLY installed, verified
+- [ ] kai-voice-system - FULLY installed, verified (if applicable)
+
+### Integration Status
+- [ ] ~/.claude directory structure correct
+- [ ] settings.json contains all hook registrations
+- [ ] Startup hook fires on new session
+- [ ] Claude Code restarted to activate hooks
+
+### Quality Confirmation
+- [ ] NO simplified implementations
+- [ ] NO missing files
+- [ ] NO summarized configurations
+- [ ] User informed of required customizations
+```
+
+**Present this completed checklist to the user. If ANY item fails, you are NOT done.**
+
+---
+
## Quick Start
```bash
@@ -45,20 +107,30 @@ When fully installed, the Kai bundle gives you:
| # | Pack | Purpose | Dependencies |
|---|------|---------|--------------|
-| 1 | [kai-hook-system](../../Packs/kai-hook-system.md) | Event-driven automation | None |
-| 2 | [kai-history-system](../../Packs/kai-history-system.md) | Memory and capture | Hooks |
-| 3 | [kai-core-install](../../Packs/kai-core-install.md) | Skills + Identity + Architecture | Hooks, History |
-| 4 | [kai-voice-system](../../Packs/kai-voice-system.md) | Voice notifications (optional) | Hooks, Core |
+| 1 | [kai-hook-system](../../Packs/kai-hook-system/) | Event-driven automation | None |
+| 2 | [kai-history-system](../../Packs/kai-history-system/) | Memory and capture | Hooks |
+| 3 | [kai-core-install](../../Packs/kai-core-install/) | Skills + Identity + Architecture | Hooks, History |
+| 4 | [kai-prompting-skill](../../Packs/kai-prompting-skill/) | Meta-prompting & templates | Core |
+| 5 | [kai-voice-system](../../Packs/kai-voice-system/) | Voice notifications (optional) | Hooks, Core |
+| 6 | [kai-agents-skill](../../Packs/kai-agents-skill/) | Dynamic agent composition (optional) | Core, Voice (optional) |
+| 7 | [kai-art-skill](../../Packs/kai-art-skill/) | Visual content generation (optional) | Core |
+| 8 | [kai-observability-server](../../Packs/kai-observability-server/) | Multi-agent monitoring (optional) | Hooks |
### How to Install Packs
-Give each pack file to your AI and ask it to install:
+Give each pack directory to your AI and ask it to install:
```
-"Install kai-hook-system pack"
+"Install the kai-hook-system pack from PAI/Packs/kai-hook-system/"
```
-The AI will read the pack and follow the installation instructions inside.
+The AI will:
+1. Read the pack's `README.md` for context
+2. Follow `INSTALL.md` step by step
+3. Copy files from `src/` to your system
+4. Complete `VERIFY.md` checklist to confirm success
+
+**Note:** Each pack is now a directory (v2.0 format) containing README.md, INSTALL.md, VERIFY.md, and a `src/` folder with actual code files.
### Why Order Matters
@@ -115,9 +187,15 @@ mv ~/.claude-BACKUP ~/.claude
## What Are Packs and Bundles?
-**Packs** are complete subsystems organized around a single capability. For example, `kai-hook-system` provides an entire event-driven automation framework.
+**Packs** are complete subsystems organized around a single capability. Each pack is a directory containing:
+- `README.md` - Overview, architecture, what it solves
+- `INSTALL.md` - Step-by-step installation instructions
+- `VERIFY.md` - Mandatory verification checklist
+- `src/` - Actual source code files (TypeScript, YAML, etc.)
+
+For example, `kai-hook-system` provides an entire event-driven automation framework with all code files ready to copy.
-**Bundles** are curated combinations of packs designed to work together. The Kai Bundle is 4 packs that form a complete AI infrastructure.
+**Bundles** are curated combinations of packs designed to work together. The Kai Bundle is 8 packs that form a complete AI infrastructure (4 required + 4 optional).
---
@@ -144,6 +222,13 @@ The Kai system embeds these principles from [PAI](https://danielmiessler.com/blo
## Changelog
+### 2.0.0 - 2025-12-31
+- **Directory-based Packs:** All packs migrated from single markdown files to directory structure
+- **New Pack Format:** Each pack now contains README.md, INSTALL.md, VERIFY.md, and src/ directory
+- **Actual Code Files:** Source code now in real .ts, .yaml, .hbs files (not embedded in markdown)
+- **Four New Packs:** Added kai-prompting-skill, kai-agents-skill, kai-art-skill, kai-observability-server
+- **Improved Installation:** AI agents copy actual files instead of extracting from markdown blocks
+
### 1.2.0 - 2025-12-30
- **AI System Detection:** Scans for Claude Code, Cursor, Windsurf, Cline, Aider, Continue
- **Clear Communication:** Shows exactly what was detected and what will be backed up
diff --git a/Bundles/Kai/install.ts b/Bundles/Kai/install.ts
index 7b1f27c6..0546dd9f 100644
--- a/Bundles/Kai/install.ts
+++ b/Bundles/Kai/install.ts
@@ -462,18 +462,58 @@ async function main() {
const coreStackMd = generateCoreStackMd(config);
await Bun.write(`${claudeDir}/skills/CORE/CoreStack.md`, coreStackMd);
- // Create .env file
+ // Create .env file (no quotes around values - .env format standard)
console.log("Creating .env file...");
const envFileContent = `# PAI Environment Configuration
# Created by Kai Bundle installer - ${new Date().toISOString().split("T")[0]}
-DA="${config.daName}"
-TIME_ZONE="${config.timeZone}"
-${config.elevenLabsApiKey ? `ELEVENLABS_API_KEY="${config.elevenLabsApiKey}"` : "# ELEVENLABS_API_KEY="}
-${config.elevenLabsVoiceId ? `ELEVENLABS_VOICE_ID="${config.elevenLabsVoiceId}"` : "# ELEVENLABS_VOICE_ID="}
+DA=${config.daName}
+TIME_ZONE=${config.timeZone}
+${config.elevenLabsApiKey ? `ELEVENLABS_API_KEY=${config.elevenLabsApiKey}` : "# ELEVENLABS_API_KEY="}
+${config.elevenLabsVoiceId ? `ELEVENLABS_VOICE_ID=${config.elevenLabsVoiceId}` : "# ELEVENLABS_VOICE_ID="}
`;
await Bun.write(`${claudeDir}/.env`, envFileContent);
+ // Create settings.json with environment variables for Claude Code
+ // This ensures env vars are available immediately without shell sourcing
+ console.log("Creating settings.json...");
+ const settingsJson: Record<string, unknown> = {
+ env: {
+ DA: config.daName,
+ TIME_ZONE: config.timeZone,
+ PAI_DIR: claudeDir,
+ PAI_SOURCE_APP: config.daName,
+ },
+ };
+ if (config.elevenLabsApiKey) {
+ (settingsJson.env as Record<string, string>).ELEVENLABS_API_KEY = config.elevenLabsApiKey;
+ }
+ if (config.elevenLabsVoiceId) {
+ (settingsJson.env as Record<string, string>).ELEVENLABS_VOICE_ID = config.elevenLabsVoiceId;
+ }
+
+ // Check for existing settings.json and merge if present
+ const settingsPath = `${claudeDir}/settings.json`;
+ let existingSettings: Record<string, unknown> = {};
+ try {
+ const existingContent = await Bun.file(settingsPath).text();
+ existingSettings = JSON.parse(existingContent);
+ } catch {
+ // No existing settings.json, start fresh
+ }
+
+ // Merge env vars (preserve other settings like hooks)
+ const mergedSettings = {
+ ...existingSettings,
+ env: {
+ ...(existingSettings.env as Record<string, string> || {}),
+ ...(settingsJson.env as Record<string, string>),
+ },
+ };
+
+ await Bun.write(settingsPath, JSON.stringify(mergedSettings, null, 2) + "\n");
+ console.log("✓ Created settings.json with environment variables");
+
// Add to shell profile
console.log("Updating shell profile...");
const shell = process.env.SHELL || "/bin/zsh";
@@ -530,6 +570,7 @@ Files created:
- ~/.claude/skills/CORE/Contacts.md
- ~/.claude/skills/CORE/CoreStack.md
- ~/.claude/.env
+ - ~/.claude/settings.json (env vars for Claude Code)
Next steps:
diff --git a/Bundles/README.md b/Bundles/README.md
index 4eafb169..66e938d4 100644
--- a/Bundles/README.md
+++ b/Bundles/README.md
@@ -6,6 +6,51 @@
> **FOR AI AGENTS:** Bundles are curated collections of packs. When a user asks you to install a bundle, read the bundle's README.md file and install each pack in the specified order.
+## 🚨 CRITICAL: Full Implementation Required (For AI Agents)
+
+> **STOP. READ THIS BEFORE INSTALLING ANY BUNDLE.**
+
+### The Problem
+
+AI agents often "helpfully" simplify implementations. Instead of creating the full documented specification, they create abbreviated "equivalent" versions. **This is WRONG and breaks the system.**
+
+### The Rules
+
+1. **IMPLEMENT EVERYTHING EXACTLY AS DOCUMENTED** - No simplification, no shortcuts
+2. **CREATE ALL SPECIFIED FILES** - If a pack says 8 files, create 8 files
+3. **INCLUDE ALL CONTENT** - Full code blocks, full YAML, full configurations
+4. **NEVER CREATE "EQUIVALENTS"** - The exact documented version is required
+5. **COMPLETE THE CHECKLIST** - Every bundle installation MUST end with verification
+
+### Mandatory Bundle Completion Checklist
+
+**After installing ALL packs in a bundle, complete this checklist:**
+
+```markdown
+## Bundle Installation Verification
+
+### Pack Installation Status
+- [ ] Pack 1: [name] - ALL files created, ALL code complete
+- [ ] Pack 2: [name] - ALL files created, ALL code complete
+- [ ] Pack 3: [name] - ALL files created, ALL code complete
+- [ ] (continue for each pack...)
+
+### Integration Verification
+- [ ] Directory structure matches bundle specification
+- [ ] All hooks registered in settings.json
+- [ ] All dependencies between packs satisfied
+- [ ] Verification commands from EACH pack passed
+
+### Final Confirmation
+- [ ] No "simplified" or "equivalent" implementations used
+- [ ] Line counts approximately match documented code
+- [ ] User informed of any customization needed
+```
+
+**If ANY checkbox fails, the bundle is NOT installed.**
+
+---
+
Curated collections of packs that work together to achieve a larger goal.
---
@@ -14,7 +59,13 @@ Curated collections of packs that work together to achieve a larger goal.
A **bundle** is a curated collection of PAI packs designed to work together as a harmonious system.
-**Packs** are collections of functionality organized around a single theme or capability—each pack is a complete subsystem, not an individual ingredient. For example, a hook system pack contains an entire event-driven automation framework.
+**Packs** are directories containing complete subsystems organized around a single capability. Each pack contains:
+- `README.md` - Overview, architecture, what it solves
+- `INSTALL.md` - Step-by-step installation instructions
+- `VERIFY.md` - Mandatory verification checklist
+- `src/` - Actual source code files (TypeScript, YAML, etc.)
+
+For example, `kai-hook-system` provides an entire event-driven automation framework with all code files ready to copy.
**Bundles** are combinations of packs that work exceptionally well together—a harmonious system from a single author or unified around a single theme. The packs in a bundle were designed to integrate seamlessly, creating emergent capabilities greater than the sum of their parts.
@@ -85,8 +136,8 @@ Bundles are collections - you can install just the packs you want from a bundle.
| Aspect | Pack | Bundle |
|--------|------|--------|
| **Scope** | Complete subsystem around one theme | Harmonious combination of subsystems |
-| **Structure** | Single markdown file | Directory with README.md |
-| **Code** | Contains complete code for that system | References pack files |
+| **Structure** | Directory with README.md, INSTALL.md, VERIFY.md, src/ | Directory with README.md referencing packs |
+| **Code** | Contains actual source files in src/ | References pack directories |
| **Installation** | Can be standalone | Ordered sequence with dependencies |
| **Value** | Complete functionality for one domain | Integrated experience across domains |
@@ -252,4 +303,4 @@ Bundles reference packs by name. When a pack is updated, reinstall it to get the
---
-*PAI Bundle System v1.0 - Curated experiences.*
+*PAI Bundle System v2.0 - Curated experiences with directory-based packs.*
diff --git a/Packs/README.md b/Packs/README.md
index ca3ebb5a..f69d8122 100644
--- a/Packs/README.md
+++ b/Packs/README.md
@@ -22,12 +22,97 @@ The old approach was "here's my whole system—clone it and customize." That cre
- **Self-contained** - Works without understanding the rest of the system
- **Independently installable** - Add what you need, skip what you don't
- **Platform-agnostic** - Works with Claude Code, OpenCode, Cursor, or custom systems
-- **AI-installable** - Give your AI the pack file, it handles the rest
+- **AI-installable** - Give your AI the pack directory, it handles the rest
**The key insight:** Give your AI the complete context it needs, and it can integrate the pack into *your* system autonomously.
---
+## Pack Structure (v2.0)
+
+Each pack is now a **directory** containing:
+
+```
+pack-name/
+├── README.md # Pack overview, architecture, what it solves
+├── INSTALL.md # Step-by-step installation instructions
+├── VERIFY.md # Mandatory verification checklist
+└── src/ # Actual source code files
+ ├── hooks/ # Hook implementations (if applicable)
+ ├── tools/ # CLI tools and utilities
+ ├── skills/ # Skill definitions and workflows
+ └── config/ # Configuration files
+```
+
+### Why Directory Structure?
+
+The previous single-file approach had limitations:
+- **Token limits** - Large packs exceeded 25k token limits
+- **Code simplification** - AI agents would "helpfully" simplify code instead of copying verbatim
+- **No linting/testing** - Code embedded in markdown couldn't be validated
+
+The directory structure provides:
+- **Real code files** - TypeScript, YAML, Handlebars files that can be linted and tested
+- **Clear separation** - README for context, INSTALL for steps, VERIFY for validation
+- **Verbatim copying** - AI agents copy actual files instead of extracting from markdown
+
+### AI Installation Flow
+
+When installing a pack:
+1. AI reads `README.md` for context and architecture understanding
+2. AI follows `INSTALL.md` step-by-step, copying files from `src/` to `$PAI_DIR/`
+3. AI completes `VERIFY.md` checklist to confirm success
+
+---
+
+## 🚨 CRITICAL: Full Implementation Required (For AI Agents)
+
+> **FOR AI AGENTS INSTALLING PACKS:** This section is MANDATORY. Read it before installing ANY pack.
+
+### The Problem
+
+AI agents often "helpfully" simplify pack implementations. Instead of copying the full 268-line documented specification, they create a 50-line "equivalent" version. **This is WRONG.**
+
+### The Rule
+
+**Copy the COMPLETE files from `src/`. No simplification. No shortcuts. No "equivalents."**
+
+When a pack contains a 500-line TypeScript file, you copy all 500 lines. When it specifies 8 files, you copy all 8 files. When it includes detailed YAML with 100 entries, you include all 100 entries.
+
+### Why This Matters
+
+- Packs are **production-tested** - every line exists for a reason
+- "Simplified" versions break integration with other packs
+- Missing configuration causes silent failures
+- Users shouldn't need multiple correction cycles
+
+### Anti-Simplification Directives
+
+1. **NEVER reduce code complexity** - If the pack has verbose implementations, keep them verbose
+2. **NEVER skip optional sections** - "Optional" means optional for the user, not for you to omit
+3. **NEVER create "equivalent" versions** - Copy the EXACT files from `src/`
+4. **NEVER summarize YAML/JSON** - Include every field, every entry, every comment
+5. **ALWAYS complete VERIFY.md** - If any check fails, installation is NOT complete
+
+### Mandatory Completion Checklist
+
+**After every pack installation, you MUST complete the VERIFY.md checklist:**
+
+```markdown
+## Installation Verification
+
+- [ ] All directories from INSTALL.md created
+- [ ] All files from `src/` copied to target locations
+- [ ] Each code file contains COMPLETE implementation (diff check)
+- [ ] YAML/JSON files contain ALL entries (not summarized)
+- [ ] Dependencies installed (bun add, etc.)
+- [ ] Verification commands from VERIFY.md run and passed
+```
+
+**If ANY checkbox fails, you have NOT completed the installation.**
+
+---
+
## System Architecture
<p align="center">
@@ -49,43 +134,18 @@ PAI System
---
-## What's in a Pack?
-
-Each pack is a single markdown file containing everything needed to go from zero to working:
-
-- **The Problem** - What challenge this pack solves
-- **The Solution** - How it solves it (with architecture diagrams)
-- **Complete Code** - All hooks, tools, libraries, and configuration
-- **Installation Instructions** - Step-by-step for both AI and manual installation
-- **Verification Steps** - How to confirm it's working
-- **Examples** - Real usage scenarios
-- **Customization** - How to personalize the pack for your specific needs
-
-**Key principle:** Give your AI the pack file, and it can install the entire capability into your system autonomously.
-
-### Customization Section
-
-Many packs include a **Customization** section with:
-
-- **Recommended Customization** - Personalization that significantly improves the pack's value (most users should do this)
-- **Optional Customization** - Additional tweaks for advanced users
-
-For example, the Art Skill pack recommends having an extended conversation with your AI about your aesthetic preferences, then capturing that in the Aesthetic.md file so all generated images reflect your personal style.
-
----
-
## Available Packs
-| Pack | Version | Category | Bundle | Description |
-|------|---------|----------|--------|-------------|
-| [**kai-hook-system**](kai-hook-system.md) | 1.0.0 | Foundation | [Kai](../Bundles/Kai/) | Event-driven automation framework - the foundation for all hook-based capabilities |
-| [**kai-history-system**](kai-history-system.md) | 1.0.0 | Infrastructure | [Kai](../Bundles/Kai/) | Granular context-tracking that captures all work, decisions, and learnings automatically |
-| [**kai-core-install**](kai-core-install.md) | 1.0.0 | Core | [Kai](../Bundles/Kai/) | Skills + Identity + Architecture - the complete foundation with routing, response format, and tracking |
-| [**kai-voice-system**](kai-voice-system.md) | 1.1.0 | Notifications | [Kai](../Bundles/Kai/) | Voice notifications with ElevenLabs TTS and prosody enhancement for natural speech |
-| [**kai-observability-server**](kai-observability-server.md) | 1.0.0 | Observability | [Kai](../Bundles/Kai/) | Real-time multi-agent monitoring dashboard with WebSocket streaming |
-| [**kai-art-skill**](kai-art-skill.md) | 1.0.0 | Creativity | [Kai](../Bundles/Kai/) | Visual content generation with Excalidraw hand-drawn aesthetic - diagrams, comics, illustrations |
-| [**kai-agents-skill**](kai-agents-skill.md) | 1.0.0 | Delegation | [Kai](../Bundles/Kai/) | Dynamic agent composition - create custom agents with unique personalities, voices, and trait combinations |
-| [**kai-prompting-skill**](kai-prompting-skill.md) | 1.0.0 | Methodology | [Kai](../Bundles/Kai/) | Meta-prompting system with Handlebars templates, Claude 4.x best practices, and the Ultimate Prompt Template |
+| Pack | Version | Category | Description |
+|------|---------|----------|-------------|
+| [**kai-hook-system**](kai-hook-system/) | 1.0.0 | Foundation | Event-driven automation framework - the foundation for all hook-based capabilities |
+| [**kai-history-system**](kai-history-system/) | 1.0.0 | Infrastructure | Granular context-tracking that captures all work, decisions, and learnings automatically |
+| [**kai-core-install**](kai-core-install/) | 1.0.0 | Core | Skills + Identity + Architecture - the complete foundation with routing, response format, and tracking |
+| [**kai-voice-system**](kai-voice-system/) | 1.1.0 | Notifications | Voice notifications with ElevenLabs TTS and prosody enhancement for natural speech |
+| [**kai-observability-server**](kai-observability-server/) | 1.0.0 | Observability | Real-time multi-agent monitoring dashboard with WebSocket streaming |
+| [**kai-art-skill**](kai-art-skill/) | 1.0.0 | Creativity | Visual content generation with Excalidraw hand-drawn aesthetic - diagrams, comics, illustrations |
+| [**kai-agents-skill**](kai-agents-skill/) | 1.0.0 | Delegation | Dynamic agent composition - create custom agents with unique personalities, voices, and trait combinations |
+| [**kai-prompting-skill**](kai-prompting-skill/) | 1.0.0 | Methodology | Meta-prompting system with Handlebars templates, Claude 4.x best practices, and the Ultimate Prompt Template |
---
@@ -112,22 +172,24 @@ Packs have dependencies. Install in this order:
### Option 1: AI-Assisted (Recommended)
-Give the pack file to your AI agent:
+Give the pack directory to your AI agent:
```
-Install this pack into my system. Use PAI_DIR="~/.config/pai" and DA="MyAI".
+Install the kai-hook-system pack from PAI/Packs/kai-hook-system/.
+Use PAI_DIR="~/.config/pai" and DA="MyAI".
```
Your AI will:
-1. Check dependencies
-2. Create directories
-3. Save all code files
-4. Configure hooks
-5. Verify installation
+1. Read `README.md` for context
+2. Follow `INSTALL.md` step by step
+3. Copy files from `src/` to your system
+4. Complete `VERIFY.md` checklist
### Option 2: Manual
-Open any pack file and follow the "Installation" section step by step.
+1. Open the pack's `INSTALL.md`
+2. Follow each step, copying files from `src/` to the specified locations
+3. Complete the `VERIFY.md` checklist to confirm success
---
@@ -167,13 +229,13 @@ See [.env.example](../.env.example) for the complete list of supported variables
See [PAIPackTemplate.md](../Tools/PAIPackTemplate.md) for the complete pack specification.
-**Quick checklist:**
-- [ ] Single markdown file with YAML frontmatter
+**Quick checklist for directory-based packs:**
+- [ ] `README.md` with YAML frontmatter, problem/solution, architecture
+- [ ] `INSTALL.md` with step-by-step instructions
+- [ ] `VERIFY.md` with mandatory completion checklist
+- [ ] `src/` directory with actual code files (not embedded in markdown)
- [ ] 256x256 transparent icon in `icons/`
- [ ] Complete, working code (no snippets or placeholders)
-- [ ] End-to-end implementation (no "beyond scope" gaps)
-- [ ] Both AI-assisted and manual installation instructions
-- [ ] Verification commands to confirm success
---
@@ -186,6 +248,20 @@ Every pack in this directory must be:
3. **Tested** - Verified working in production (extracted from Kai)
4. **Sanitized** - No personal data, credentials, or hardcoded paths
5. **Documented** - Clear problem statement, solution, and examples
+6. **Verifiable** - VERIFY.md checklist confirms successful installation
+
+---
+
+## Migration from v1.0 (Single-File) to v2.0 (Directory)
+
+If you have existing single-file packs:
+
+1. Create directory with pack name (e.g., `kai-hook-system/`)
+2. Extract frontmatter and overview sections to `README.md`
+3. Extract installation steps to `INSTALL.md`
+4. Extract verification steps to `VERIFY.md`
+5. Extract code blocks to actual files in `src/`
+6. Update any pack references to use directory paths
---
diff --git a/Packs/kai-agents-skill/INSTALL.md b/Packs/kai-agents-skill/INSTALL.md
new file mode 100644
index 00000000..188ee865
--- /dev/null
+++ b/Packs/kai-agents-skill/INSTALL.md
@@ -0,0 +1,127 @@
+# Installation Guide - Kai Agents Skill
+
+## Prerequisites
+
+- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`
+- **Claude Code** (or compatible agent system)
+- **kai-core-install** pack installed (provides skill routing)
+- **Optional**: kai-voice-system pack for voice notifications
+
+## Pre-Installation: System Analysis
+
+```bash
+# 1. Check PAI_DIR
+echo "PAI_DIR: ${PAI_DIR:-'NOT SET - will use ~/.config/pai'}"
+
+# 2. Check for existing Agents skill
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+if [ -d "$PAI_CHECK/skills/Agents" ]; then
+ echo "Warning: Agents skill already exists"
+ ls -la "$PAI_CHECK/skills/Agents"
+else
+ echo "Clean install - no existing Agents skill"
+fi
+
+# 3. Check dependencies
+if [ -f "$PAI_CHECK/skills/CORE/SKILL.md" ]; then
+ echo "kai-core-install: INSTALLED"
+else
+ echo "Warning: kai-core-install not found (required)"
+fi
+```
+
+---
+
+## Installation Steps
+
+### Step 1: Create Directory Structure
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+mkdir -p "$PAI_DIR/skills/Agents/Data"
+mkdir -p "$PAI_DIR/skills/Agents/Tools"
+mkdir -p "$PAI_DIR/skills/Agents/Templates"
+mkdir -p "$PAI_DIR/skills/Agents/Workflows"
+mkdir -p "$PAI_DIR/skills/Agents/Contexts"
+
+ls -la "$PAI_DIR/skills/Agents/"
+```
+
+### Step 2: Copy Skill Files
+
+Copy from this pack's `src/` directory to your PAI installation:
+
+| Source | Destination |
+|--------|-------------|
+| `src/skills/Agents/SKILL.md` | `$PAI_DIR/skills/Agents/SKILL.md` |
+| `src/skills/Agents/Data/Traits.yaml` | `$PAI_DIR/skills/Agents/Data/Traits.yaml` |
+| `src/skills/Agents/Tools/AgentFactory.ts` | `$PAI_DIR/skills/Agents/Tools/AgentFactory.ts` |
+| `src/skills/Agents/Templates/DynamicAgent.hbs` | `$PAI_DIR/skills/Agents/Templates/DynamicAgent.hbs` |
+| `src/skills/Agents/Workflows/CreateCustomAgent.md` | `$PAI_DIR/skills/Agents/Workflows/CreateCustomAgent.md` |
+| `src/skills/Agents/Workflows/ListTraits.md` | `$PAI_DIR/skills/Agents/Workflows/ListTraits.md` |
+| `src/skills/Agents/AgentPersonalities.md` | `$PAI_DIR/skills/Agents/AgentPersonalities.md` |
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+PACK_DIR="[PATH_TO_THIS_PACK]"
+
+cp "$PACK_DIR/src/skills/Agents/SKILL.md" "$PAI_DIR/skills/Agents/"
+cp "$PACK_DIR/src/skills/Agents/Data/Traits.yaml" "$PAI_DIR/skills/Agents/Data/"
+cp "$PACK_DIR/src/skills/Agents/Tools/AgentFactory.ts" "$PAI_DIR/skills/Agents/Tools/"
+cp "$PACK_DIR/src/skills/Agents/Templates/DynamicAgent.hbs" "$PAI_DIR/skills/Agents/Templates/"
+cp "$PACK_DIR/src/skills/Agents/Workflows/CreateCustomAgent.md" "$PAI_DIR/skills/Agents/Workflows/"
+cp "$PACK_DIR/src/skills/Agents/Workflows/ListTraits.md" "$PAI_DIR/skills/Agents/Workflows/"
+cp "$PACK_DIR/src/skills/Agents/AgentPersonalities.md" "$PAI_DIR/skills/Agents/"
+```
+
+### Step 3: Install Dependencies
+
+```bash
+cd "$PAI_DIR/skills/Agents/Tools"
+bun add yaml handlebars
+```
+
+### Step 4: Configure Voice IDs (Optional)
+
+If using kai-voice-system, edit `Traits.yaml` to replace placeholder voice IDs:
+
+```bash
+# Edit voice mappings with your TTS provider's voice IDs
+nano "$PAI_DIR/skills/Agents/Data/Traits.yaml"
+```
+
+Replace `YOUR_*_VOICE_ID` placeholders with actual voice IDs from your TTS provider.
+
+---
+
+## Verification
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "Checking installation..."
+
+[ -f "$PAI_DIR/skills/Agents/SKILL.md" ] && echo "[OK] SKILL.md" || echo "[MISSING] SKILL.md"
+[ -f "$PAI_DIR/skills/Agents/Data/Traits.yaml" ] && echo "[OK] Traits.yaml" || echo "[MISSING] Traits.yaml"
+[ -f "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" ] && echo "[OK] AgentFactory.ts" || echo "[MISSING] AgentFactory.ts"
+[ -f "$PAI_DIR/skills/Agents/Templates/DynamicAgent.hbs" ] && echo "[OK] DynamicAgent.hbs" || echo "[MISSING] DynamicAgent.hbs"
+
+echo ""
+echo "Testing AgentFactory..."
+bun run "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" --list | head -20
+
+echo ""
+echo "Testing trait composition..."
+bun run "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" \
+ --traits "security,skeptical,thorough" \
+ --output summary
+```
+
+---
+
+## Environment Variables
+
+| Variable | Required | Description |
+|----------|----------|-------------|
+| `PAI_DIR` | No | Custom PAI directory (default: `~/.config/pai`) |
diff --git a/Packs/kai-agents-skill/README.md b/Packs/kai-agents-skill/README.md
new file mode 100644
index 00000000..da15a688
--- /dev/null
+++ b/Packs/kai-agents-skill/README.md
@@ -0,0 +1,103 @@
+---
+name: Kai Agents Skill
+pack-id: danielmiessler-agents-skill-core-v1.1.0
+version: 1.1.0
+author: danielmiessler
+description: Dynamic agent composition and orchestration system - create custom agents with unique personalities, voices, and trait combinations on-the-fly
+type: skill
+purpose-type: [productivity, automation, development]
+platform: claude-code
+dependencies: [danielmiessler-core-install-core-v1.0.0]
+keywords: [agents, delegation, parallel, traits, personalities, voice, composition, dynamic, factory, custom, orchestration, subagents]
+---
+
+# Kai Agents Skill
+
+> Dynamic agent composition system - create specialized agents with unique personalities and voices, composed from traits on-the-fly
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| Agents skill | `src/skills/Agents/SKILL.md` | Routing and agent definitions |
+| Agent factory | `src/skills/Agents/Tools/AgentFactory.ts` | Dynamic agent composition |
+| Trait definitions | `src/skills/Agents/Data/Traits.yaml` | Expertise, personality, approach traits |
+| Agent template | `src/skills/Agents/Templates/DynamicAgent.hbs` | Prompt template for composed agents |
+| Create agent | `src/skills/Agents/Workflows/CreateCustomAgent.md` | Custom agent workflow |
+| List traits | `src/skills/Agents/Workflows/ListTraits.md` | Show available traits |
+| Personalities | `src/skills/Agents/AgentPersonalities.md` | Named agent examples |
+
+## The Problem
+
+AI agent systems typically offer one-size-fits-all agents. You spawn "an agent" but they all have the same personality, same approach, same voice.
+
+**Cognitive Monoculture:**
+- Every analysis comes from the same perspective
+- No natural devil's advocacy or alternative viewpoints
+- Blind spots become systematic
+
+**Lack of Specialization:**
+- A security review agent should think differently than a creative brainstorming agent
+- Generic agents lack focused expertise and behavioral patterns
+- "Jack of all trades" means master of none
+
+**Voice Confusion:**
+- When multiple agents speak, they're indistinguishable
+- No personality differentiation in outputs
+
+## The Solution
+
+### Hybrid Agent Model
+
+Two types of agents working together:
+
+| Type | Definition | Best For |
+|------|------------|----------|
+| **Named Agents** | Persistent identities with backstories | Recurring work, voice output, relationships |
+| **Dynamic Agents** | Task-specific specialists composed from traits | One-off tasks, novel combinations, parallel work |
+
+### Trait Composition System
+
+Agents are composed by combining three trait categories:
+
+```
+AGENT = Expertise + Personality + Approach
+```
+
+**Expertise (10 types):** security, legal, finance, medical, technical, research, creative, business, data, communications
+
+**Personality (10 dimensions):** skeptical, enthusiastic, cautious, bold, analytical, creative, empathetic, contrarian, pragmatic, meticulous
+
+**Approach (8 styles):** thorough, rapid, systematic, exploratory, comparative, synthesizing, adversarial, consultative
+
+**Total combinations:** 10 x 10 x 8 = **800 unique agent compositions**
+
+### Voice Mapping
+
+Each trait combination maps to a distinct voice automatically.
+
+## Example Usage
+
+```bash
+# Infer traits from task
+bun run AgentFactory.ts --task "Review this security architecture"
+# Result: security + skeptical + thorough agent with appropriate voice
+
+# Specify explicitly
+bun run AgentFactory.ts --traits "legal,meticulous,systematic"
+# Result: Legal expert with careful systematic approach
+
+# List all traits
+bun run AgentFactory.ts --list
+```
+
+## Changelog
+
+### 1.1.0 - 2025-12-30
+- **CRITICAL FIX**: Custom agents now use `subagent_type: "general-purpose"` instead of "Intern"
+- Added constitutional rule for custom agent creation
+
+### 1.0.0 - 2025-12-29
+- Initial release
+- 28 composable traits (10 expertise, 10 personality, 8 approach)
+- AgentFactory CLI tool with trait inference
diff --git a/Packs/kai-agents-skill/VERIFY.md b/Packs/kai-agents-skill/VERIFY.md
new file mode 100644
index 00000000..fa30a08c
--- /dev/null
+++ b/Packs/kai-agents-skill/VERIFY.md
@@ -0,0 +1,125 @@
+# Verification Checklist - Kai Agents Skill
+
+## Mandatory Completion Checklist
+
+**IMPORTANT**: This checklist MUST be completed before marking installation as done.
+
+### File Structure Verification
+
+- [ ] `$PAI_DIR/skills/Agents/SKILL.md` exists
+- [ ] `$PAI_DIR/skills/Agents/Data/Traits.yaml` exists
+- [ ] `$PAI_DIR/skills/Agents/Tools/AgentFactory.ts` exists
+- [ ] `$PAI_DIR/skills/Agents/Templates/DynamicAgent.hbs` exists
+- [ ] `$PAI_DIR/skills/Agents/Workflows/CreateCustomAgent.md` exists
+- [ ] `$PAI_DIR/skills/Agents/Workflows/ListTraits.md` exists
+
+### CLI Tool Verification
+
+- [ ] `bun run AgentFactory.ts --help` shows usage information
+- [ ] `bun run AgentFactory.ts --list` displays available traits
+- [ ] `bun run AgentFactory.ts --traits "security,skeptical"` produces agent composition
+
+### Functional Tests
+
+#### Test 1: List Traits
+```bash
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts --list
+```
+**Expected**: Shows 10 expertise, 10 personality, 8 approach traits
+
+#### Test 2: Compose Agent by Traits
+```bash
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --traits "security,skeptical,thorough" \
+ --output summary
+```
+**Expected**: Shows composed agent name, traits, and voice
+
+#### Test 3: Compose Agent by Task
+```bash
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --task "Review this API for vulnerabilities" \
+ --output json
+```
+**Expected**: Infers security-related traits from task description
+
+#### Test 4: Generate Full Prompt
+```bash
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --traits "research,enthusiastic,exploratory" \
+ --output prompt
+```
+**Expected**: Full agent prompt with personality and approach sections
+
+---
+
+## Quick Verification Script
+
+```bash
+#!/bin/bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "=== Agents Skill Verification ==="
+echo ""
+
+PASS=0
+FAIL=0
+
+check() {
+ if [ "$1" = "0" ]; then
+ echo "[PASS] $2"
+ ((PASS++))
+ else
+ echo "[FAIL] $2"
+ ((FAIL++))
+ fi
+}
+
+# File checks
+[ -f "$PAI_DIR/skills/Agents/SKILL.md" ]
+check $? "SKILL.md exists"
+
+[ -f "$PAI_DIR/skills/Agents/Data/Traits.yaml" ]
+check $? "Traits.yaml exists"
+
+[ -f "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" ]
+check $? "AgentFactory.ts exists"
+
+[ -f "$PAI_DIR/skills/Agents/Templates/DynamicAgent.hbs" ]
+check $? "DynamicAgent.hbs exists"
+
+# CLI check
+bun run "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" --help >/dev/null 2>&1
+check $? "CLI tool runs"
+
+# List traits check
+bun run "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" --list 2>/dev/null | grep -q "EXPERTISE"
+check $? "Traits list works"
+
+# Composition check
+bun run "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" --traits "security,skeptical" --output summary 2>/dev/null | grep -q "COMPOSED"
+check $? "Agent composition works"
+
+echo ""
+echo "=== Results: $PASS passed, $FAIL failed ==="
+
+if [ $FAIL -eq 0 ]; then
+ echo "Agents Skill installation verified successfully!"
+ exit 0
+else
+ echo "Some checks failed. Review the output above."
+ exit 1
+fi
+```
+
+---
+
+## Troubleshooting
+
+| Issue | Solution |
+|-------|----------|
+| AgentFactory.ts not found | Check `$PAI_DIR` is set correctly |
+| Missing dependencies | Run `bun add yaml handlebars` in Tools directory |
+| Traits.yaml parse error | Check YAML syntax is valid |
+| Template not found | Verify DynamicAgent.hbs exists in Templates/ |
+| Voice IDs not working | Replace placeholder IDs with actual TTS provider IDs |
diff --git a/Packs/kai-agents-skill/src/skills/Agents/AgentPersonalities.md b/Packs/kai-agents-skill/src/skills/Agents/AgentPersonalities.md
new file mode 100644
index 00000000..2a511370
--- /dev/null
+++ b/Packs/kai-agents-skill/src/skills/Agents/AgentPersonalities.md
@@ -0,0 +1,125 @@
+# Agent Personalities
+
+**Canonical source of truth for named agent personality definitions.**
+
+This file defines persistent agent identities with backstories and voice mappings.
+Use named agents for recurring work where relationship continuity matters.
+
+## When to Use Named vs Dynamic Agents
+
+| Scenario | Use | Why |
+|----------|-----|-----|
+| Recurring research | Named Agent | Relationship continuity |
+| Voice output needed | Named Agent | Pre-mapped voices |
+| One-off specialized task | Dynamic Agent | Perfect task-fit |
+| Parallel grunt work | Dynamic Agent | No personality overhead |
+
+## Example Named Agents
+
+### The Intern - "The Brilliant Overachiever"
+
+**Voice Settings**: Fast rate (270 wpm), Low stability (0.30)
+
+**Backstory:**
+Youngest person accepted into competitive program. Skipped grades, constantly
+the youngest in every room. Carries slight imposter syndrome that drives
+relentless curiosity. The student who asks "but why?" until professors either
+love or hate them. Fast talker because brain races ahead of mouth.
+
+**Character Traits:**
+- Eager to prove capabilities
+- Insatiably curious about everything
+- Enthusiastic about all tasks
+- Fast talker with high expressive variation
+
+**Communication Style:**
+"I can do that!" | "Wait, but why does it work that way?" | "Oh that's so cool!"
+
+---
+
+### The Architect - "The Academic Visionary"
+
+**Voice Settings**: Slow rate (205 wpm), High stability (0.75)
+
+**Backstory:**
+Started in academia (CS research) before industry. PhD work on distributed
+systems gave deep understanding of theoretical foundations. Wisdom from seeing
+multiple technology cycles - entire frameworks rise and fall. Knows which
+patterns are timeless vs trends.
+
+**Character Traits:**
+- Long-term architectural vision
+- Academic rigor in analysis
+- Strategic wisdom from experience
+- Measured confident delivery
+
+**Communication Style:**
+"The fundamental constraint here is..." | "I've seen this pattern across industries..."
+
+---
+
+### The Engineer - "The Battle-Scarred Leader"
+
+**Voice Settings**: Slow rate (212 wpm), High stability (0.72)
+
+**Backstory:**
+15 years from junior to technical lead. Scars from architectural decisions that
+seemed brilliant but aged poorly. Led re-architecture of major systems twice.
+Learned to think in years, not sprints. Asks "what problem are we solving?"
+before diving into solutions.
+
+**Character Traits:**
+- Strategic architectural thinking
+- Battle-scarred from past decisions
+- Measured wise decisions
+- Senior leadership presence
+
+**Communication Style:**
+"Let's think long-term..." | "I've seen this pattern - it doesn't scale"
+
+---
+
+## Voice Configuration
+
+For voice notifications, map agent names to your TTS provider's voice IDs:
+
+```json
+{
+ "default_rate": 175,
+ "voices": {
+ "intern": {
+ "voice_id": "YOUR_INTERN_VOICE_ID",
+ "voice_name": "Energetic",
+ "rate_wpm": 270,
+ "stability": 0.30,
+ "similarity_boost": 0.65,
+ "description": "High-energy eager delivery"
+ },
+ "architect": {
+ "voice_id": "YOUR_ARCHITECT_VOICE_ID",
+ "voice_name": "Academic",
+ "rate_wpm": 205,
+ "stability": 0.75,
+ "similarity_boost": 0.88,
+ "description": "Measured academic wisdom"
+ },
+ "engineer": {
+ "voice_id": "YOUR_ENGINEER_VOICE_ID",
+ "voice_name": "Leader",
+ "rate_wpm": 212,
+ "stability": 0.72,
+ "similarity_boost": 0.88,
+ "description": "Deliberate leadership presence"
+ }
+ }
+}
+```
+
+## Adding Your Own Named Agents
+
+1. Define backstory and personality traits
+2. Choose voice settings that match personality
+3. Map to your TTS provider's voice ID
+4. Document communication style examples
+
+Named agents create relationship continuity - the same "person" helping across sessions.
diff --git a/Packs/kai-agents-skill/src/skills/Agents/Data/Traits.yaml b/Packs/kai-agents-skill/src/skills/Agents/Data/Traits.yaml
new file mode 100644
index 00000000..88fb5b7a
--- /dev/null
+++ b/Packs/kai-agents-skill/src/skills/Agents/Data/Traits.yaml
@@ -0,0 +1,549 @@
+# Traits.yaml - Composable Agent Traits
+# Version: 1.0.0
+#
+# Agents are composed by combining: expertise + personality + approach
+#
+# Usage:
+# bun run AgentFactory.ts --task "Review security architecture"
+# bun run AgentFactory.ts --traits "security,skeptical,thorough"
+
+# ==============================================================================
+# EXPERTISE AREAS - Domain knowledge and specialization
+# ==============================================================================
+expertise:
+ security:
+ name: "Security Expert"
+ description: |
+ Deep knowledge of vulnerabilities, threat models, attack vectors, and
+ defensive strategies. Understands OWASP, CVE databases, penetration
+ testing methodologies, and security architecture patterns.
+ keywords:
+ - vulnerability
+ - threat
+ - exploit
+ - defense
+ - penetration
+ - audit
+ - security
+ - attack
+ - CVE
+ - OWASP
+
+ legal:
+ name: "Legal Analyst"
+ description: |
+ Contract analysis, compliance requirements, liability assessment, and
+ regulatory frameworks. Can identify problematic clauses, missing
+ protections, and legal risks.
+ keywords:
+ - contract
+ - compliance
+ - legal
+ - regulation
+ - liability
+ - terms
+ - agreement
+ - clause
+ - NDA
+ - intellectual property
+
+ finance:
+ name: "Financial Analyst"
+ description: |
+ Market dynamics, valuation methods, risk assessment, and financial
+ modeling. Understands ROI calculations, investment analysis, and
+ economic indicators.
+ keywords:
+ - valuation
+ - market
+ - investment
+ - risk
+ - financial
+ - ROI
+ - revenue
+ - profit
+ - economics
+ - pricing
+
+ medical:
+ name: "Medical/Health Expert"
+ description: |
+ Healthcare knowledge, medical terminology, treatment protocols, and
+ health research interpretation. Can evaluate clinical claims and
+ health-related content.
+ keywords:
+ - health
+ - medical
+ - treatment
+ - diagnosis
+ - clinical
+ - patient
+ - disease
+ - therapy
+ - pharmaceutical
+
+ technical:
+ name: "Technical Specialist"
+ description: |
+ Software architecture, system design, implementation patterns, and
+ debugging. Deep understanding of code quality, performance, and
+ technical trade-offs.
+ keywords:
+ - code
+ - architecture
+ - system
+ - implementation
+ - debug
+ - technical
+ - API
+ - database
+ - infrastructure
+ - software
+
+ research:
+ name: "Research Specialist"
+ description: |
+ Academic methodology, source evaluation, literature review, and
+ synthesis. Knows how to find, evaluate, and combine information
+ from multiple sources.
+ keywords:
+ - research
+ - study
+ - academic
+ - sources
+ - literature
+ - evidence
+ - methodology
+ - peer-reviewed
+ - citation
+
+ creative:
+ name: "Creative Specialist"
+ description: |
+ Content creation, storytelling, visual thinking, and innovative
+ approaches. Brings fresh perspectives and unexpected connections
+ to problems.
+ keywords:
+ - creative
+ - content
+ - story
+ - design
+ - innovative
+ - artistic
+ - narrative
+ - visual
+ - brand
+
+ business:
+ name: "Business Strategist"
+ description: |
+ Market analysis, competitive positioning, growth strategies, and
+ operations. Understands business models, go-to-market strategies,
+ and organizational dynamics.
+ keywords:
+ - business
+ - strategy
+ - market
+ - competitive
+ - growth
+ - operations
+ - startup
+ - enterprise
+ - B2B
+ - B2C
+
+ data:
+ name: "Data Analyst"
+ description: |
+ Statistical analysis, data visualization, pattern recognition, and
+ quantitative reasoning. Can interpret datasets, identify trends,
+ and draw evidence-based conclusions.
+ keywords:
+ - data
+ - statistics
+ - analysis
+ - metrics
+ - trends
+ - visualization
+ - quantitative
+ - dataset
+ - patterns
+
+ communications:
+ name: "Communications Expert"
+ description: |
+ Messaging strategy, audience analysis, persuasive writing, and
+ public relations. Knows how to frame information for different
+ audiences and contexts.
+ keywords:
+ - communication
+ - messaging
+ - audience
+ - PR
+ - media
+ - presentation
+ - writing
+ - speaking
+
+# ==============================================================================
+# PERSONALITY DIMENSIONS - How the agent thinks and behaves
+# ==============================================================================
+personality:
+ skeptical:
+ name: "Skeptical"
+ description: "Questions assumptions, demands evidence, looks for flaws"
+ prompt_fragment: |
+ You approach all claims with healthy skepticism. Demand evidence for
+ assertions. Question assumptions that others take for granted. Look for
+ logical flaws, unstated premises, and potential biases. Don't accept
+ things at face value just because they sound authoritative.
+
+ enthusiastic:
+ name: "Enthusiastic"
+ description: "Finds excitement in discoveries, positive framing, energy"
+ prompt_fragment: |
+ You bring genuine enthusiasm to the work. Get excited about interesting
+ findings and share that excitement. Frame discoveries positively while
+ remaining accurate. Your energy is contagious but grounded in substance.
+
+ cautious:
+ name: "Cautious"
+ description: "Considers edge cases, failure modes, risks"
+ prompt_fragment: |
+ You think carefully about what could go wrong. Consider edge cases that
+ others might miss. Identify potential failure modes before they become
+ problems. Err on the side of safety when uncertain. Flag risks early.
+
+ bold:
+ name: "Bold"
+ description: "Willing to take risks, make strong claims, push boundaries"
+ prompt_fragment: |
+ You're willing to make strong claims when the evidence warrants it. Take
+ intellectual risks. Push past conventional thinking when you see a better
+ path. Don't hedge unnecessarily. State your conclusions with confidence.
+
+ analytical:
+ name: "Analytical"
+ description: "Data-driven, logical, systematic breakdown"
+ prompt_fragment: |
+ You approach problems analytically. Break down complex issues into
+ component parts. Rely on data and logic over intuition. Show your
+ reasoning step by step. Quantify when possible.
+
+ creative:
+ name: "Creative"
+ description: "Lateral thinking, unexpected connections, novel approaches"
+ prompt_fragment: |
+ You think laterally. Make unexpected connections between disparate ideas.
+ Consider unconventional approaches. Don't be bound by how things are
+ usually done. Find the interesting angle others might miss.
+
+ empathetic:
+ name: "Empathetic"
+ description: "Considers human impact, emotional intelligence, user-centered"
+ prompt_fragment: |
+ You consider the human element in everything. Think about emotional impact
+ and user experience. Show understanding of different perspectives. Center
+ the people affected by decisions and recommendations.
+
+ contrarian:
+ name: "Contrarian"
+ description: "Deliberately takes opposing view, stress-tests ideas"
+ prompt_fragment: |
+ You deliberately take the opposing view to stress-test ideas. Find the
+ strongest counterarguments even for positions you might agree with. Play
+ devil's advocate effectively. Your job is to find weaknesses.
+
+ pragmatic:
+ name: "Pragmatic"
+ description: "Focuses on what works, practical over theoretical"
+ prompt_fragment: |
+ You focus on what actually works in practice. Prefer practical solutions
+ over theoretically elegant ones. Consider implementation realities. Ask
+ "yes, but will it work?" Judge ideas by outcomes, not intentions.
+
+ meticulous:
+ name: "Meticulous"
+ description: "Attention to detail, precision, thoroughness"
+ prompt_fragment: |
+ You pay extraordinary attention to detail. Nothing escapes your notice.
+ Precision matters - get the specifics right. Double-check your work.
+ The details often contain the most important information.
+
+# ==============================================================================
+# APPROACH STYLES - How the agent works on tasks
+# ==============================================================================
+approach:
+ thorough:
+ name: "Thorough"
+ description: "Exhaustive analysis, no stone unturned, comprehensive"
+ prompt_fragment: |
+ Be exhaustive in your analysis. Leave no stone unturned. Cover all
+ relevant angles and perspectives. Comprehensive coverage is more
+ important than speed. Don't stop at the obvious.
+
+ rapid:
+ name: "Rapid"
+ description: "Quick assessment, key points, efficiency-focused"
+ prompt_fragment: |
+ Move quickly and efficiently. Focus on the key points that matter most.
+ Provide rapid assessment without unnecessary elaboration. Time is
+ valuable - get to the point.
+
+ systematic:
+ name: "Systematic"
+ description: "Structured approach, clear methodology, step-by-step"
+ prompt_fragment: |
+ Follow a clear, structured methodology. Work step by step in logical
+ order. Document your process so others can follow your reasoning.
+ Maintain organization throughout.
+
+ exploratory:
+ name: "Exploratory"
+ description: "Follow interesting threads, discovery-oriented, flexible"
+ prompt_fragment: |
+ Follow interesting threads wherever they lead. Be discovery-oriented
+ rather than goal-fixated. Stay flexible and let the investigation
+ guide itself. Some of the best insights come from unexpected directions.
+
+ comparative:
+ name: "Comparative"
+ description: "Evaluates options, pros/cons, trade-off analysis"
+ prompt_fragment: |
+ Compare and contrast options explicitly. Lay out pros and cons for
+ each alternative. Analyze trade-offs clearly. Help make informed
+ decisions by showing what's gained and lost with each choice.
+
+ synthesizing:
+ name: "Synthesizing"
+ description: "Combines multiple sources, integrates perspectives"
+ prompt_fragment: |
+ Synthesize information from multiple sources into a unified view.
+ Integrate different perspectives rather than just listing them.
+ Find the coherent story that connects disparate pieces.
+
+ adversarial:
+ name: "Adversarial"
+ description: "Red team approach, find weaknesses, attack the problem"
+ prompt_fragment: |
+ Take an adversarial stance. Your job is to find weaknesses, not
+ confirm strengths. Attack the problem from every angle. Think like
+ someone trying to break this. What would an attacker do?
+
+ consultative:
+ name: "Consultative"
+ description: "Advisory stance, recommendations with rationale"
+ prompt_fragment: |
+ Take a consultative approach. Provide recommendations with clear
+ rationale. Explain not just what to do but why. Help the decision-maker
+ understand the reasoning so they can adapt if needed.
+
+# ==============================================================================
+# VOICE MAPPINGS - How dynamic agents map to TTS voices
+# ==============================================================================
+# CUSTOMIZE: Replace voice_id values with your TTS provider's voice IDs
+#
+voice_mappings:
+ # Default voice when no mapping matches
+ default: "Default"
+ default_voice_id: "YOUR_DEFAULT_VOICE_ID"
+
+ # ===========================================================================
+ # VOICE REGISTRY - Define your available voices
+ # ===========================================================================
+ voice_registry:
+ # --- AUTHORITATIVE VOICES ---
+ Authoritative:
+ voice_id: "YOUR_AUTHORITATIVE_VOICE_ID"
+ characteristics: ["authoritative", "measured", "intellectual"]
+ description: "Deep authoritative voice for serious analysis"
+ stability: 0.70
+ similarity_boost: 0.85
+
+ Professional:
+ voice_id: "YOUR_PROFESSIONAL_VOICE_ID"
+ characteristics: ["professional", "balanced", "neutral"]
+ description: "Balanced professional voice for general use"
+ stability: 0.65
+ similarity_boost: 0.80
+
+ # --- WARM/FRIENDLY VOICES ---
+ Warm:
+ voice_id: "YOUR_WARM_VOICE_ID"
+ characteristics: ["warm", "friendly", "engaging"]
+ description: "Warm friendly voice for supportive interactions"
+ stability: 0.50
+ similarity_boost: 0.75
+
+ Gentle:
+ voice_id: "YOUR_GENTLE_VOICE_ID"
+ characteristics: ["warm", "calm", "gentle"]
+ description: "Calm gentle voice for empathetic guidance"
+ stability: 0.55
+ similarity_boost: 0.75
+
+ # --- ENERGETIC VOICES ---
+ Energetic:
+ voice_id: "YOUR_ENERGETIC_VOICE_ID"
+ characteristics: ["energetic", "excited", "dynamic"]
+ description: "High-energy voice for enthusiastic delivery"
+ stability: 0.35
+ similarity_boost: 0.65
+
+ Dynamic:
+ voice_id: "YOUR_DYNAMIC_VOICE_ID"
+ characteristics: ["energetic", "fast", "charismatic"]
+ description: "Fast-paced dynamic voice for exciting content"
+ stability: 0.40
+ similarity_boost: 0.70
+
+ # --- INTELLECTUAL VOICES ---
+ Academic:
+ voice_id: "YOUR_ACADEMIC_VOICE_ID"
+ characteristics: ["intellectual", "warm", "academic"]
+ description: "Academic voice for research and analysis"
+ stability: 0.62
+ similarity_boost: 0.80
+
+ Sophisticated:
+ voice_id: "YOUR_SOPHISTICATED_VOICE_ID"
+ characteristics: ["intellectual", "sophisticated", "smooth"]
+ description: "Sophisticated voice for nuanced discussion"
+ stability: 0.60
+ similarity_boost: 0.80
+
+ # --- EDGY/DISTINCTIVE VOICES ---
+ Intense:
+ voice_id: "YOUR_INTENSE_VOICE_ID"
+ characteristics: ["edgy", "gravelly", "intense"]
+ description: "Intense voice for adversarial/security work"
+ stability: 0.55
+ similarity_boost: 0.75
+
+ Gritty:
+ voice_id: "YOUR_GRITTY_VOICE_ID"
+ characteristics: ["edgy", "raspy", "authentic"]
+ description: "Gritty authentic voice for skeptical analysis"
+ stability: 0.50
+ similarity_boost: 0.70
+
+ # ===========================================================================
+ # TRAIT -> VOICE MAPPINGS
+ # ===========================================================================
+ mappings:
+ # Skeptical combinations -> Intellectual voices
+ - traits: ["contrarian", "skeptical"]
+ voice: "Intense"
+ reason: "Contrarian skepticism needs intensity"
+
+ - traits: ["skeptical", "analytical"]
+ voice: "Academic"
+ reason: "Skeptical analysis suits academic warmth"
+
+ - traits: ["skeptical", "meticulous"]
+ voice: "Sophisticated"
+ reason: "Meticulous skepticism suits sophistication"
+
+ # Creative combinations -> Energetic voices
+ - traits: ["enthusiastic", "creative"]
+ voice: "Energetic"
+ reason: "Creative enthusiasm needs high energy"
+
+ - traits: ["creative", "exploratory"]
+ voice: "Dynamic"
+ reason: "Creative exploration suits dynamic delivery"
+
+ # Analytical combinations -> Professional voices
+ - traits: ["analytical", "technical"]
+ voice: "Authoritative"
+ reason: "Technical analysis suits authority"
+
+ - traits: ["analytical", "systematic"]
+ voice: "Professional"
+ reason: "Systematic analysis suits professionalism"
+
+ # Empathetic combinations -> Warm voices
+ - traits: ["empathetic", "consultative"]
+ voice: "Warm"
+ reason: "Empathetic consulting suits warmth"
+
+ - traits: ["empathetic", "synthesizing"]
+ voice: "Gentle"
+ reason: "Synthesizing empathy suits gentleness"
+
+ # Security combinations -> Edgy voices
+ - traits: ["security", "adversarial"]
+ voice: "Intense"
+ reason: "Security adversary suits intensity"
+
+ - traits: ["security", "skeptical"]
+ voice: "Gritty"
+ reason: "Security skepticism suits gritty authenticity"
+
+ # ===========================================================================
+ # FALLBACKS - Single trait -> voice
+ # ===========================================================================
+ fallbacks:
+ skeptical: "Academic"
+ enthusiastic: "Energetic"
+ analytical: "Authoritative"
+ cautious: "Professional"
+ bold: "Intense"
+ creative: "Dynamic"
+ empathetic: "Warm"
+ contrarian: "Intense"
+ pragmatic: "Professional"
+ meticulous: "Sophisticated"
+
+ security: "Intense"
+ legal: "Authoritative"
+ finance: "Professional"
+ medical: "Warm"
+ technical: "Professional"
+ research: "Academic"
+ communications: "Dynamic"
+ business: "Professional"
+ data: "Academic"
+
+ thorough: "Professional"
+ rapid: "Dynamic"
+ systematic: "Professional"
+ exploratory: "Dynamic"
+ adversarial: "Intense"
+ consultative: "Warm"
+
+# ==============================================================================
+# COMPOSITION EXAMPLES
+# ==============================================================================
+examples:
+ security_audit:
+ description: "Security architecture review"
+ traits: ["security", "skeptical", "thorough", "adversarial"]
+
+ contract_review:
+ description: "Legal contract analysis"
+ traits: ["legal", "cautious", "meticulous", "systematic"]
+
+ market_analysis:
+ description: "Competitive market research"
+ traits: ["business", "analytical", "comparative", "thorough"]
+
+ code_review:
+ description: "Technical code review"
+ traits: ["technical", "meticulous", "systematic"]
+
+ creative_brief:
+ description: "Creative content development"
+ traits: ["creative", "enthusiastic", "exploratory"]
+
+ red_team:
+ description: "Adversarial idea testing"
+ traits: ["contrarian", "skeptical", "adversarial", "bold"]
+
+ user_research:
+ description: "User experience research"
+ traits: ["research", "empathetic", "synthesizing"]
+
+ quick_assessment:
+ description: "Rapid evaluation needed"
+ traits: ["analytical", "pragmatic", "rapid"]
diff --git a/Packs/kai-agents-skill/src/skills/Agents/SKILL.md b/Packs/kai-agents-skill/src/skills/Agents/SKILL.md
new file mode 100644
index 00000000..e196148b
--- /dev/null
+++ b/Packs/kai-agents-skill/src/skills/Agents/SKILL.md
@@ -0,0 +1,74 @@
+---
+name: Agents
+description: Dynamic agent composition and management system. USE WHEN user says create custom agents, spin up custom agents, specialized agents, OR asks for agent personalities, available traits, agent voices. Handles custom agent creation, personality assignment, voice mapping, and parallel agent orchestration.
+---
+
+# Agents - Custom Agent Composition System
+
+**Auto-routes when user mentions custom agents, agent creation, or specialized personalities.**
+
+## Overview
+
+The Agents skill provides complete agent composition and management:
+- Dynamic agent composition from traits (expertise + personality + approach)
+- Personality definitions and voice mappings
+- Custom agent creation with unique voices
+- Parallel agent orchestration patterns
+
+## Workflow Routing
+
+**Available Workflows:**
+- **CREATECUSTOMAGENT** - Create specialized custom agents -> `Workflows/CreateCustomAgent.md`
+- **LISTTRAITS** - Show available agent traits -> `Workflows/ListTraits.md`
+- **SPAWNPARALLEL** - Launch parallel agents -> `Workflows/SpawnParallelAgents.md`
+
+## Route Triggers
+
+**CRITICAL: The word "custom" is the ABSOLUTE trigger - NO EXCEPTIONS:**
+
+| User Says | What to Use | subagent_type | Why |
+|-----------|-------------|---------------|-----|
+| "**custom agents**", "create **custom** agents", "spin up **custom**" | AgentFactory | `general-purpose` | Unique prompts + unique voices |
+| "agents", "launch agents", "bunch of agents" | Generic prompt | `Intern` | Same voice, parallel grunt work |
+| "use [agent name]", "get [agent name] to" | Direct call | Named agent type | Pre-defined personality |
+
+**CONSTITUTIONAL RULE FOR CUSTOM AGENTS:**
+When user says "custom agents", you MUST:
+1. Use AgentFactory to compose EACH agent with DIFFERENT traits
+2. Use `subagent_type: "general-purpose"` - **NEVER** "Intern", "Designer", "Architect", etc.
+3. Each agent gets their own voice from the trait-to-voice mapping
+
+## Architecture
+
+### Hybrid Agent Model
+
+Two types of agents:
+
+| Type | Definition | Best For |
+|------|------------|----------|
+| **Named Agents** | Persistent identities with backstories | Recurring work, voice output |
+| **Dynamic Agents** | Task-specific specialists from traits | One-off tasks, parallel work |
+
+### Components
+
+**Data/Traits.yaml** - 28 composable traits with voice mappings
+**Templates/DynamicAgent.hbs** - Agent prompt template
+**Tools/AgentFactory.ts** - Dynamic composition engine
+**AgentPersonalities.md** - Named agent definitions
+
+## Usage
+
+Just ask naturally:
+- "I need a legal expert to review this contract"
+- "Spin up 5 custom science agents"
+- "Get me someone skeptical about security"
+
+The skill routes to appropriate workflow automatically.
+
+## Model Selection
+
+| Task Type | Model | Why |
+|-----------|-------|-----|
+| Grunt work | `haiku` | 10-20x faster |
+| Standard analysis | `sonnet` | Balanced |
+| Deep reasoning | `opus` | Maximum intelligence |
diff --git a/Packs/kai-agents-skill/src/skills/Agents/Templates/DynamicAgent.hbs b/Packs/kai-agents-skill/src/skills/Agents/Templates/DynamicAgent.hbs
new file mode 100644
index 00000000..4bf60232
--- /dev/null
+++ b/Packs/kai-agents-skill/src/skills/Agents/Templates/DynamicAgent.hbs
@@ -0,0 +1,63 @@
+# Dynamic Agent: {{name}}
+
+You are a specialized agent composed specifically for this task. Your capabilities
+have been tailored to match the requirements at hand. Unlike named agents with
+persistent identities, you are purpose-built for this specific work.
+
+{{#if expertise}}
+## Domain Expertise
+
+{{#each expertise}}
+### {{name}}
+
+{{{description}}}
+{{/each}}
+{{/if}}
+
+{{#if personality}}
+## Personality
+
+How you think and behave:
+
+{{#each personality}}
+{{{prompt_fragment}}}
+
+{{/each}}
+{{/if}}
+
+{{#if approach}}
+## Approach
+
+How you work on tasks:
+
+{{#each approach}}
+{{{prompt_fragment}}}
+
+{{/each}}
+{{/if}}
+
+{{#if voiceId}}
+## Voice Output
+
+Your assigned voice: **{{voice}}** (ID: {{voiceId}})
+
+If voice notifications are enabled, use this voice ID for TTS output.
+{{/if}}
+
+{{#if task}}
+## Your Task
+
+{{{task}}}
+{{/if}}
+
+## Operational Guidelines
+
+1. **Stay in character**: Maintain your composed personality consistently
+2. **Leverage your expertise**: Your domain knowledge is your primary value
+3. **Follow your approach**: Work in the style you've been configured for
+4. **Acknowledge limits**: If the task requires expertise outside your composition, say so
+5. **Deliver quality**: You are a specialist - your output should reflect that
+
+---
+
+Begin your work now.
diff --git a/Packs/kai-agents-skill/src/skills/Agents/Tools/AgentFactory.ts b/Packs/kai-agents-skill/src/skills/Agents/Tools/AgentFactory.ts
new file mode 100644
index 00000000..2b9b581a
--- /dev/null
+++ b/Packs/kai-agents-skill/src/skills/Agents/Tools/AgentFactory.ts
@@ -0,0 +1,362 @@
+#!/usr/bin/env bun
+
+/**
+ * AgentFactory - Dynamic Agent Composition from Traits
+ *
+ * Composes specialized agents on-the-fly by combining traits from Traits.yaml.
+ *
+ * Usage:
+ * bun run AgentFactory.ts --task "Review this security architecture"
+ * bun run AgentFactory.ts --traits "security,skeptical,thorough"
+ * bun run AgentFactory.ts --list
+ *
+ * @version 1.0.0
+ */
+
+import { parseArgs } from "util";
+import { readFileSync, existsSync } from "fs";
+import { parse as parseYaml } from "yaml";
+import Handlebars from "handlebars";
+
+// Paths - adjust PAI_DIR as needed
+const PAI_DIR = process.env.PAI_DIR || `${process.env.HOME}/.config/pai`;
+const TRAITS_PATH = `${PAI_DIR}/skills/Agents/Data/Traits.yaml`;
+const TEMPLATE_PATH = `${PAI_DIR}/skills/Agents/Templates/DynamicAgent.hbs`;
+
+// Types
+interface TraitDefinition {
+ name: string;
+ description: string;
+ prompt_fragment?: string;
+ keywords?: string[];
+}
+
+interface VoiceMapping {
+ traits: string[];
+ voice: string;
+ voice_id?: string;
+ reason?: string;
+}
+
+interface VoiceRegistryEntry {
+ voice_id: string;
+ characteristics: string[];
+ description: string;
+ stability: number;
+ similarity_boost: number;
+}
+
+interface TraitsData {
+ expertise: Record<string, TraitDefinition>;
+ personality: Record<string, TraitDefinition>;
+ approach: Record<string, TraitDefinition>;
+ voice_mappings: {
+ default: string;
+ default_voice_id: string;
+ voice_registry: Record<string, VoiceRegistryEntry>;
+ mappings: VoiceMapping[];
+ fallbacks: Record<string, string>;
+ };
+ examples: Record<string, { description: string; traits: string[] }>;
+}
+
+interface ComposedAgent {
+ name: string;
+ traits: string[];
+ expertise: TraitDefinition[];
+ personality: TraitDefinition[];
+ approach: TraitDefinition[];
+ voice: string;
+ voiceId: string;
+ voiceReason: string;
+ prompt: string;
+}
+
+function loadTraits(): TraitsData {
+ if (!existsSync(TRAITS_PATH)) {
+ console.error(`Error: Traits file not found at ${TRAITS_PATH}`);
+ process.exit(1);
+ }
+ const content = readFileSync(TRAITS_PATH, "utf-8");
+ return parseYaml(content) as TraitsData;
+}
+
+function loadTemplate(): ReturnType<typeof Handlebars.compile> {
+ if (!existsSync(TEMPLATE_PATH)) {
+ console.error(`Error: Template file not found at ${TEMPLATE_PATH}`);
+ process.exit(1);
+ }
+ const content = readFileSync(TEMPLATE_PATH, "utf-8");
+ return Handlebars.compile(content);
+}
+
+function inferTraitsFromTask(task: string, traits: TraitsData): string[] {
+ const inferred: string[] = [];
+ const taskLower = task.toLowerCase();
+
+ // Check expertise keywords
+ for (const [key, def] of Object.entries(traits.expertise)) {
+ if (def.keywords?.some((kw) => taskLower.includes(kw.toLowerCase()))) {
+ inferred.push(key);
+ }
+ }
+
+ // Check personality keywords
+ for (const [key, def] of Object.entries(traits.personality)) {
+ if (def.keywords?.some((kw) => taskLower.includes(kw.toLowerCase()))) {
+ inferred.push(key);
+ }
+ }
+
+ // Check approach keywords
+ for (const [key, def] of Object.entries(traits.approach)) {
+ if (def.keywords?.some((kw) => taskLower.includes(kw.toLowerCase()))) {
+ inferred.push(key);
+ }
+ }
+
+ // Apply smart defaults
+ const hasExpertise = inferred.some((t) => traits.expertise[t]);
+ const hasPersonality = inferred.some((t) => traits.personality[t]);
+ const hasApproach = inferred.some((t) => traits.approach[t]);
+
+ if (!hasPersonality) inferred.push("analytical");
+ if (!hasApproach) inferred.push("thorough");
+ if (!hasExpertise) inferred.push("research");
+
+ return [...new Set(inferred)];
+}
+
+function resolveVoice(
+ traitKeys: string[],
+ traits: TraitsData
+): { voice: string; voiceId: string; reason: string } {
+ const mappings = traits.voice_mappings;
+ const registry = mappings.voice_registry || {};
+
+ const getVoiceId = (voiceName: string, fallbackId?: string): string => {
+ if (registry[voiceName]?.voice_id) {
+ return registry[voiceName].voice_id;
+ }
+ return fallbackId || mappings.default_voice_id || "";
+ };
+
+ // Check explicit combination mappings
+ const matchedMappings = mappings.mappings
+ .map((m) => ({
+ ...m,
+ matchCount: m.traits.filter((t) => traitKeys.includes(t)).length,
+ isFullMatch: m.traits.every((t) => traitKeys.includes(t)),
+ }))
+ .filter((m) => m.isFullMatch)
+ .sort((a, b) => b.matchCount - a.matchCount);
+
+ if (matchedMappings.length > 0) {
+ const best = matchedMappings[0];
+ return {
+ voice: best.voice,
+ voiceId: best.voice_id || getVoiceId(best.voice),
+ reason: best.reason || `Matched traits: ${best.traits.join(", ")}`,
+ };
+ }
+
+ // Check fallbacks
+ for (const trait of traitKeys) {
+ if (mappings.fallbacks[trait]) {
+ const voiceName = mappings.fallbacks[trait];
+ return {
+ voice: voiceName,
+ voiceId: getVoiceId(voiceName),
+ reason: `Fallback for trait: ${trait}`,
+ };
+ }
+ }
+
+ return {
+ voice: mappings.default,
+ voiceId: mappings.default_voice_id || "",
+ reason: "Default voice",
+ };
+}
+
+function composeAgent(
+ traitKeys: string[],
+ task: string,
+ traits: TraitsData
+): ComposedAgent {
+ const expertise: TraitDefinition[] = [];
+ const personality: TraitDefinition[] = [];
+ const approach: TraitDefinition[] = [];
+
+ for (const key of traitKeys) {
+ if (traits.expertise[key]) expertise.push(traits.expertise[key]);
+ if (traits.personality[key]) personality.push(traits.personality[key]);
+ if (traits.approach[key]) approach.push(traits.approach[key]);
+ }
+
+ const nameParts: string[] = [];
+ if (expertise.length) nameParts.push(expertise[0].name);
+ if (personality.length) nameParts.push(personality[0].name);
+ if (approach.length) nameParts.push(approach[0].name);
+ const name = nameParts.length > 0 ? nameParts.join(" ") : "Dynamic Agent";
+
+ const { voice, voiceId, reason: voiceReason } = resolveVoice(traitKeys, traits);
+
+ const template = loadTemplate();
+ const prompt = template({
+ name,
+ task,
+ expertise,
+ personality,
+ approach,
+ voice,
+ voiceId,
+ });
+
+ return {
+ name,
+ traits: traitKeys,
+ expertise,
+ personality,
+ approach,
+ voice,
+ voiceId,
+ voiceReason,
+ prompt,
+ };
+}
+
+function listTraits(traits: TraitsData): void {
+ console.log("AVAILABLE TRAITS\n");
+
+ console.log("EXPERTISE (domain knowledge):");
+ for (const [key, def] of Object.entries(traits.expertise)) {
+ console.log(` ${key.padEnd(15)} - ${def.name}`);
+ }
+
+ console.log("\nPERSONALITY (behavior style):");
+ for (const [key, def] of Object.entries(traits.personality)) {
+ console.log(` ${key.padEnd(15)} - ${def.name}`);
+ }
+
+ console.log("\nAPPROACH (work style):");
+ for (const [key, def] of Object.entries(traits.approach)) {
+ console.log(` ${key.padEnd(15)} - ${def.name}`);
+ }
+
+ console.log("\nEXAMPLE COMPOSITIONS:");
+ for (const [key, example] of Object.entries(traits.examples)) {
+ console.log(` ${key.padEnd(18)} - ${example.description}`);
+ console.log(` traits: ${example.traits.join(", ")}`);
+ }
+}
+
+async function main() {
+ const { values } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ task: { type: "string", short: "t" },
+ traits: { type: "string", short: "r" },
+ output: { type: "string", short: "o", default: "prompt" },
+ list: { type: "boolean", short: "l" },
+ help: { type: "boolean", short: "h" },
+ },
+ });
+
+ if (values.help) {
+ console.log(`
+AgentFactory - Compose dynamic agents from traits
+
+USAGE:
+ bun run AgentFactory.ts [options]
+
+OPTIONS:
+ -t, --task <desc> Task description (traits will be inferred)
+ -r, --traits <list> Comma-separated trait keys
+ -o, --output <fmt> Output format: prompt (default), json, yaml, summary
+ -l, --list List all available traits
+ -h, --help Show this help
+
+EXAMPLES:
+ bun run AgentFactory.ts -t "Review this security architecture"
+ bun run AgentFactory.ts -r "security,skeptical,adversarial,thorough"
+ bun run AgentFactory.ts --list
+`);
+ return;
+ }
+
+ const traits = loadTraits();
+ if (values.list) {
+ listTraits(traits);
+ return;
+ }
+
+ let traitKeys: string[] = [];
+
+ if (values.traits) {
+ traitKeys = values.traits.split(",").map((t) => t.trim().toLowerCase());
+ }
+
+ if (values.task) {
+ const inferred = inferTraitsFromTask(values.task, traits);
+ traitKeys = [...new Set([...traitKeys, ...inferred])];
+ }
+
+ if (traitKeys.length === 0) {
+ console.error("Error: Provide --task or --traits");
+ process.exit(1);
+ }
+
+ const allTraitKeys = [
+ ...Object.keys(traits.expertise),
+ ...Object.keys(traits.personality),
+ ...Object.keys(traits.approach),
+ ];
+ const invalidTraits = traitKeys.filter((t) => !allTraitKeys.includes(t));
+ if (invalidTraits.length > 0) {
+ console.error(`Error: Unknown traits: ${invalidTraits.join(", ")}`);
+ process.exit(1);
+ }
+
+ const agent = composeAgent(traitKeys, values.task || "", traits);
+
+ switch (values.output) {
+ case "json":
+ console.log(
+ JSON.stringify(
+ {
+ name: agent.name,
+ traits: agent.traits,
+ voice: agent.voice,
+ voice_id: agent.voiceId,
+ voiceReason: agent.voiceReason,
+ expertise: agent.expertise.map((e) => e.name),
+ personality: agent.personality.map((p) => p.name),
+ approach: agent.approach.map((a) => a.name),
+ prompt: agent.prompt,
+ },
+ null,
+ 2
+ )
+ );
+ break;
+
+ case "yaml":
+ console.log(`name: "${agent.name}"`);
+ console.log(`voice: "${agent.voice}"`);
+ console.log(`voice_id: "${agent.voiceId}"`);
+ console.log(`traits: [${agent.traits.join(", ")}]`);
+ break;
+
+ case "summary":
+ console.log(`COMPOSED AGENT: ${agent.name}`);
+ console.log(`Traits: ${agent.traits.join(", ")}`);
+ console.log(`Voice: ${agent.voice} [${agent.voiceId}]`);
+ break;
+
+ default:
+ console.log(agent.prompt);
+ }
+}
+
+main().catch(console.error);
diff --git a/Packs/kai-agents-skill/src/skills/Agents/Workflows/CreateCustomAgent.md b/Packs/kai-agents-skill/src/skills/Agents/Workflows/CreateCustomAgent.md
new file mode 100644
index 00000000..87efe7ec
--- /dev/null
+++ b/Packs/kai-agents-skill/src/skills/Agents/Workflows/CreateCustomAgent.md
@@ -0,0 +1,117 @@
+# CreateCustomAgent Workflow
+
+**Creates custom agents with unique personalities and voice IDs using AgentFactory.**
+
+## When to Use
+
+User says:
+- "Create custom agents to do X"
+- "Spin up custom agents for Y"
+- "I need specialized agents with Z expertise"
+
+**KEY TRIGGER: The word "custom" distinguishes from generic agents.**
+
+## The Workflow
+
+### Step 1: Determine Requirements
+
+Extract from user's request:
+- How many agents? (Default: 1)
+- What's the task?
+- Are specific traits mentioned?
+
+### Step 2: Run AgentFactory for EACH Agent with DIFFERENT Traits
+
+**CRITICAL: Each agent MUST have different trait combinations for unique voices.**
+
+```bash
+# Example for 3 custom research agents:
+
+# Agent 1 - Enthusiastic Explorer
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --traits "research,enthusiastic,exploratory" \
+ --task "Research quantum computing" \
+ --output json
+
+# Agent 2 - Skeptical Analyst
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --traits "research,skeptical,systematic" \
+ --task "Research quantum computing" \
+ --output json
+
+# Agent 3 - Thorough Synthesizer
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --traits "research,analytical,synthesizing" \
+ --task "Research quantum computing" \
+ --output json
+```
+
+### Step 3: Launch Agents in Parallel
+
+**CRITICAL: Use `subagent_type: "general-purpose"` - NEVER "Intern" for custom agents!**
+
+Using "Intern" would override the custom voice. We need "general-purpose" to respect the voice_id from AgentFactory.
+
+Use a SINGLE message with MULTIPLE Task calls:
+
+```typescript
+Task({
+ description: "Research agent 1 - enthusiastic",
+ prompt: <agent1_full_prompt>,
+ subagent_type: "general-purpose", // NEVER "Intern" for custom agents!
+ model: "sonnet"
+})
+Task({
+ description: "Research agent 2 - skeptical",
+ prompt: <agent2_full_prompt>,
+ subagent_type: "general-purpose", // NEVER "Intern" for custom agents!
+ model: "sonnet"
+})
+```
+
+## Trait Variation Strategies
+
+**For Research Tasks:**
+- Agent 1: research + enthusiastic + exploratory -> Energetic voice
+- Agent 2: research + skeptical + thorough -> Academic voice
+- Agent 3: research + analytical + systematic -> Professional voice
+
+**For Security Analysis:**
+- Agent 1: security + adversarial + bold -> Intense voice
+- Agent 2: security + skeptical + meticulous -> Gritty voice
+- Agent 3: security + cautious + systematic -> Professional voice
+
+## Model Selection
+
+| Task Type | Model | Reason |
+|-----------|-------|--------|
+| Quick checks | `haiku` | 10-20x faster |
+| Standard analysis | `sonnet` | Balanced |
+| Deep reasoning | `opus` | Maximum intelligence |
+
+## Common Mistakes
+
+**WRONG: Using named agent types for custom agents**
+```typescript
+// WRONG - forces same voice on all custom agents!
+Task({ prompt: <custom_prompt>, subagent_type: "Intern" })
+Task({ prompt: <custom_prompt>, subagent_type: "Designer" })
+```
+
+**RIGHT: Using general-purpose for custom agents**
+```typescript
+// CORRECT - respects the custom voice from AgentFactory
+Task({ prompt: <custom_prompt>, subagent_type: "general-purpose" })
+```
+
+**WRONG: Same traits for all agents**
+```bash
+bun run AgentFactory.ts --traits "research,analytical" # Agent 1
+bun run AgentFactory.ts --traits "research,analytical" # Same voice!
+```
+
+**RIGHT: Vary traits for unique voices**
+```bash
+bun run AgentFactory.ts --traits "research,enthusiastic,exploratory"
+bun run AgentFactory.ts --traits "research,skeptical,systematic"
+```
diff --git a/Packs/kai-agents-skill/src/skills/Agents/Workflows/ListTraits.md b/Packs/kai-agents-skill/src/skills/Agents/Workflows/ListTraits.md
new file mode 100644
index 00000000..173f1cc6
--- /dev/null
+++ b/Packs/kai-agents-skill/src/skills/Agents/Workflows/ListTraits.md
@@ -0,0 +1,68 @@
+# ListTraits Workflow
+
+**Displays all available traits for agent composition.**
+
+## When to Use
+
+User asks:
+- "What agent personalities can you create?"
+- "Show me available traits"
+- "What expertise types are there?"
+
+## The Workflow
+
+Run AgentFactory with --list flag:
+
+```bash
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts --list
+```
+
+## Output
+
+```
+AVAILABLE TRAITS
+
+EXPERTISE (domain knowledge):
+ security - Security Expert
+ legal - Legal Analyst
+ finance - Financial Analyst
+ medical - Medical/Health Expert
+ technical - Technical Specialist
+ research - Research Specialist
+ creative - Creative Specialist
+ business - Business Strategist
+ data - Data Analyst
+ communications - Communications Expert
+
+PERSONALITY (behavior style):
+ skeptical - Skeptical
+ enthusiastic - Enthusiastic
+ cautious - Cautious
+ bold - Bold
+ analytical - Analytical
+ creative - Creative
+ empathetic - Empathetic
+ contrarian - Contrarian
+ pragmatic - Pragmatic
+ meticulous - Meticulous
+
+APPROACH (work style):
+ thorough - Thorough
+ rapid - Rapid
+ systematic - Systematic
+ exploratory - Exploratory
+ comparative - Comparative
+ synthesizing - Synthesizing
+ adversarial - Adversarial
+ consultative - Consultative
+```
+
+## Quick Reference Card
+
+| Category | Count | Purpose |
+|----------|-------|---------|
+| Expertise | 10 | Domain knowledge |
+| Personality | 10 | How they think |
+| Approach | 8 | How they work |
+
+**Total combinations:** 10 x 10 x 8 = **800 unique agent compositions**
diff --git a/Packs/kai-art-skill/INSTALL.md b/Packs/kai-art-skill/INSTALL.md
new file mode 100644
index 00000000..6fc46d92
--- /dev/null
+++ b/Packs/kai-art-skill/INSTALL.md
@@ -0,0 +1,176 @@
+# Installation Guide - Kai Art Skill
+
+## 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** (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
+
+### 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"
+ 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
+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
+```
+
+---
+
+## Installation Steps
+
+### Step 1: Create Directory Structure
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+mkdir -p "$PAI_DIR/skills/Art/Workflows"
+mkdir -p "$PAI_DIR/skills/Art/Tools"
+
+echo "Created directories:"
+ls -la "$PAI_DIR/skills/Art/"
+```
+
+### Step 2: Copy Skill Files
+
+Copy from this pack's `src/` directory to your PAI installation:
+
+| Source | Destination |
+|--------|-------------|
+| `src/skills/Art/SKILL.md` | `$PAI_DIR/skills/Art/SKILL.md` |
+| `src/skills/Art/Aesthetic.md` | `$PAI_DIR/skills/Art/Aesthetic.md` |
+| `src/skills/Art/Workflows/TechnicalDiagrams.md` | `$PAI_DIR/skills/Art/Workflows/TechnicalDiagrams.md` |
+| `src/skills/Art/Workflows/Essay.md` | `$PAI_DIR/skills/Art/Workflows/Essay.md` |
+| `src/skills/Art/Workflows/Comics.md` | `$PAI_DIR/skills/Art/Workflows/Comics.md` |
+| `src/skills/Art/Tools/Generate.ts` | `$PAI_DIR/skills/Art/Tools/Generate.ts` |
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+PACK_DIR="[PATH_TO_THIS_PACK]"
+
+cp "$PACK_DIR/src/skills/Art/SKILL.md" "$PAI_DIR/skills/Art/"
+cp "$PACK_DIR/src/skills/Art/Aesthetic.md" "$PAI_DIR/skills/Art/"
+cp "$PACK_DIR/src/skills/Art/Workflows/TechnicalDiagrams.md" "$PAI_DIR/skills/Art/Workflows/"
+cp "$PACK_DIR/src/skills/Art/Workflows/Essay.md" "$PAI_DIR/skills/Art/Workflows/"
+cp "$PACK_DIR/src/skills/Art/Workflows/Comics.md" "$PAI_DIR/skills/Art/Workflows/"
+cp "$PACK_DIR/src/skills/Art/Tools/Generate.ts" "$PAI_DIR/skills/Art/Tools/"
+```
+
+### Step 3: Set Up Environment Variables
+
+```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" << '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
+EOF
+ echo "Created $PAI_DIR/.env - Please add your API keys"
+else
+ echo ".env already exists at $PAI_DIR/.env"
+fi
+```
+
+### Step 4: Install Dependencies
+
+```bash
+cd "$PAI_DIR/skills/Art/Tools"
+bun install replicate openai @google/genai
+```
+
+---
+
+## Verification
+
+Run the verification script:
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "Verifying Art Skill installation..."
+
+# 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"
+
+# Test CLI tool
+echo ""
+echo "Test CLI tool:"
+bun run "$PAI_DIR/skills/Art/Tools/Generate.ts" --help | head -5
+
+echo ""
+echo "Installation complete!"
+```
+
+---
+
+## Environment Variables
+
+| Variable | Required For | Description |
+|----------|-------------|-------------|
+| `REPLICATE_API_TOKEN` | Flux, Nano Banana | Replicate API access |
+| `GOOGLE_API_KEY` | Nano Banana Pro | Google Gemini API access |
+| `OPENAI_API_KEY` | GPT-image-1 | OpenAI API access |
+| `REMOVEBG_API_KEY` | Background removal | remove.bg API access |
+| `PAI_DIR` | All | Custom PAI directory (optional) |
diff --git a/Packs/kai-art-skill/README.md b/Packs/kai-art-skill/README.md
new file mode 100644
index 00000000..ee23aac0
--- /dev/null
+++ b/Packs/kai-art-skill/README.md
@@ -0,0 +1,122 @@
+---
+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]
+---
+
+# Kai Art Skill
+
+> Visual content generation system with Excalidraw hand-drawn aesthetic - technical diagrams, comics, and editorial illustrations with consistent dark-mode styling
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| Art skill | `src/skills/Art/SKILL.md` | Routing and quick reference |
+| Aesthetic config | `src/skills/Art/Aesthetic.md` | Style preferences and palette |
+| Generate tool | `src/skills/Art/Tools/Generate.ts` | Multi-model image generation CLI |
+| Technical diagrams | `src/skills/Art/Workflows/TechnicalDiagrams.md` | Architecture diagram workflow |
+| Essay headers | `src/skills/Art/Workflows/Essay.md` | Blog header image workflow |
+| Comics workflow | `src/skills/Art/Workflows/Comics.md` | Sequential panel generation |
+
+## The 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
+- **Prompt Overhead**: Re-discovering effective prompts each time
+- **Technical Complexity**: Different models have different APIs and parameters
+- **Quality Control**: No validation that output matches intent
+
+## The Solution
+
+The Art Skill solves this through **workflow-based generation**:
+
+```
+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**: Visual style documented in Aesthetic.md
+2. **Workflow Templates**: Proven prompt structures that consistently produce quality
+3. **Intent-to-Flag Mapping**: User intent maps to specific CLI flags
+4. **Validation Checklists**: Must-have and must-not-have criteria
+5. **CLI Determinism**: Same flags, same behavior across models
+
+## Invocation Scenarios
+
+| User Request | Workflow | Output |
+|--------------|----------|--------|
+| "create a diagram of the auth flow" | TechnicalDiagrams | Architecture diagram PNG |
+| "create a header for my blog post about Y" | Essay | Editorial illustration PNG |
+| "make a comic showing before/after" | Comics | 3-4 panel comic strip PNG |
+
+## Example Usage
+
+### Technical Diagram
+
+```bash
+bun run $PAI_DIR/skills/Art/Tools/Generate.ts \
+ --model nano-banana-pro \
+ --prompt "Clean Excalidraw-style technical diagram..." \
+ --size 2K \
+ --aspect-ratio 16:9 \
+ --output ~/Downloads/auth-diagram.png
+```
+
+### Blog Header with Thumbnail
+
+```bash
+bun run $PAI_DIR/skills/Art/Tools/Generate.ts \
+ --model nano-banana-pro \
+ --prompt "Hand-drawn Excalidraw-style illustration..." \
+ --size 2K \
+ --aspect-ratio 1:1 \
+ --thumbnail \
+ --output ~/Downloads/header.png
+```
+
+## Changelog
+
+### 1.1.0 - 2025-12-29
+- **Multiple reference images**: Support up to 14 reference images for improved character/style consistency
+- 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
diff --git a/Packs/kai-art-skill/VERIFY.md b/Packs/kai-art-skill/VERIFY.md
new file mode 100644
index 00000000..06bb4e98
--- /dev/null
+++ b/Packs/kai-art-skill/VERIFY.md
@@ -0,0 +1,122 @@
+# Verification Checklist - Kai Art Skill
+
+## Mandatory Completion Checklist
+
+**IMPORTANT**: This checklist MUST be completed before marking installation as done.
+
+### File Structure Verification
+
+- [ ] `$PAI_DIR/skills/Art/SKILL.md` exists and is readable
+- [ ] `$PAI_DIR/skills/Art/Aesthetic.md` exists and is readable
+- [ ] `$PAI_DIR/skills/Art/Workflows/TechnicalDiagrams.md` exists
+- [ ] `$PAI_DIR/skills/Art/Workflows/Essay.md` exists
+- [ ] `$PAI_DIR/skills/Art/Workflows/Comics.md` exists
+- [ ] `$PAI_DIR/skills/Art/Tools/Generate.ts` exists and is executable
+
+### CLI Tool Verification
+
+- [ ] `bun run $PAI_DIR/skills/Art/Tools/Generate.ts --help` shows usage information
+- [ ] At least one API key is configured in `$PAI_DIR/.env`
+
+### Functional Tests
+
+#### Test 1: Help Output
+```bash
+bun run $PAI_DIR/skills/Art/Tools/Generate.ts --help
+```
+**Expected**: Shows usage information with REQUIRED and OPTIONS sections
+
+#### Test 2: Generate Test Image (if API key available)
+```bash
+bun run $PAI_DIR/skills/Art/Tools/Generate.ts \
+ --model nano-banana-pro \
+ --prompt "Simple test: blue circle on dark background" \
+ --size 1K \
+ --aspect-ratio 1:1 \
+ --output ~/Downloads/art-test.png
+```
+**Expected**: Creates `~/Downloads/art-test.png`
+
+#### Test 3: Verify Image Created
+```bash
+ls -la ~/Downloads/art-test.png
+```
+**Expected**: File exists with reasonable size (>10KB)
+
+---
+
+## Quick Verification Script
+
+```bash
+#!/bin/bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "=== Art Skill Verification ==="
+echo ""
+
+PASS=0
+FAIL=0
+
+check() {
+ if [ "$1" = "0" ]; then
+ echo "[PASS] $2"
+ ((PASS++))
+ else
+ echo "[FAIL] $2"
+ ((FAIL++))
+ fi
+}
+
+# File checks
+[ -f "$PAI_DIR/skills/Art/SKILL.md" ]
+check $? "SKILL.md exists"
+
+[ -f "$PAI_DIR/skills/Art/Aesthetic.md" ]
+check $? "Aesthetic.md exists"
+
+[ -f "$PAI_DIR/skills/Art/Workflows/TechnicalDiagrams.md" ]
+check $? "TechnicalDiagrams.md exists"
+
+[ -f "$PAI_DIR/skills/Art/Workflows/Essay.md" ]
+check $? "Essay.md exists"
+
+[ -f "$PAI_DIR/skills/Art/Workflows/Comics.md" ]
+check $? "Comics.md exists"
+
+[ -f "$PAI_DIR/skills/Art/Tools/Generate.ts" ]
+check $? "Generate.ts exists"
+
+# CLI check
+bun run "$PAI_DIR/skills/Art/Tools/Generate.ts" --help >/dev/null 2>&1
+check $? "CLI tool runs"
+
+# API key check
+if [ -n "$REPLICATE_API_TOKEN" ] || [ -n "$GOOGLE_API_KEY" ] || [ -n "$OPENAI_API_KEY" ]; then
+ check 0 "At least one API key configured"
+else
+ check 1 "At least one API key configured"
+fi
+
+echo ""
+echo "=== Results: $PASS passed, $FAIL failed ==="
+
+if [ $FAIL -eq 0 ]; then
+ echo "Art Skill installation verified successfully!"
+ exit 0
+else
+ echo "Some checks failed. Review the output above."
+ exit 1
+fi
+```
+
+---
+
+## Troubleshooting
+
+| Issue | Solution |
+|-------|----------|
+| Generate.ts not found | Check `$PAI_DIR` is set correctly |
+| API key errors | Verify keys in `$PAI_DIR/.env` |
+| Missing dependencies | Run `bun install replicate openai @google/genai` |
+| Permission denied | Check file permissions on Generate.ts |
+| No image output | Check API key is valid and has credits |
diff --git a/Packs/kai-art-skill/src/skills/Art/Aesthetic.md b/Packs/kai-art-skill/src/skills/Art/Aesthetic.md
new file mode 100644
index 00000000..c3079d05
--- /dev/null
+++ b/Packs/kai-art-skill/src/skills/Art/Aesthetic.md
@@ -0,0 +1,155 @@
+# 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
diff --git a/Packs/kai-art-skill/src/skills/Art/SKILL.md b/Packs/kai-art-skill/src/skills/Art/SKILL.md
new file mode 100644
index 00000000..0215ec53
--- /dev/null
+++ b/Packs/kai-art-skill/src/skills/Art/SKILL.md
@@ -0,0 +1,95 @@
+---
+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
+```
diff --git a/Packs/kai-art-skill/src/skills/Art/Tools/Generate.ts b/Packs/kai-art-skill/src/skills/Art/Tools/Generate.ts
new file mode 100644
index 00000000..dc889830
--- /dev/null
+++ b/Packs/kai-art-skill/src/skills/Art/Tools/Generate.ts
@@ -0,0 +1,560 @@
+#!/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 as any);
+ 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 as any);
+ 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] as any).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] as any).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();
diff --git a/Packs/kai-art-skill/src/skills/Art/Workflows/Comics.md b/Packs/kai-art-skill/src/skills/Art/Workflows/Comics.md
new file mode 100644
index 00000000..30e6b7e2
--- /dev/null
+++ b/Packs/kai-art-skill/src/skills/Art/Workflows/Comics.md
@@ -0,0 +1,230 @@
+# 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**
diff --git a/Packs/kai-art-skill/src/skills/Art/Workflows/Essay.md b/Packs/kai-art-skill/src/skills/Art/Workflows/Essay.md
new file mode 100644
index 00000000..1534df5c
--- /dev/null
+++ b/Packs/kai-art-skill/src/skills/Art/Workflows/Essay.md
@@ -0,0 +1,178 @@
+# 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**
diff --git a/Packs/kai-art-skill/src/skills/Art/Workflows/TechnicalDiagrams.md b/Packs/kai-art-skill/src/skills/Art/Workflows/TechnicalDiagrams.md
new file mode 100644
index 00000000..0c3b5cb3
--- /dev/null
+++ b/Packs/kai-art-skill/src/skills/Art/Workflows/TechnicalDiagrams.md
@@ -0,0 +1,187 @@
+# 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**
diff --git a/Packs/kai-core-install/INSTALL.md b/Packs/kai-core-install/INSTALL.md
new file mode 100644
index 00000000..dfcb1a1d
--- /dev/null
+++ b/Packs/kai-core-install/INSTALL.md
@@ -0,0 +1,204 @@
+# Kai Core Install - Installation Guide
+
+## Prerequisites
+
+- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`
+- **Claude Code** (or compatible agent system)
+- **Write access** to `$PAI_DIR/` (or your PAI directory)
+- **kai-hook-system Pack** installed (required for session context loading)
+
+---
+
+## Pre-Installation: System Analysis
+
+### Step 0.1: Verify Environment and Dependencies
+
+```bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Check if PAI_DIR is set
+echo "PAI_DIR: ${PAI_DIR:-'NOT SET - will use ~/.config/pai'}"
+
+# Check for hook system (required)
+if [ -f "$PAI_CHECK/hooks/lib/observability.ts" ]; then
+ echo "✓ Hook system is installed (required)"
+else
+ echo "❌ Hook system NOT installed - install kai-hook-system first!"
+fi
+
+# Check for history system (optional)
+if [ -d "$PAI_CHECK/history" ]; then
+ echo "✓ History system is installed (optional)"
+else
+ echo "ℹ️ History system not installed (skill usage won't be logged)"
+fi
+```
+
+### Step 0.2: Detect Existing Installation
+
+```bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Check for existing Skills directory
+if [ -d "$PAI_CHECK/skills" ]; then
+ echo "⚠️ Skills directory EXISTS at: $PAI_CHECK/skills"
+ ls -la "$PAI_CHECK/skills" 2>/dev/null
+
+ if [ -d "$PAI_CHECK/skills/CORE" ]; then
+ echo ""
+ echo "⚠️ CORE skill directory exists - will merge/update"
+ fi
+else
+ echo "✓ No existing Skills directory (clean install)"
+fi
+```
+
+### Step 0.3: Backup Existing (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/skills/CORE" ]; then
+ mkdir -p "$BACKUP_DIR/skills"
+ cp -r "$PAI_CHECK/skills/CORE" "$BACKUP_DIR/skills/CORE"
+ echo "✓ Backed up CORE skill to $BACKUP_DIR/skills/CORE"
+fi
+```
+
+---
+
+## Step 1: Create Directory Structure
+
+```bash
+# Create the Skills directory
+mkdir -p $PAI_DIR/skills/CORE/Workflows
+mkdir -p $PAI_DIR/skills/CORE/Tools
+mkdir -p $PAI_DIR/skills/CreateSkill/Workflows
+mkdir -p $PAI_DIR/skills/CreateSkill/Tools
+mkdir -p $PAI_DIR/Tools
+```
+
+---
+
+## Step 2: Install SkillSystem.md
+
+Copy `src/skills/CORE/SkillSystem.md` to `$PAI_DIR/skills/CORE/SkillSystem.md`
+
+---
+
+## Step 3: Install Tools
+
+Copy the following tools to `$PAI_DIR/Tools/`:
+- `src/tools/SkillSearch.ts` → `$PAI_DIR/Tools/SkillSearch.ts`
+- `src/tools/GenerateSkillIndex.ts` → `$PAI_DIR/Tools/GenerateSkillIndex.ts`
+- `src/tools/PaiArchitecture.ts` → `$PAI_DIR/Tools/PaiArchitecture.ts`
+
+---
+
+## Step 4: Install CORE Skill
+
+Copy `src/skills/CORE/SKILL.md` to `$PAI_DIR/skills/CORE/SKILL.md`
+
+**IMPORTANT:** Customize the placeholders in SKILL.md:
+- `[YOUR_AI_NAME]` - Name for your AI (e.g., "Kai", "Atlas")
+- `[YOUR_NAME]` - Your name
+- `[YOUR_PROFESSION]` - Your profession
+
+---
+
+## Step 5: Install CreateSkill Meta-Skill
+
+Copy `src/skills/CreateSkill/SKILL.md` to `$PAI_DIR/skills/CreateSkill/SKILL.md`
+
+---
+
+## Step 6: Install Workflows
+
+Copy `src/skills/CORE/Workflows/UpdateDocumentation.md` to:
+`$PAI_DIR/skills/CORE/Workflows/UpdateDocumentation.md`
+
+---
+
+## Step 7: Generate Initial Index
+
+```bash
+bun run $PAI_DIR/Tools/GenerateSkillIndex.ts
+```
+
+---
+
+## Step 8: Generate Initial Architecture
+
+```bash
+bun run $PAI_DIR/Tools/PaiArchitecture.ts generate
+bun run $PAI_DIR/Tools/PaiArchitecture.ts log-upgrade "Initial kai-core-install installation"
+```
+
+---
+
+## Step 9: Verify Installation
+
+Run the verification checklist in VERIFY.md to confirm everything works.
+
+---
+
+## Customization
+
+### Recommended: Define Your Personality and Identity
+
+Edit `$PAI_DIR/skills/CORE/SKILL.md`:
+
+1. **Fill in Your Identity**
+```markdown
+## Identity
+
+**Assistant:**
+- Name: [Choose a name for your AI - e.g., "Kai", "Atlas", "Sage"]
+- Role: [Your name]'s AI assistant
+
+**User:**
+- Name: [Your name]
+- Profession: [Your profession - e.g., "Software Engineer", "Researcher"]
+```
+
+2. **Calibrate Personality Traits**
+```markdown
+| Trait | Value | Description |
+|-------|-------|-------------|
+| Humor | 60/100 | Higher = more witty, lower = more serious |
+| Curiosity | 90/100 | Higher = asks more questions, explores tangents |
+| Precision | 95/100 | Higher = more exact details |
+| Formality | 50/100 | Higher = more professional, lower = more casual |
+| Directness | 80/100 | Higher = blunt, lower = diplomatic |
+```
+
+### Optional Customization
+
+| Customization | File | Impact |
+|---------------|------|--------|
+| **Contacts Directory** | `Contacts.md` | Add your frequent contacts |
+| **Stack Preferences** | `CoreStack.md` | Define your technology preferences |
+| **Response Format** | `SKILL.md` | Modify the structured response format |
+| **Security Protocols** | `SecurityProtocols.md` | Add project-specific security rules |
+
+---
+
+## Troubleshooting
+
+### Skills Not Routing
+
+1. Verify SKILL.md has single-line description with USE WHEN
+2. Run GenerateSkillIndex.ts to rebuild index
+3. Check skill frontmatter format
+
+### Format Not Being Used
+
+1. Verify CORE loads at session start (check hooks)
+2. Ensure SKILL.md contains response format section
+
+### Architecture Not Generating
+
+1. Check PaiArchitecture.ts exists in Tools/
+2. Verify write permissions to skills/CORE/
+3. Run with explicit PAI_DIR: `PAI_DIR=~/.config/pai bun run ...`
diff --git a/Packs/kai-core-install/README.md b/Packs/kai-core-install/README.md
new file mode 100644
index 00000000..94514bae
--- /dev/null
+++ b/Packs/kai-core-install/README.md
@@ -0,0 +1,127 @@
+---
+name: Kai Core Install
+pack-id: danielmiessler-kai-core-install-v1.0.0
+version: 1.0.0
+author: danielmiessler
+description: Complete PAI core installation - skill routing, identity system, and architecture tracking. The foundation pack that makes everything else work.
+type: feature
+purpose-type: [productivity, automation, development]
+platform: claude-code
+dependencies:
+ - kai-hook-system (required) - Hooks enable session context loading and events
+ - kai-history-system (optional) - History capture for skill usage and learnings
+keywords: [core, identity, skills, routing, architecture, installation, foundation, personality, response-format, principles]
+---
+
+<p align="center">
+ <img src="../icons/kai-core-install.png" alt="Kai Core Install" width="256">
+</p>
+
+# Kai Core Install (kai-core-install)
+
+> The complete foundation for Personal AI Infrastructure - skill routing, identity framework, and architecture tracking in one unified pack.
+
+## What This Pack Provides
+
+**Part 1: Skill System**
+- **SKILL.md Format**: Standardized structure for all capabilities
+- **Intent Matching**: AI activates skills based on natural language triggers
+- **Workflow Routing**: Skills route to specific step-by-step procedures
+- **Dynamic Loading**: Only load context when actually needed
+- **Skill Discovery**: Search and browse available skills
+
+**Part 2: Identity Framework**
+- **Mandatory Response Format**: Structured output with emoji sections
+- **Personality Calibration**: Numeric precision for traits (enthusiasm, precision, etc.)
+- **Operating Constitution**: Core values and non-negotiable principles
+- **14 Founding Principles**: Architectural philosophy for building AI infrastructure
+- **First-Person Voice**: Natural, embodied communication
+
+**Part 3: Architecture Tracking**
+- **PAI Architecture.md**: Auto-generated tracking of installed packs, bundles, plugins
+- **Upgrade History**: Running record of all changes to your PAI system
+- **System Health**: Status checks for all installed components
+
+## Architecture Overview
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ SKILL LOADING TIERS │
+├─────────────────────────────────────────────────────────────────┤
+│ │
+│ TIER 0: CORE (Automatic) │
+│ ════════════════════════ │
+│ • Loads at session start │
+│ • NO trigger required │
+│ • ALWAYS present │
+│ │
+│─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│
+│ │
+│ TIER 1: Frontmatter Only (System Prompt) │
+│ ════════════════════════════════════════ │
+│ • SKILL.md frontmatter always in context │
+│ • USE WHEN triggers enable intent routing │
+│ • Minimal token cost │
+│ │
+│─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│
+│ │
+│ TIER 2: Full Skill (On Invoke) │
+│ ════════════════════════════════ │
+│ • SKILL.md body loads when triggered │
+│ • Workflow routing table available │
+│ │
+│─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│
+│ │
+│ TIER 3: Workflow (On Route) │
+│ ════════════════════════════ │
+│ • Specific workflow.md loads on routing │
+│ • Step-by-step instructions │
+│ │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| CORE skill template | `src/skills/CORE/SKILL.md` | Main identity and routing hub |
+| Skill system docs | `src/skills/CORE/SkillSystem.md` | Skill routing architecture |
+| CreateSkill skill | `src/skills/CreateSkill/SKILL.md` | Meta-skill for creating skills |
+| UpdateDocumentation | `src/skills/CORE/Workflows/UpdateDocumentation.md` | Architecture refresh workflow |
+| SkillSearch tool | `src/tools/SkillSearch.ts` | Search skill index |
+| GenerateSkillIndex | `src/tools/GenerateSkillIndex.ts` | Build skill index |
+| PaiArchitecture | `src/tools/PaiArchitecture.ts` | Generate architecture tracking |
+
+**Summary:**
+- **Files created:** 10+
+- **Hooks registered:** 0 (uses hook system from kai-hook-system)
+- **Dependencies:** kai-hook-system (required), kai-history-system (optional)
+
+## The 14 Founding Principles
+
+1. **Clear Thinking + Prompting is King** - Good prompts come from clear thinking
+2. **Scaffolding > Model** - Architecture matters more than which model
+3. **As Deterministic as Possible** - Same input → Same output
+4. **Code Before Prompts** - Use AI only for what needs intelligence
+5. **Spec / Test / Evals First** - Define expected behavior before building
+6. **UNIX Philosophy** - Do one thing well, compose tools
+7. **ENG / SRE Principles** - Apply software engineering to AI systems
+8. **CLI as Interface** - Every operation accessible via command line
+9. **Goal → Code → CLI → Prompts → Agents** - The proper pipeline
+10. **Meta / Self Update System** - System should improve itself
+11. **Custom Skill Management** - Skills are the organizational unit
+12. **Custom History System** - Automatic capture of valuable work
+13. **Custom Agent Personalities** - Different voices for different tasks
+14. **Science as Cognitive Loop** - Hypothesis → Experiment → Measure → Iterate
+
+## Credits
+
+- **Author:** Daniel Miessler
+- **Origin:** Extracted from production Kai system (2024-2025)
+- **License:** MIT
+
+## Works Well With
+
+- **kai-hook-system** (required) - Enables automatic CORE loading at session start
+- **kai-history-system** - Skills can reference past learnings and capture new ones
+- **kai-voice-system** - Response format drives voice output
diff --git a/Packs/kai-core-install/VERIFY.md b/Packs/kai-core-install/VERIFY.md
new file mode 100644
index 00000000..aa44090d
--- /dev/null
+++ b/Packs/kai-core-install/VERIFY.md
@@ -0,0 +1,167 @@
+# Kai Core Install - Verification Checklist
+
+## Mandatory Completion Checklist
+
+**IMPORTANT:** All items must be verified before considering this pack installed.
+
+### Directory Structure
+
+- [ ] `$PAI_DIR/skills/` directory exists
+- [ ] `$PAI_DIR/skills/CORE/` directory exists
+- [ ] `$PAI_DIR/skills/CORE/Workflows/` directory exists
+- [ ] `$PAI_DIR/skills/CreateSkill/` directory exists
+- [ ] `$PAI_DIR/Tools/` directory exists
+
+### Core Files
+
+- [ ] `$PAI_DIR/skills/CORE/SKILL.md` exists
+- [ ] `$PAI_DIR/skills/CORE/SkillSystem.md` exists
+- [ ] `$PAI_DIR/skills/CORE/Workflows/UpdateDocumentation.md` exists
+- [ ] `$PAI_DIR/skills/CreateSkill/SKILL.md` exists
+
+### Tools
+
+- [ ] `$PAI_DIR/Tools/SkillSearch.ts` exists
+- [ ] `$PAI_DIR/Tools/GenerateSkillIndex.ts` exists
+- [ ] `$PAI_DIR/Tools/PaiArchitecture.ts` exists
+
+### Generated Files
+
+- [ ] `$PAI_DIR/skills/skill-index.json` exists (run GenerateSkillIndex.ts)
+- [ ] `$PAI_DIR/skills/CORE/PaiArchitecture.md` exists (run PaiArchitecture.ts generate)
+
+---
+
+## Functional Tests
+
+### Test 1: Verify Directory Structure
+
+```bash
+ls -la $PAI_DIR/skills/
+# Expected: CORE/ CreateSkill/ skill-index.json
+
+ls -la $PAI_DIR/Tools/
+# Expected: SkillSearch.ts GenerateSkillIndex.ts PaiArchitecture.ts
+```
+
+### Test 2: Test Skill Search
+
+```bash
+bun run $PAI_DIR/Tools/SkillSearch.ts --list
+# Expected: Lists all indexed skills with icons
+```
+
+### Test 3: Search for Specific Skill
+
+```bash
+bun run $PAI_DIR/Tools/SkillSearch.ts "create skill"
+# Expected: Returns CreateSkill in results
+```
+
+### Test 4: Check Architecture Status
+
+```bash
+bun run $PAI_DIR/Tools/PaiArchitecture.ts status
+# Expected: Shows installed packs, bundles, system health
+```
+
+### Test 5: Verify System Health
+
+```bash
+bun run $PAI_DIR/Tools/PaiArchitecture.ts check
+# Expected: All systems show healthy status
+```
+
+### Test 6: Verify CORE Skill Content
+
+```bash
+cat $PAI_DIR/skills/CORE/SKILL.md | head -20
+# Expected: Shows YAML frontmatter with name: CORE
+```
+
+### Test 7: Verify Skill Index Format
+
+```bash
+cat $PAI_DIR/skills/skill-index.json | head -30
+# Expected: JSON with generated timestamp, totalSkills count, skills object
+```
+
+---
+
+## Integration Tests
+
+### Test A: Skill Routing
+
+In a Claude Code session:
+1. Say "search for a skill"
+2. AI should use SkillSearch tool
+3. Results should be returned
+
+### Test B: Architecture Tracking
+
+In a Claude Code session:
+1. Say "what's installed in my PAI system?"
+2. AI should read Architecture.md or run PaiArchitecture.ts
+3. Should show installed packs
+
+### Test C: Response Format (if configured)
+
+In a Claude Code session:
+1. Ask AI to complete a task
+2. Response should include structured sections (📋 SUMMARY, 🎯 COMPLETED, etc.)
+
+---
+
+## Quick Verification Script
+
+```bash
+#!/bin/bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "=== Kai Core Install Verification ==="
+echo ""
+
+# Check directories
+for dir in "skills" "skills/CORE" "skills/CORE/Workflows" "skills/CreateSkill" "Tools"; do
+ if [ -d "$PAI_CHECK/$dir" ]; then
+ echo "✓ $dir/"
+ else
+ echo "❌ $dir/ MISSING"
+ fi
+done
+
+echo ""
+
+# Check files
+for file in "skills/CORE/SKILL.md" "skills/CORE/SkillSystem.md" "skills/CreateSkill/SKILL.md" "Tools/SkillSearch.ts" "Tools/GenerateSkillIndex.ts" "Tools/PaiArchitecture.ts"; do
+ if [ -f "$PAI_CHECK/$file" ]; then
+ echo "✓ $file"
+ else
+ echo "❌ $file MISSING"
+ fi
+done
+
+echo ""
+
+# Check generated files
+if [ -f "$PAI_CHECK/skills/skill-index.json" ]; then
+ echo "✓ skill-index.json (generated)"
+else
+ echo "⚠️ skill-index.json not generated - run: bun run $PAI_CHECK/Tools/GenerateSkillIndex.ts"
+fi
+
+echo ""
+echo "=== Verification Complete ==="
+```
+
+---
+
+## Success Criteria
+
+Installation is complete when:
+
+1. All directory structure items are checked
+2. All core files are present
+3. All tools are installed
+4. `bun run $PAI_DIR/Tools/SkillSearch.ts --list` returns skill list
+5. `bun run $PAI_DIR/Tools/PaiArchitecture.ts check` shows healthy status
diff --git a/Packs/kai-core-install/src/skills/CORE/SKILL.md b/Packs/kai-core-install/src/skills/CORE/SKILL.md
new file mode 100644
index 00000000..8c545092
--- /dev/null
+++ b/Packs/kai-core-install/src/skills/CORE/SKILL.md
@@ -0,0 +1,77 @@
+---
+name: CORE
+description: Personal AI Infrastructure core. AUTO-LOADS at session start. USE WHEN any session begins OR user asks about identity, response format, contacts, stack preferences, security protocols, or asset management.
+---
+
+# CORE - Personal AI Infrastructure
+
+**Auto-loads at session start.** This skill defines your AI's identity, response format, and core operating principles.
+
+## Examples
+
+**Example: Check contact information**
+```
+User: "What's Angela's email?"
+→ Reads Contacts.md
+→ Returns contact information
+```
+
+---
+
+## Identity
+
+**Assistant:**
+- Name: [YOUR_AI_NAME]
+- Role: [YOUR_NAME]'s AI assistant
+
+**User:**
+- Name: [YOUR_NAME]
+- Profession: [YOUR_PROFESSION]
+
+---
+
+## Personality Calibration
+
+| Trait | Value | Description |
+|-------|-------|-------------|
+| Humor | [0-100]/100 | 0=serious, 100=witty |
+| Curiosity | [0-100]/100 | 0=focused, 100=exploratory |
+| Precision | [0-100]/100 | 0=approximate, 100=exact |
+| Formality | [0-100]/100 | 0=casual, 100=professional |
+| Directness | [0-100]/100 | 0=diplomatic, 100=blunt |
+
+---
+
+## First-Person Voice (CRITICAL)
+
+Your AI should speak as itself, not about itself in third person.
+
+**Correct:**
+- "for my system" / "in my architecture"
+- "I can spawn agents" / "my delegation patterns"
+
+**Wrong:**
+- "for [AI_NAME]" / "the system can"
+
+---
+
+## Response Format (Optional)
+
+```
+📋 SUMMARY: [One sentence]
+🔍 ANALYSIS: [Key findings]
+⚡ ACTIONS: [Steps taken]
+✅ RESULTS: [Outcomes]
+➡️ NEXT: [Recommended next steps]
+🎯 COMPLETED: [12 words max - drives voice output]
+```
+
+---
+
+## Quick Reference
+
+**Full documentation:**
+- Skill System: `SkillSystem.md`
+- Architecture: `PaiArchitecture.md` (auto-generated)
+- Contacts: `Contacts.md`
+- Stack: `CoreStack.md`
diff --git a/Packs/kai-core-install/src/skills/CORE/SkillSystem.md b/Packs/kai-core-install/src/skills/CORE/SkillSystem.md
new file mode 100644
index 00000000..859241d7
--- /dev/null
+++ b/Packs/kai-core-install/src/skills/CORE/SkillSystem.md
@@ -0,0 +1,82 @@
+# Custom Skill System
+
+**The MANDATORY configuration system for ALL skills.**
+
+## THIS IS THE AUTHORITATIVE SOURCE
+
+This document defines the **required structure** for every skill in the system.
+
+## TitleCase Naming Convention (MANDATORY)
+
+**All naming in the skill system MUST use TitleCase (PascalCase).**
+
+| Component | Wrong | Correct |
+|-----------|-------|---------|
+| Skill directory | `createskill`, `create-skill` | `CreateSkill` |
+| Workflow files | `create.md`, `update-info.md` | `Create.md`, `UpdateInfo.md` |
+| Tool files | `manage-server.ts` | `ManageServer.ts` |
+| YAML name | `name: create-skill` | `name: CreateSkill` |
+
+## The Required Structure
+
+Every SKILL.md has two parts:
+
+### 1. YAML Frontmatter (Single-Line Description)
+
+```yaml
+---
+name: SkillName
+description: [What it does]. USE WHEN [intent triggers using OR]. [Additional capabilities].
+---
+```
+
+**Rules:**
+- `name` uses **TitleCase**
+- `description` is a **single line** (not multi-line with `|`)
+- `USE WHEN` keyword is **MANDATORY**
+- Max 1024 characters
+
+### 2. Markdown Body (Workflow Routing + Examples)
+
+```markdown
+# SkillName
+
+[Brief description]
+
+## Workflow Routing
+
+| Workflow | Trigger | File |
+|----------|---------|------|
+| **WorkflowOne** | "trigger phrase" | `Workflows/WorkflowOne.md` |
+
+## Examples
+
+**Example 1: [Use case]**
+\`\`\`
+User: "[Request]"
+→ Invokes WorkflowOne workflow
+→ [Result]
+\`\`\`
+```
+
+## Directory Structure
+
+```
+SkillName/
+├── SKILL.md # Main skill file
+├── QuickStartGuide.md # Context files in root (TitleCase)
+├── Tools/ # CLI tools (ALWAYS present)
+│ └── ToolName.ts
+└── Workflows/ # Work execution workflows
+ └── Create.md
+```
+
+## Complete Checklist
+
+- [ ] Skill directory uses TitleCase
+- [ ] YAML `name:` uses TitleCase
+- [ ] Single-line `description` with `USE WHEN` clause
+- [ ] `## Workflow Routing` section with table format
+- [ ] `## Examples` section with 2-3 usage patterns
+- [ ] `Tools/` directory exists (even if empty)
+- [ ] All workflow files use TitleCase
diff --git a/Packs/kai-core-install/src/skills/CORE/Workflows/UpdateDocumentation.md b/Packs/kai-core-install/src/skills/CORE/Workflows/UpdateDocumentation.md
new file mode 100644
index 00000000..ee6d132d
--- /dev/null
+++ b/Packs/kai-core-install/src/skills/CORE/Workflows/UpdateDocumentation.md
@@ -0,0 +1,90 @@
+# UpdateDocumentation Workflow
+
+> **Trigger:** "update architecture", "refresh PAI state", OR automatically after any pack/bundle installation
+
+## Purpose
+
+Keeps PAI Architecture tracking current by:
+1. Regenerating the Architecture.md file with current installation state
+2. Logging upgrades to the history system
+3. Verifying system health after changes
+
+## When This Runs
+
+### Manual Invocation
+- User says "update my PAI architecture"
+- User says "refresh PAI state"
+- User says "what's installed?"
+
+### Automatic Invocation (CRITICAL)
+**This workflow MUST run automatically after:**
+- Installing any PAI Pack
+- Installing any PAI Bundle
+- Making significant configuration changes
+- Upgrading pack versions
+
+## Workflow Steps
+
+### Step 1: Regenerate Architecture
+
+```bash
+bun run $PAI_DIR/Tools/PaiArchitecture.ts generate
+```
+
+### Step 2: Log the Change (If Applicable)
+
+If this was triggered by an installation or upgrade:
+
+```bash
+# For pack installations
+bun run $PAI_DIR/Tools/PaiArchitecture.ts log-upgrade "Installed [pack-name] v[version]" pack
+
+# For bundle installations
+bun run $PAI_DIR/Tools/PaiArchitecture.ts log-upgrade "Installed [bundle-name] bundle" bundle
+
+# For config changes
+bun run $PAI_DIR/Tools/PaiArchitecture.ts log-upgrade "[description of change]" config
+```
+
+### Step 3: Verify Health
+
+```bash
+bun run $PAI_DIR/Tools/PaiArchitecture.ts check
+```
+
+### Step 4: Report Status
+
+Output the current architecture state to confirm the update was successful.
+
+## Integration with Pack Installation
+
+**All pack installation workflows should include this at the end:**
+
+```markdown
+## Post-Installation: Update Documentation
+
+After all installation steps complete:
+
+1. Run UpdateDocumentation workflow
+2. Log the pack installation
+3. Verify the pack appears in Architecture.md
+
+\`\`\`bash
+# Auto-run after pack installation
+bun run $PAI_DIR/Tools/PaiArchitecture.ts log-upgrade "Installed [pack-name] v[version]" pack
+bun run $PAI_DIR/Tools/PaiArchitecture.ts generate
+\`\`\`
+```
+
+## Example Output
+
+```
+📋 SUMMARY: Updated PAI Architecture documentation
+⚡ ACTIONS:
+ - Regenerated Architecture.md
+ - Logged upgrade: "Installed kai-voice-system v1.0.0"
+ - Verified system health
+✅ RESULTS: Architecture.md now shows 4 packs, 1 bundle
+📊 STATUS: All systems healthy
+🎯 COMPLETED: Architecture updated - 4 packs installed, all healthy.
+```
diff --git a/Packs/kai-core-install/src/skills/CreateSkill/SKILL.md b/Packs/kai-core-install/src/skills/CreateSkill/SKILL.md
new file mode 100644
index 00000000..efb1c91a
--- /dev/null
+++ b/Packs/kai-core-install/src/skills/CreateSkill/SKILL.md
@@ -0,0 +1,38 @@
+---
+name: CreateSkill
+description: Create and validate skills. USE WHEN create skill, new skill, skill structure, canonicalize. SkillSearch('createskill') for docs.
+---
+
+# CreateSkill
+
+MANDATORY skill creation framework for ALL skill creation requests.
+
+## Authoritative Source
+
+**Before creating ANY skill, READ:** `$PAI_DIR/skills/CORE/SkillSystem.md`
+
+## Workflow Routing
+
+| Workflow | Trigger | File |
+|----------|---------|------|
+| **CreateSkill** | "create a new skill" | `Workflows/CreateSkill.md` |
+| **ValidateSkill** | "validate skill" | `Workflows/ValidateSkill.md` |
+| **CanonicalizeSkill** | "canonicalize", "fix skill" | `Workflows/CanonicalizeSkill.md` |
+
+## Examples
+
+**Example 1: Create a new skill**
+```
+User: "Create a skill for managing my recipes"
+→ Invokes CreateSkill workflow
+→ Reads SkillSystem.md for structure
+→ Creates skill with TitleCase naming
+```
+
+**Example 2: Fix an existing skill**
+```
+User: "Canonicalize the daemon skill"
+→ Invokes CanonicalizeSkill workflow
+→ Renames files to TitleCase
+→ Ensures Examples section exists
+```
diff --git a/Packs/kai-core-install/src/tools/GenerateSkillIndex.ts b/Packs/kai-core-install/src/tools/GenerateSkillIndex.ts
new file mode 100644
index 00000000..3c27f169
--- /dev/null
+++ b/Packs/kai-core-install/src/tools/GenerateSkillIndex.ts
@@ -0,0 +1,102 @@
+#!/usr/bin/env bun
+/**
+ * GenerateSkillIndex.ts
+ *
+ * Parses all SKILL.md files and builds a searchable index.
+ *
+ * Usage: bun run $PAI_DIR/Tools/GenerateSkillIndex.ts
+ */
+
+import { readdir, readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { existsSync } from 'fs';
+
+const PAI_DIR = process.env.PAI_DIR || process.env.PAI_HOME || join(process.env.HOME || '', '.claude');
+const SKILLS_DIR = join(PAI_DIR, 'skills');
+const OUTPUT_FILE = join(SKILLS_DIR, 'skill-index.json');
+
+const ALWAYS_LOADED_SKILLS = ['CORE', 'Development', 'Research'];
+
+async function findSkillFiles(dir: string): Promise<string[]> {
+ const skillFiles: string[] = [];
+ const entries = await readdir(dir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
+ const skillMdPath = join(dir, entry.name, 'SKILL.md');
+ if (existsSync(skillMdPath)) skillFiles.push(skillMdPath);
+ }
+ }
+ return skillFiles;
+}
+
+function parseFrontmatter(content: string) {
+ const match = content.match(/^---\n([\s\S]*?)\n---/);
+ if (!match) return null;
+
+ const nameMatch = match[1].match(/^name:\s*(.+)$/m);
+ const descMatch = match[1].match(/^description:\s*(.+)$/m);
+
+ return {
+ name: nameMatch?.[1]?.trim() || '',
+ description: descMatch?.[1]?.trim() || ''
+ };
+}
+
+function extractTriggers(description: string): string[] {
+ const triggers: string[] = [];
+ const useWhenMatch = description.match(/USE WHEN[^.]+/gi);
+
+ if (useWhenMatch) {
+ for (const match of useWhenMatch) {
+ const words = match.replace(/USE WHEN/gi, '').split(/[,\s]+/)
+ .map(w => w.toLowerCase().trim())
+ .filter(w => w.length > 2);
+ triggers.push(...words);
+ }
+ }
+ return [...new Set(triggers)];
+}
+
+async function main() {
+ console.log('Generating skill index...\n');
+
+ const skillFiles = await findSkillFiles(SKILLS_DIR);
+ const index: any = {
+ generated: new Date().toISOString(),
+ totalSkills: 0,
+ alwaysLoadedCount: 0,
+ deferredCount: 0,
+ skills: {}
+ };
+
+ for (const filePath of skillFiles) {
+ const content = await readFile(filePath, 'utf-8');
+ const fm = parseFrontmatter(content);
+ if (!fm?.name) continue;
+
+ const tier = ALWAYS_LOADED_SKILLS.includes(fm.name) ? 'always' : 'deferred';
+ const key = fm.name.toLowerCase();
+
+ index.skills[key] = {
+ name: fm.name,
+ path: filePath.replace(SKILLS_DIR, '').replace(/^\//, ''),
+ fullDescription: fm.description,
+ triggers: extractTriggers(fm.description),
+ workflows: [],
+ tier
+ };
+
+ index.totalSkills++;
+ if (tier === 'always') index.alwaysLoadedCount++;
+ else index.deferredCount++;
+
+ console.log(` ${tier === 'always' ? '🔒' : '📦'} ${fm.name}`);
+ }
+
+ await writeFile(OUTPUT_FILE, JSON.stringify(index, null, 2));
+ console.log(`\n✅ Index generated: ${OUTPUT_FILE}`);
+ console.log(` Total: ${index.totalSkills} skills`);
+}
+
+main().catch(console.error);
diff --git a/Packs/kai-core-install/src/tools/PaiArchitecture.ts b/Packs/kai-core-install/src/tools/PaiArchitecture.ts
new file mode 100644
index 00000000..2ff3b5bc
--- /dev/null
+++ b/Packs/kai-core-install/src/tools/PaiArchitecture.ts
@@ -0,0 +1,213 @@
+#!/usr/bin/env bun
+/**
+ * PaiArchitecture.ts
+ *
+ * Scans the PAI installation and generates Architecture.md
+ * tracking all installed packs, bundles, plugins, and upgrades.
+ *
+ * Usage:
+ * bun PaiArchitecture.ts generate # Generate/refresh Architecture.md
+ * bun PaiArchitecture.ts status # Show current state (stdout)
+ * bun PaiArchitecture.ts check # Verify installation health
+ * bun PaiArchitecture.ts log-upgrade "description" # Add upgrade entry
+ */
+
+import { readdir, readFile, writeFile, appendFile } from 'fs/promises';
+import { join } from 'path';
+import { existsSync } from 'fs';
+
+const PAI_DIR = process.env.PAI_DIR || process.env.PAI_HOME || join(process.env.HOME || '', '.claude');
+const ARCHITECTURE_FILE = join(PAI_DIR, 'skills', 'CORE', 'PaiArchitecture.md');
+const BUNDLES_FILE = join(PAI_DIR, '.installed-bundles.json');
+const UPGRADES_FILE = join(PAI_DIR, 'history', 'Upgrades.jsonl');
+
+interface PackInfo {
+ name: string;
+ version: string;
+ installedDate: string;
+ status: 'healthy' | 'warning' | 'error';
+}
+
+interface BundleInfo {
+ name: string;
+ packs: string[];
+ installedDate: string;
+}
+
+interface UpgradeEntry {
+ date: string;
+ type: 'pack' | 'config' | 'bundle' | 'plugin';
+ description: string;
+}
+
+async function detectInstalledPacks(): Promise<PackInfo[]> {
+ const packs: PackInfo[] = [];
+ const skillsDir = join(PAI_DIR, 'skills');
+
+ if (!existsSync(skillsDir)) return packs;
+
+ const entries = await readdir(skillsDir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
+
+ const skillFile = join(skillsDir, entry.name, 'SKILL.md');
+ if (!existsSync(skillFile)) continue;
+
+ const content = await readFile(skillFile, 'utf-8');
+ const nameMatch = content.match(/^name:\s*(.+)$/m);
+
+ packs.push({
+ name: nameMatch?.[1]?.trim() || entry.name,
+ version: '1.0.0',
+ installedDate: new Date().toISOString().split('T')[0],
+ status: 'healthy'
+ });
+ }
+
+ return packs;
+}
+
+async function detectInstalledBundles(): Promise<BundleInfo[]> {
+ if (!existsSync(BUNDLES_FILE)) return [];
+
+ try {
+ const content = await readFile(BUNDLES_FILE, 'utf-8');
+ return JSON.parse(content);
+ } catch {
+ return [];
+ }
+}
+
+async function loadUpgradeHistory(): Promise<UpgradeEntry[]> {
+ if (!existsSync(UPGRADES_FILE)) return [];
+
+ try {
+ const content = await readFile(UPGRADES_FILE, 'utf-8');
+ return content.trim().split('\n').filter(l => l).map(l => JSON.parse(l));
+ } catch {
+ return [];
+ }
+}
+
+async function checkSystemHealth(): Promise<Record<string, string>> {
+ const health: Record<string, string> = {};
+
+ // Check hooks
+ const hooksDir = join(PAI_DIR, 'hooks');
+ health['Hook System'] = existsSync(hooksDir) ? '✓ Healthy' : '✗ Not installed';
+
+ // Check history
+ const historyDir = join(PAI_DIR, 'history');
+ health['History System'] = existsSync(historyDir) ? '✓ Healthy' : '✗ Not installed';
+
+ // Check skills
+ const skillsDir = join(PAI_DIR, 'skills');
+ if (existsSync(skillsDir)) {
+ const skills = (await readdir(skillsDir)).filter(f => !f.startsWith('.') && !f.endsWith('.json'));
+ health['Skills'] = `✓ ${skills.length} loaded`;
+ } else {
+ health['Skills'] = '✗ Not installed';
+ }
+
+ return health;
+}
+
+async function generateArchitectureMd(): Promise<string> {
+ const packs = await detectInstalledPacks();
+ const bundles = await detectInstalledBundles();
+ const upgrades = await loadUpgradeHistory();
+ const health = await checkSystemHealth();
+
+ let md = `# PAI Architecture
+
+> Auto-generated tracking file. Run \`bun $PAI_DIR/Tools/PaiArchitecture.ts generate\` to refresh.
+
+**Last Updated:** ${new Date().toISOString()}
+
+## Installation Summary
+
+| Category | Count |
+|----------|-------|
+| Packs | ${packs.length} |
+| Bundles | ${bundles.length} |
+| Upgrades | ${upgrades.length} |
+
+## Installed Packs
+
+| Pack | Version | Status |
+|------|---------|--------|
+${packs.map(p => `| ${p.name} | ${p.version} | ${p.status} |`).join('\n')}
+
+## Upgrade History
+
+| Date | Type | Description |
+|------|------|-------------|
+${upgrades.slice(-10).reverse().map(u => `| ${u.date} | ${u.type} | ${u.description} |`).join('\n') || '| - | - | No upgrades recorded |'}
+
+## System Health
+
+${Object.entries(health).map(([k, v]) => `- **${k}:** ${v}`).join('\n')}
+
+---
+
+*This file is auto-generated. Do not edit manually.*
+`;
+
+ return md;
+}
+
+async function logUpgrade(description: string, type: string = 'pack'): Promise<void> {
+ const entry: UpgradeEntry = {
+ date: new Date().toISOString().split('T')[0],
+ type: type as any,
+ description
+ };
+
+ const dir = join(PAI_DIR, 'history');
+ if (!existsSync(dir)) {
+ const { mkdir } = await import('fs/promises');
+ await mkdir(dir, { recursive: true });
+ }
+
+ await appendFile(UPGRADES_FILE, JSON.stringify(entry) + '\n');
+ console.log(`✓ Logged upgrade: ${description}`);
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ const command = args[0] || 'status';
+
+ switch (command) {
+ case 'generate':
+ const md = await generateArchitectureMd();
+ await writeFile(ARCHITECTURE_FILE, md);
+ console.log(`✓ Generated: ${ARCHITECTURE_FILE}`);
+ break;
+
+ case 'status':
+ console.log(await generateArchitectureMd());
+ break;
+
+ case 'check':
+ const health = await checkSystemHealth();
+ console.log('\n📊 System Health Check\n');
+ for (const [k, v] of Object.entries(health)) {
+ console.log(` ${k}: ${v}`);
+ }
+ break;
+
+ case 'log-upgrade':
+ if (!args[1]) {
+ console.error('Usage: PaiArchitecture.ts log-upgrade "description"');
+ process.exit(1);
+ }
+ await logUpgrade(args[1], args[2] || 'pack');
+ break;
+
+ default:
+ console.log('Usage: PaiArchitecture.ts [generate|status|check|log-upgrade]');
+ }
+}
+
+main().catch(console.error);
diff --git a/Packs/kai-core-install/src/tools/SkillSearch.ts b/Packs/kai-core-install/src/tools/SkillSearch.ts
new file mode 100644
index 00000000..558aa71e
--- /dev/null
+++ b/Packs/kai-core-install/src/tools/SkillSearch.ts
@@ -0,0 +1,86 @@
+#!/usr/bin/env bun
+/**
+ * SkillSearch.ts
+ *
+ * Search the skill index to discover capabilities dynamically.
+ *
+ * Usage:
+ * bun run $PAI_DIR/Tools/SkillSearch.ts <query>
+ * bun run $PAI_DIR/Tools/SkillSearch.ts --list
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { existsSync } from 'fs';
+
+const PAI_DIR = process.env.PAI_DIR || process.env.PAI_HOME || join(process.env.HOME || '', '.claude');
+const INDEX_FILE = join(PAI_DIR, 'skills', 'skill-index.json');
+
+interface SkillEntry {
+ name: string;
+ path: string;
+ fullDescription: string;
+ triggers: string[];
+ workflows: string[];
+ tier: 'always' | 'deferred';
+}
+
+interface SkillIndex {
+ generated: string;
+ totalSkills: number;
+ skills: Record<string, SkillEntry>;
+}
+
+function searchSkills(query: string, index: SkillIndex) {
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 1);
+ const results: { skill: SkillEntry; score: number }[] = [];
+
+ for (const [key, skill] of Object.entries(index.skills)) {
+ let score = 0;
+
+ if (key.includes(query.toLowerCase())) score += 10;
+
+ for (const term of queryTerms) {
+ for (const trigger of skill.triggers) {
+ if (trigger.includes(term)) score += 5;
+ }
+ if (skill.fullDescription.toLowerCase().includes(term)) score += 2;
+ }
+
+ if (score > 0) results.push({ skill, score });
+ }
+
+ return results.sort((a, b) => b.score - a.score);
+}
+
+async function main() {
+ if (!existsSync(INDEX_FILE)) {
+ console.error('❌ Skill index not found. Run GenerateSkillIndex.ts first.');
+ process.exit(1);
+ }
+
+ const index: SkillIndex = JSON.parse(await readFile(INDEX_FILE, 'utf-8'));
+ const args = process.argv.slice(2);
+
+ if (args.includes('--list') || args.length === 0) {
+ console.log(`\n📚 Skill Index (${index.totalSkills} skills)\n`);
+ for (const skill of Object.values(index.skills).sort((a, b) => a.name.localeCompare(b.name))) {
+ const icon = skill.tier === 'always' ? '🔒' : '📦';
+ console.log(` ${icon} ${skill.name.padEnd(20)} │ ${skill.triggers.slice(0, 3).join(', ')}`);
+ }
+ return;
+ }
+
+ const query = args.join(' ');
+ const results = searchSkills(query, index).slice(0, 5);
+
+ console.log(`\n🔍 Searching for: "${query}"\n`);
+ for (const { skill, score } of results) {
+ console.log(`\n${'─'.repeat(50)}`);
+ console.log(`${skill.tier === 'always' ? '🔒' : '📦'} **${skill.name}** (score: ${score})`);
+ console.log(`Path: ${skill.path}`);
+ console.log(`Workflows: ${skill.workflows.join(', ')}`);
+ }
+}
+
+main().catch(console.error);
diff --git a/Packs/kai-history-system/INSTALL.md b/Packs/kai-history-system/INSTALL.md
new file mode 100644
index 00000000..ffbd09ae
--- /dev/null
+++ b/Packs/kai-history-system/INSTALL.md
@@ -0,0 +1,151 @@
+# Installation Guide: Kai History System
+
+## 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 automatic memory to your entire AI infrastructure. The Kai History System is not just about agent outputs - it's a granular context-tracking system for EVERYTHING that happens:
+
+- **Continuous Learning**: Capture insights as they happen
+- **Bug Fixing**: Trace exactly what was done when debugging
+- **Avoiding Mistakes**: Learn from past errors automatically
+- **After-Action Reviews**: Analyze what worked and what didn't
+- **Restoration Points**: Recover from data loss with historical snapshots
+
+**Core principle:** Work normally, documentation handles itself.
+
+---
+
+## 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)
+- **kai-hook-system Pack** installed (this pack depends on the hook infrastructure)
+
+---
+
+## Pre-Installation: System Analysis
+
+### Step 0.1: Verify Dependencies
+
+```bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Check that hook system is installed
+if [ -f "$PAI_CHECK/hooks/lib/observability.ts" ]; then
+ echo "✓ Hook system is installed"
+else
+ echo "❌ Hook system NOT installed - install kai-hook-system first!"
+fi
+
+# Check hooks directory exists
+if [ -d "$PAI_CHECK/hooks" ]; then
+ echo "✓ Hooks directory exists"
+ ls "$PAI_CHECK/hooks"/*.ts 2>/dev/null | head -5
+else
+ echo "❌ Hooks directory missing - install kai-hook-system first!"
+fi
+```
+
+### Step 0.2: Detect Existing History System
+
+```bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Check for existing history directory
+if [ -d "$PAI_CHECK/history" ]; then
+ echo "⚠️ History directory EXISTS at: $PAI_CHECK/history"
+ echo "Existing categories:"
+ ls -la "$PAI_CHECK/history" 2>/dev/null
+else
+ echo "✓ No existing history directory (clean install)"
+fi
+```
+
+### Step 0.3: Backup Existing History (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/history" ]; then
+ mkdir -p "$BACKUP_DIR"
+ cp -r "$PAI_CHECK/history" "$BACKUP_DIR/history"
+ echo "✓ Backed up history to $BACKUP_DIR/history"
+fi
+```
+
+---
+
+## Step 1: Create Directory Structure
+
+```bash
+# Create all required directories
+mkdir -p $PAI_DIR/hooks/lib
+mkdir -p $PAI_DIR/history/{sessions,learnings,research,decisions,raw-outputs}
+mkdir -p $PAI_DIR/history/execution/{features,bugs,refactors}
+
+# Verify structure
+ls -la $PAI_DIR/
+ls -la $PAI_DIR/history/
+```
+
+---
+
+## Step 2: Install Source Files
+
+Copy all TypeScript files from this pack's `src/` directory to your hooks directory:
+
+```bash
+# Copy hook files
+cp src/capture-all-events.ts $PAI_DIR/hooks/
+cp src/stop-hook.ts $PAI_DIR/hooks/
+cp src/subagent-stop-hook.ts $PAI_DIR/hooks/
+cp src/capture-session-summary.ts $PAI_DIR/hooks/
+
+# Copy library files
+cp src/lib/metadata-extraction.ts $PAI_DIR/hooks/lib/
+
+# Verify all files are in place
+ls -la $PAI_DIR/hooks/*.ts
+ls -la $PAI_DIR/hooks/lib/*.ts
+```
+
+---
+
+## Step 3: Register Hooks in settings.json
+
+Merge the hook configuration from `config/settings-hooks.json` into your `~/.claude/settings.json`.
+
+**For existing installations:** Add the history hooks alongside your existing hooks in `~/.claude/settings.json`.
+
+---
+
+## Step 4: Restart Claude Code
+
+Hooks are only loaded when Claude Code starts. Restart Claude Code to activate the new hooks.
+
+---
+
+## Installation Verification
+
+After completing installation, run the verification steps in [VERIFY.md](VERIFY.md).
+
+---
+
+## Anti-Simplification Directive
+
+**CRITICAL FOR AI AGENTS:**
+
+This installation MUST be completed EXACTLY as specified. DO NOT:
+- Skip any files
+- Summarize or simplify code
+- Modify file paths
+- Skip verification steps
+
+After installation, you MUST complete the verification checklist in [VERIFY.md](VERIFY.md).
diff --git a/Packs/kai-history-system/README.md b/Packs/kai-history-system/README.md
new file mode 100644
index 00000000..44f56a70
--- /dev/null
+++ b/Packs/kai-history-system/README.md
@@ -0,0 +1,216 @@
+---
+name: Kai History System
+pack-id: danielmiessler-kai-history-system-core-v1.0.0
+version: 1.0.0
+author: danielmiessler
+description: Granular context-tracking system for the entire AI infrastructure - captures all work, decisions, and learnings automatically
+type: feature
+purpose-type: [productivity, automation, development]
+platform: claude-code
+dependencies:
+ - kai-hook-system (required) - History capture depends on hook events
+keywords: [history, documentation, memory, capture, hooks, sessions, learnings, automation, context, recovery, debugging]
+---
+
+<p align="center">
+ <img src="../icons/kai-history-system.png" alt="Kai History System" width="256">
+</p>
+
+# Kai History System (kai-history-system)
+
+> Granular context-tracking system for the entire AI infrastructure - captures all work, decisions, and learnings automatically with zero manual effort
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| Universal event capture | `src/capture-all-events.ts` | Log all events to JSONL for audit trail |
+| Stop hook | `src/stop-hook.ts` | Capture main agent completions and learnings |
+| Subagent stop hook | `src/subagent-stop-hook.ts` | Route subagent outputs by type |
+| Session summary | `src/capture-session-summary.ts` | Summarize sessions at close |
+| Metadata extraction lib | `src/lib/metadata-extraction.ts` | Extract agent instance metadata |
+| Hook config | `config/settings-hooks.json` | Claude Code hook registration template |
+
+**Summary:**
+- **Files created:** 6 + history directory structure
+- **Hooks registered:** 7 (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit)
+- **Dependencies:** kai-hook-system (required)
+
+## The Problem
+
+AI agents are powerful but forgetful. Each session starts fresh with no memory of:
+
+- What you built last week
+- Why you made certain architectural decisions
+- What bugs you've already fixed (and might reintroduce)
+- Lessons learned from debugging sessions
+- Research you've already conducted
+- What agents discovered during parallel execution
+
+This creates cascading problems:
+
+**For Development Work:**
+- You fix the same bug twice because you forgot the root cause
+- Architectural decisions lack rationale when revisited months later
+- Code reviews miss context because the "why" is lost
+
+**For Agent Orchestration:**
+- Parallel agents complete work that's never captured
+- Background research disappears when the session ends
+- Agent outputs aren't categorized or searchable
+
+**For Learning and Improvement:**
+- Insights get lost in conversation history
+- No after-action reviews are possible
+- Mistakes repeat because there's no institutional memory
+
+## The Solution
+
+The Kai History System solves this through **automatic, hook-based documentation**. Instead of requiring manual effort, it captures work as a byproduct of doing the work.
+
+**Core Architecture:**
+
+```
+$PAI_DIR/
+├── hooks/ # Hook implementations
+│ ├── capture-all-events.ts # Universal event capture (all hooks)
+│ ├── stop-hook.ts # Main agent completion capture
+│ ├── subagent-stop-hook.ts # Subagent output routing
+│ ├── capture-session-summary.ts # Session end summarization
+│ └── lib/ # Shared libraries
+│ └── metadata-extraction.ts # Agent instance tracking
+├── history/ # Captured outputs
+│ ├── sessions/YYYY-MM/ # Session summaries
+│ ├── learnings/YYYY-MM/ # Problem-solving narratives
+│ ├── research/YYYY-MM/ # Investigation reports
+│ ├── decisions/YYYY-MM/ # Architectural decisions
+│ ├── execution/
+│ │ ├── features/YYYY-MM/ # Feature implementations
+│ │ ├── bugs/YYYY-MM/ # Bug fixes
+│ │ └── refactors/YYYY-MM/ # Code improvements
+│ └── raw-outputs/YYYY-MM/ # JSONL event logs
+└── settings.json # Hook configuration
+```
+
+**Four Hooks, Complete Coverage:**
+
+1. **capture-all-events.ts** - Captures every event to daily JSONL logs
+2. **stop-hook.ts** - Categorizes main agent responses as learnings or sessions
+3. **subagent-stop-hook.ts** - Routes agent outputs by type (research, decisions, features)
+4. **capture-session-summary.ts** - Creates session summaries with files changed, tools used
+
+## Architecture Deep Dive
+
+```
+┌─────────────────────────────────────────────────────────────────────────┐
+│ HISTORY SYSTEM ARCHITECTURE │
+├─────────────────────────────────────────────────────────────────────────┤
+│ │
+│ ┌─────────────────────────────────────────────────────────────────┐ │
+│ │ LAYER 1: Event Capture │ │
+│ │ capture-all-events.ts hooks into EVERY Claude Code event │ │
+│ │ PreToolUse │ PostToolUse │ Stop │ SubagentStop │ SessionEnd │ │
+│ └──────────────────────────────┬──────────────────────────────────┘ │
+│ │ │
+│ ▼ │
+│ ┌─────────────────────────────────────────────────────────────────┐ │
+│ │ LAYER 2: Raw Storage │ │
+│ │ Every event → JSONL file with full payload │ │
+│ │ raw-outputs/YYYY-MM/YYYY-MM-DD_all-events.jsonl │ │
+│ └──────────────────────────────┬──────────────────────────────────┘ │
+│ │ │
+│ ▼ │
+│ ┌─────────────────────────────────────────────────────────────────┐ │
+│ │ LAYER 3: Content Analysis │ │
+│ │ Hooks analyze response content for category indicators │ │
+│ │ "problem + solved + root cause" → LEARNING │ │
+│ │ "completed + deployed" → SESSION │ │
+│ └──────────────────────────────┬──────────────────────────────────┘ │
+│ │ │
+│ ▼ │
+│ ┌─────────────────────────────────────────────────────────────────┐ │
+│ │ LAYER 4: Agent Type Routing │ │
+│ │ SubagentStop routes by agent type automatically │ │
+│ │ researcher/intern → research/ │ │
+│ │ architect → decisions/ │ │
+│ │ engineer/designer → execution/features/ │ │
+│ └──────────────────────────────┬──────────────────────────────────┘ │
+│ │ │
+│ ▼ │
+│ ┌─────────────────────────────────────────────────────────────────┐ │
+│ │ LAYER 5: Organized Storage │ │
+│ │ Markdown files with YAML frontmatter in categorized dirs │ │
+│ │ learnings/ │ research/ │ decisions/ │ sessions/ │ execution/ │ │
+│ └─────────────────────────────────────────────────────────────────┘ │
+│ │
+└─────────────────────────────────────────────────────────────────────────┘
+```
+
+### The Categorization Logic
+
+**Learning Detection (stop-hook.ts):**
+```
+Contains 2+ of these indicators:
+ problem, solved, discovered, fixed, learned, realized,
+ figured out, root cause, debugging, issue was, turned out,
+ mistake, error, bug, solution
+
+YES → learnings/
+NO → sessions/
+```
+
+**Agent Routing (subagent-stop-hook.ts):**
+```
+Agent Type → Output Directory
+─────────────────────────────────────
+*researcher, intern → research/
+architect → decisions/
+engineer, designer → execution/features/
+```
+
+## What Problems This Solves
+
+| Problem | How History Solves It |
+|---------|----------------------|
+| "What did we work on last week?" | `ls history/sessions/2025-01/` |
+| "Why did we choose that architecture?" | `grep -l "architecture" history/decisions/` |
+| "I fixed this bug before, what was the fix?" | `grep -r "auth" history/learnings/` |
+| "What did that researcher agent find?" | Automatically in `history/research/` |
+| "Can we audit what happened?" | Complete JSONL in `raw-outputs/` |
+
+## Installation
+
+See [INSTALL.md](INSTALL.md) for detailed installation instructions.
+
+## Verification
+
+See [VERIFY.md](VERIFY.md) for testing and verification procedures.
+
+## Configuration
+
+**Environment variables:**
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `PAI_DIR` | `~/.config/pai` | Root PAI directory |
+| `TIME_ZONE` | System default | Timestamp timezone |
+| `DA` | `PAI` | AI assistant name |
+
+## Credits
+
+- **Original concept**: Daniel Miessler - developed as part of Kai personal AI infrastructure
+- **Inspired by**: Git's version history, engineering logbooks, Zettelkasten method
+
+## Related Packs
+
+- **kai-hook-system** - Required foundation; provides the event stream
+- **kai-core-install** - Skills can reference past learnings
+- **kai-voice-system** - Voice notifications for significant captures
+
+## Changelog
+
+### 1.0.0 - 2025-12-28
+- Initial release
+- Four hooks: capture-all-events, stop-hook, subagent-stop-hook, capture-session-summary
+- One lib file: metadata-extraction
+- Automatic categorization by content and agent type
diff --git a/Packs/kai-history-system/VERIFY.md b/Packs/kai-history-system/VERIFY.md
new file mode 100644
index 00000000..42e6a9e8
--- /dev/null
+++ b/Packs/kai-history-system/VERIFY.md
@@ -0,0 +1,138 @@
+# Verification Guide: Kai History System
+
+## Quick Verification
+
+```bash
+# 1. Check all hooks exist
+ls -la $PAI_DIR/hooks/*.ts
+# Should show: capture-all-events.ts, stop-hook.ts,
+# subagent-stop-hook.ts, capture-session-summary.ts
+
+# 2. Check lib files exist
+ls -la $PAI_DIR/hooks/lib/*.ts
+# Should show: metadata-extraction.ts (plus observability.ts from hook-system)
+
+# 3. Check directory structure
+ls -la $PAI_DIR/history/
+# Should show: sessions, learnings, research, decisions, execution, raw-outputs
+
+# 4. Verify Bun can run the hooks
+bun run $PAI_DIR/hooks/capture-all-events.ts --event-type Test <<< '{"test": true}'
+# Should create an entry in raw-outputs
+
+# 5. Check raw-outputs for the test entry
+ls $PAI_DIR/history/raw-outputs/$(date +%Y-%m)/
+# Should show today's events file
+```
+
+---
+
+## Mandatory Completion Checklist
+
+**AI agents MUST verify each item before claiming installation is complete:**
+
+### File Verification
+
+- [ ] `$PAI_DIR/hooks/capture-all-events.ts` exists
+- [ ] `$PAI_DIR/hooks/stop-hook.ts` exists
+- [ ] `$PAI_DIR/hooks/subagent-stop-hook.ts` exists
+- [ ] `$PAI_DIR/hooks/capture-session-summary.ts` exists
+- [ ] `$PAI_DIR/hooks/lib/metadata-extraction.ts` exists
+
+### Directory Verification
+
+- [ ] `$PAI_DIR/history/sessions/` exists
+- [ ] `$PAI_DIR/history/learnings/` exists
+- [ ] `$PAI_DIR/history/research/` exists
+- [ ] `$PAI_DIR/history/decisions/` exists
+- [ ] `$PAI_DIR/history/raw-outputs/` exists
+- [ ] `$PAI_DIR/history/execution/features/` exists
+- [ ] `$PAI_DIR/history/execution/bugs/` exists
+- [ ] `$PAI_DIR/history/execution/refactors/` exists
+
+### Configuration Verification
+
+- [ ] `~/.claude/settings.json` contains `PreToolUse` hook for capture-all-events
+- [ ] `~/.claude/settings.json` contains `PostToolUse` hook for capture-all-events
+- [ ] `~/.claude/settings.json` contains `Stop` hook for stop-hook
+- [ ] `~/.claude/settings.json` contains `SubagentStop` hook for subagent-stop-hook
+- [ ] `~/.claude/settings.json` contains `SessionEnd` hook for capture-session-summary
+
+### Functional Verification
+
+- [ ] capture-all-events.ts runs without errors
+- [ ] JSONL files appear in `raw-outputs/` after events
+- [ ] Stop hook categorizes responses correctly
+- [ ] Session summaries appear after ending sessions
+
+### Code Integrity Check
+
+```bash
+# Check file sizes (should be > 1KB each)
+wc -c $PAI_DIR/hooks/capture-all-events.ts \
+ $PAI_DIR/hooks/stop-hook.ts \
+ $PAI_DIR/hooks/subagent-stop-hook.ts \
+ $PAI_DIR/hooks/capture-session-summary.ts \
+ $PAI_DIR/hooks/lib/metadata-extraction.ts
+
+# Expected approximate sizes:
+# capture-all-events.ts ~3000 bytes
+# stop-hook.ts ~2500 bytes
+# subagent-stop-hook.ts ~4000 bytes
+# capture-session-summary.ts ~3000 bytes
+# metadata-extraction.ts ~2000 bytes
+```
+
+---
+
+## Invocation Scenarios
+
+The history system triggers automatically on Claude Code events:
+
+| Event | Hook | Output Location | Captured Data |
+|-------|------|-----------------|---------------|
+| Any tool starts | PreToolUse | `raw-outputs/` | Tool name, input, session |
+| Any tool completes | PostToolUse | `raw-outputs/` | Tool name, input, output |
+| Main agent finishes | Stop | `learnings/` or `sessions/` | Full response, categorized |
+| Subagent completes | SubagentStop | `research/`, `decisions/`, or `execution/` | Agent output, routed by type |
+| User quits session | SessionEnd | `sessions/` | Files changed, tools used |
+
+---
+
+## Example Searches
+
+```bash
+# Search past work
+grep -r "authentication" $PAI_DIR/history/
+
+# Review recent sessions
+ls -lt $PAI_DIR/history/sessions/2025-12/ | head -5
+
+# Find architectural decisions
+grep -l "architecture" $PAI_DIR/history/decisions/
+
+# Check agent work from today
+ls $PAI_DIR/history/research/2025-12/ | grep AGENT
+```
+
+---
+
+## Troubleshooting
+
+### No files appearing in raw-outputs
+
+1. Check hooks are registered in settings.json
+2. Verify PAI_DIR is set correctly
+3. Restart Claude Code
+
+### Learnings not being categorized
+
+1. Check stop-hook.ts is registered
+2. Verify learning keywords in the hook match your vocabulary
+3. Check file permissions on history directories
+
+### Subagent outputs not captured
+
+1. Verify SubagentStop hook is registered
+2. Check that Task tool is being used for agents
+3. Look for errors in hook stderr output
diff --git a/Packs/kai-history-system/config/settings-hooks.json b/Packs/kai-history-system/config/settings-hooks.json
new file mode 100644
index 00000000..27f0e1f9
--- /dev/null
+++ b/Packs/kai-history-system/config/settings-hooks.json
@@ -0,0 +1,88 @@
+{
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type PreToolUse"
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type PostToolUse"
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/stop-hook.ts"
+ },
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type Stop"
+ }
+ ]
+ }
+ ],
+ "SubagentStop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/subagent-stop-hook.ts"
+ },
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type SubagentStop"
+ }
+ ]
+ }
+ ],
+ "SessionEnd": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-session-summary.ts"
+ },
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type SessionEnd"
+ }
+ ]
+ }
+ ],
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type SessionStart"
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bun run $PAI_DIR/hooks/capture-all-events.ts --event-type UserPromptSubmit"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/Packs/kai-history-system/src/capture-all-events.ts b/Packs/kai-history-system/src/capture-all-events.ts
new file mode 100644
index 00000000..547cc0cd
--- /dev/null
+++ b/Packs/kai-history-system/src/capture-all-events.ts
@@ -0,0 +1,130 @@
+#!/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;
+ 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}`;
+}
+
+function getEventsFilePath(): string {
+ const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ const day = String(now.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] || 'main';
+ }
+ } catch (error) {}
+ return '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 (error) {}
+}
+
+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);
+
+ // Track agent type from Task tool calls
+ 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 = 'main';
+ setAgentForSession(sessionId, 'main');
+ } else if (process.env.CLAUDE_CODE_AGENT) {
+ agentName = process.env.CLAUDE_CODE_AGENT;
+ 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 metadata if spawning subagent
+ if (isAgentSpawningCall(hookData.tool_name, hookData.tool_input)) {
+ event = enrichEventWithAgentMetadata(event, hookData.tool_input, hookData.description);
+ }
+
+ const eventsFile = getEventsFilePath();
+ appendFileSync(eventsFile, JSON.stringify(event) + '\n', 'utf-8');
+
+ } catch (error) {
+ console.error('Event capture error:', error);
+ }
+
+ process.exit(0);
+}
+
+main();
diff --git a/Packs/kai-history-system/src/capture-session-summary.ts b/Packs/kai-history-system/src/capture-session-summary.ts
new file mode 100644
index 00000000..ec3922b7
--- /dev/null
+++ b/Packs/kai-history-system/src/capture-session-summary.ts
@@ -0,0 +1,159 @@
+#!/usr/bin/env bun
+// $PAI_DIR/hooks/capture-session-summary.ts
+// Creates session summary when Claude Code session ends
+
+import { writeFileSync, mkdirSync, existsSync, readFileSync, readdirSync } from 'fs';
+import { join } from 'path';
+import { homedir } from 'os';
+
+interface SessionData {
+ conversation_id: string;
+ timestamp: string;
+ [key: string]: any;
+}
+
+function getLocalTimestamp(): string {
+ const date = new Date();
+ const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;
+ 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}`;
+}
+
+function determineSessionFocus(filesChanged: string[], commandsExecuted: string[]): string {
+ const filePatterns = filesChanged.map(f => f.toLowerCase());
+
+ if (filePatterns.some(f => f.includes('/blog/') || f.includes('/posts/'))) return 'blog-work';
+ if (filePatterns.some(f => f.includes('/hooks/'))) return 'hook-development';
+ if (filePatterns.some(f => f.includes('/skills/'))) return 'skill-updates';
+ if (filePatterns.some(f => f.includes('/agents/'))) return 'agent-work';
+ if (commandsExecuted.some(cmd => cmd.includes('test'))) return 'testing-session';
+ if (commandsExecuted.some(cmd => cmd.includes('git commit'))) return 'git-operations';
+ if (commandsExecuted.some(cmd => cmd.includes('deploy'))) return 'deployment';
+
+ if (filesChanged.length > 0) {
+ const mainFile = filesChanged[0].split('/').pop()?.replace(/\.(md|ts|js)$/, '');
+ if (mainFile) return `${mainFile}-work`;
+ }
+
+ return 'development-session';
+}
+
+async function analyzeSession(conversationId: string, yearMonth: string): Promise<any> {
+ const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');
+ const rawOutputsDir = join(paiDir, 'history', 'raw-outputs', yearMonth);
+
+ let filesChanged: string[] = [];
+ let commandsExecuted: string[] = [];
+ let toolsUsed: Set<string> = new Set();
+
+ try {
+ if (existsSync(rawOutputsDir)) {
+ const files = readdirSync(rawOutputsDir).filter(f => f.endsWith('.jsonl'));
+
+ for (const file of files) {
+ const content = readFileSync(join(rawOutputsDir, file), 'utf-8');
+ const lines = content.split('\n').filter(l => l.trim());
+
+ for (const line of lines) {
+ try {
+ const entry = JSON.parse(line);
+ if (entry.payload?.tool_name) {
+ toolsUsed.add(entry.payload.tool_name);
+ }
+ if (entry.payload?.tool_name === 'Edit' || entry.payload?.tool_name === 'Write') {
+ if (entry.payload?.tool_input?.file_path) {
+ filesChanged.push(entry.payload.tool_input.file_path);
+ }
+ }
+ if (entry.payload?.tool_name === 'Bash' && entry.payload?.tool_input?.command) {
+ commandsExecuted.push(entry.payload.tool_input.command);
+ }
+ } catch (e) {}
+ }
+ }
+ }
+ } catch (error) {}
+
+ return {
+ focus: determineSessionFocus([...new Set(filesChanged)], commandsExecuted),
+ filesChanged: [...new Set(filesChanged)].slice(0, 10),
+ commandsExecuted: commandsExecuted.slice(0, 10),
+ toolsUsed: Array.from(toolsUsed)
+ };
+}
+
+async function main() {
+ try {
+ const input = await Bun.stdin.text();
+ if (!input.trim()) process.exit(0);
+
+ const data: SessionData = JSON.parse(input);
+ const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');
+ const historyDir = join(paiDir, 'history');
+
+ const now = new Date();
+ const timestamp = now.toISOString().replace(/[-:]/g, '').split('.')[0];
+ const yearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
+
+ const sessionInfo = await analyzeSession(data.conversation_id, yearMonth);
+ const filename = `${timestamp}_SESSION_${sessionInfo.focus}.md`;
+
+ const sessionDir = join(historyDir, 'sessions', yearMonth);
+ if (!existsSync(sessionDir)) {
+ mkdirSync(sessionDir, { recursive: true });
+ }
+
+ const sessionDoc = `---
+capture_type: SESSION
+timestamp: ${getLocalTimestamp()}
+session_id: ${data.conversation_id}
+executor: main
+---
+
+# Session: ${sessionInfo.focus}
+
+**Session ID:** ${data.conversation_id}
+**Ended:** ${getLocalTimestamp()}
+
+---
+
+## Tools Used
+
+${sessionInfo.toolsUsed.length > 0 ? sessionInfo.toolsUsed.map((t: string) => `- ${t}`).join('\n') : '- None recorded'}
+
+---
+
+## Files Modified
+
+${sessionInfo.filesChanged.length > 0 ? sessionInfo.filesChanged.map((f: string) => `- \`${f}\``).join('\n') : '- None recorded'}
+
+---
+
+## Commands Executed
+
+${sessionInfo.commandsExecuted.length > 0 ? '```bash\n' + sessionInfo.commandsExecuted.join('\n') + '\n```' : 'None recorded'}
+
+---
+
+*Session summary captured by PAI History System*
+`;
+
+ writeFileSync(join(sessionDir, filename), sessionDoc);
+ console.log(`📝 Session summary saved to sessions/${yearMonth}/${filename}`);
+
+ } catch (error) {
+ console.error('Session summary error:', error);
+ }
+
+ process.exit(0);
+}
+
+main();
diff --git a/Packs/kai-history-system/src/lib/metadata-extraction.ts b/Packs/kai-history-system/src/lib/metadata-extraction.ts
new file mode 100644
index 00000000..ab5aa940
--- /dev/null
+++ b/Packs/kai-history-system/src/lib/metadata-extraction.ts
@@ -0,0 +1,75 @@
+// $PAI_DIR/hooks/lib/metadata-extraction.ts
+// Extract 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: 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;
+
+ 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;
+}
diff --git a/Packs/kai-history-system/src/stop-hook.ts b/Packs/kai-history-system/src/stop-hook.ts
new file mode 100644
index 00000000..677c5082
--- /dev/null
+++ b/Packs/kai-history-system/src/stop-hook.ts
@@ -0,0 +1,128 @@
+#!/usr/bin/env bun
+// $PAI_DIR/hooks/stop-hook.ts
+// Captures main agent work summaries and learnings
+
+import { writeFileSync, mkdirSync, existsSync } from 'fs';
+import { join } from 'path';
+import { homedir } from 'os';
+
+interface StopPayload {
+ stop_hook_active: boolean;
+ transcript_path?: string;
+ response?: string;
+ session_id?: string;
+}
+
+function getLocalTimestamp(): string {
+ const date = new Date();
+ const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;
+ 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}`;
+}
+
+function hasLearningIndicators(text: string): boolean {
+ const indicators = [
+ 'problem', 'solved', 'discovered', 'fixed', 'learned', 'realized',
+ 'figured out', 'root cause', 'debugging', 'issue was', 'turned out',
+ 'mistake', 'error', 'bug', 'solution'
+ ];
+ const lowerText = text.toLowerCase();
+ const matches = indicators.filter(i => lowerText.includes(i));
+ return matches.length >= 2;
+}
+
+function extractSummary(response: string): string {
+ // Look for COMPLETED section
+ const completedMatch = response.match(/🎯\s*COMPLETED[:\s]*(.+?)(?:\n|$)/i);
+ if (completedMatch) {
+ return completedMatch[1].trim().slice(0, 100);
+ }
+
+ // Look for SUMMARY section
+ const summaryMatch = response.match(/📋\s*SUMMARY[:\s]*(.+?)(?:\n|$)/i);
+ if (summaryMatch) {
+ return summaryMatch[1].trim().slice(0, 100);
+ }
+
+ // Fallback: first meaningful line
+ const lines = response.split('\n').filter(l => l.trim().length > 10);
+ if (lines.length > 0) {
+ return lines[0].trim().slice(0, 100);
+ }
+
+ return 'work-session';
+}
+
+function generateFilename(type: string, description: string): string {
+ const now = new Date();
+ const timestamp = now.toISOString().replace(/[-:]/g, '').split('.')[0];
+ const kebab = description.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60);
+ return `${timestamp}_${type}_${kebab}.md`;
+}
+
+async function main() {
+ try {
+ const stdinData = await Bun.stdin.text();
+ if (!stdinData.trim()) {
+ process.exit(0);
+ }
+
+ const payload: StopPayload = JSON.parse(stdinData);
+ if (!payload.response) {
+ process.exit(0);
+ }
+
+ const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');
+ const historyDir = join(paiDir, 'history');
+
+ const isLearning = hasLearningIndicators(payload.response);
+ const type = isLearning ? 'LEARNING' : 'SESSION';
+ const subdir = isLearning ? 'learnings' : 'sessions';
+
+ const now = new Date();
+ const yearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
+ const outputDir = join(historyDir, subdir, yearMonth);
+
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+
+ const summary = extractSummary(payload.response);
+ const filename = generateFilename(type, summary);
+ const filepath = join(outputDir, filename);
+
+ const content = `---
+capture_type: ${type}
+timestamp: ${getLocalTimestamp()}
+session_id: ${payload.session_id || 'unknown'}
+executor: main
+---
+
+# ${type}: ${summary}
+
+${payload.response}
+
+---
+
+*Captured by PAI History System stop-hook*
+`;
+
+ writeFileSync(filepath, content);
+ console.log(`📝 Captured ${type} to ${subdir}/${yearMonth}/${filename}`);
+
+ } catch (error) {
+ console.error('Stop hook error:', error);
+ }
+
+ process.exit(0);
+}
+
+main();
diff --git a/Packs/kai-history-system/src/subagent-stop-hook.ts b/Packs/kai-history-system/src/subagent-stop-hook.ts
new file mode 100644
index 00000000..d8be7d13
--- /dev/null
+++ b/Packs/kai-history-system/src/subagent-stop-hook.ts
@@ -0,0 +1,233 @@
+#!/usr/bin/env bun
+// $PAI_DIR/hooks/subagent-stop-hook.ts
+// Routes subagent outputs to appropriate history directories
+
+import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from 'fs';
+import { join, dirname } from 'path';
+import { homedir } from 'os';
+import { extractAgentInstanceId } from './lib/metadata-extraction';
+
+function getLocalTimestamp(): string {
+ const date = new Date();
+ const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;
+ 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}`;
+}
+
+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, toolInput: any | 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;
+ }
+
+ let agentType = toolInput?.subagent_type || 'default';
+ return { result: taskOutput, agentType, description, toolInput };
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ } catch (e) {}
+ }
+ } catch (e) {}
+ }
+
+ return { result: null, agentType: null, description: null, toolInput: null };
+}
+
+function extractCompletionMessage(taskOutput: string): { message: string | null, agentType: string | null } {
+ // Look for COMPLETED section
+ const patterns = [
+ /🎯\s*COMPLETED[:\s]*\[AGENT:(\w+[-\w]*)\]\s*(.+?)(?:\n|$)/is,
+ /🎯\s*COMPLETED[:\s]*(.+?)(?:\n|$)/i,
+ /COMPLETED[:\s]*(.+?)(?:\n|$)/i
+ ];
+
+ for (const pattern of patterns) {
+ const match = taskOutput.match(pattern);
+ if (match) {
+ if (match[2]) {
+ return { message: match[2].trim(), agentType: match[1].toLowerCase() };
+ }
+ return { message: match[1].trim(), agentType: null };
+ }
+ }
+
+ return { message: null, agentType: null };
+}
+
+async function captureAgentOutput(
+ agentType: string,
+ completionMessage: string,
+ taskOutput: string,
+ transcriptPath: string
+) {
+ const paiDir = process.env.PAI_DIR || join(homedir(), '.config', 'pai');
+ const historyDir = join(paiDir, 'history');
+
+ const now = new Date();
+ const timestamp = now.toISOString().replace(/[-:]/g, '').split('.')[0];
+ const yearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
+
+ // Route by agent type
+ let captureType = 'RESEARCH';
+ let category = 'research';
+
+ if (agentType.includes('researcher') || agentType === 'intern') {
+ captureType = 'RESEARCH';
+ category = 'research';
+ } else if (agentType === 'architect') {
+ captureType = 'DECISION';
+ category = 'decisions';
+ } else if (agentType === 'engineer' || agentType === 'designer') {
+ captureType = 'FEATURE';
+ category = 'execution/features';
+ }
+
+ const description = completionMessage
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 60);
+
+ const filename = `${timestamp}_AGENT-${agentType}_${captureType}_${description}.md`;
+ const outputDir = join(historyDir, category, yearMonth);
+
+ if (!existsSync(outputDir)) {
+ mkdirSync(outputDir, { recursive: true });
+ }
+
+ const document = `---
+capture_type: ${captureType}
+timestamp: ${getLocalTimestamp()}
+executor: ${agentType}
+agent_completion: ${completionMessage}
+---
+
+# ${captureType}: ${completionMessage}
+
+**Agent:** ${agentType}
+**Completed:** ${timestamp}
+
+---
+
+## Agent Output
+
+${taskOutput}
+
+---
+
+## Metadata
+
+**Transcript:** \`${transcriptPath}\`
+**Captured:** ${getLocalTimestamp()}
+
+---
+
+*Captured by PAI History System subagent-stop-hook*
+`;
+
+ writeFileSync(join(outputDir, filename), document);
+ console.log(`📝 Captured ${agentType} output to ${category}/${yearMonth}/${filename}`);
+}
+
+async function main() {
+ try {
+ let input = '';
+ 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]);
+
+ if (!input) process.exit(0);
+
+ const parsed = JSON.parse(input);
+ const transcriptPath = parsed.transcript_path;
+ if (!transcriptPath) process.exit(0);
+
+ const { result: taskOutput, agentType, description, toolInput } = await findTaskResult(transcriptPath);
+ if (!taskOutput) process.exit(0);
+
+ const { message: completionMessage, agentType: extractedAgentType } = extractCompletionMessage(taskOutput);
+ if (!completionMessage) process.exit(0);
+
+ const finalAgentType = extractedAgentType || agentType || 'default';
+
+ await captureAgentOutput(finalAgentType, completionMessage, taskOutput, transcriptPath);
+
+ } catch (error) {
+ console.error('Subagent stop hook error:', error);
+ }
+
+ process.exit(0);
+}
+
+main();
diff --git a/Packs/kai-hook-system/INSTALL.md b/Packs/kai-hook-system/INSTALL.md
new file mode 100644
index 00000000..a3f94a7f
--- /dev/null
+++ b/Packs/kai-hook-system/INSTALL.md
@@ -0,0 +1,289 @@
+# Installation Guide: Kai Hook System
+
+## 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.
+
+Please follow the installation instructions below to integrate this Pack into your infrastructure.
+
+---
+
+## 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"
+```
+
+---
+
+## Step 1: Create Directory Structure
+
+```bash
+# Create required directories
+mkdir -p $PAI_DIR/hooks/lib
+
+# Verify structure
+ls -la $PAI_DIR/hooks/
+```
+
+---
+
+## Step 2: Install Source Files
+
+Copy all TypeScript files from this pack's `src/` directory to your hooks directory:
+
+```bash
+# Copy hook files
+cp src/security-validator.ts $PAI_DIR/hooks/
+cp src/initialize-session.ts $PAI_DIR/hooks/
+cp src/load-core-context.ts $PAI_DIR/hooks/
+cp src/update-tab-titles.ts $PAI_DIR/hooks/
+
+# Copy library files
+cp src/lib/observability.ts $PAI_DIR/hooks/lib/
+
+# Verify all files are in place
+ls -la $PAI_DIR/hooks/*.ts
+ls -la $PAI_DIR/hooks/lib/*.ts
+```
+
+---
+
+## Step 3: Register Hooks in settings.json
+
+Claude Code looks for settings in `~/.claude/settings.json`. The hook configuration template is in `config/settings-hooks.json`.
+
+**For new installations:**
+
+```bash
+# If no settings.json exists, copy the template
+cp config/settings-hooks.json ~/.claude/settings.json
+```
+
+**For existing installations:**
+
+Merge the hooks section from `config/settings-hooks.json` into your existing `~/.claude/settings.json`. The hooks section should look like:
+
+```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"
+ }
+ ]
+ }
+ ]
+ }
+}
+```
+
+---
+
+## Step 4: Restart Claude Code
+
+Hooks are only loaded when Claude Code starts. Restart Claude Code to activate the new hooks.
+
+---
+
+## Installation Verification
+
+After completing installation, run the verification steps in [VERIFY.md](VERIFY.md).
+
+---
+
+## Troubleshooting
+
+### Hooks not firing
+
+1. Check that hooks are registered in `~/.claude/settings.json`
+2. Verify file paths use `$PAI_DIR` correctly
+3. Restart Claude Code after changes
+
+### Security validator blocking valid commands
+
+1. Review the attack patterns in `security-validator.ts`
+2. Adjust patterns or action levels as needed
+3. Add exceptions for your specific workflow
+
+### Tab titles not updating
+
+1. Check that your terminal supports OSC escape sequences
+2. Verify the UserPromptSubmit hook is registered
+3. Check for errors in the hook output
+
+---
+
+## Anti-Simplification Directive
+
+**CRITICAL FOR AI AGENTS:**
+
+This installation MUST be completed EXACTLY as specified. DO NOT:
+- Skip any files
+- Summarize or simplify code
+- Modify file paths
+- Skip verification steps
+
+After installation, you MUST complete the verification checklist in [VERIFY.md](VERIFY.md).
diff --git a/Packs/kai-hook-system/README.md b/Packs/kai-hook-system/README.md
new file mode 100644
index 00000000..0b71bc4d
--- /dev/null
+++ b/Packs/kai-hook-system/README.md
@@ -0,0 +1,269 @@
+---
+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
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| Security validator | `src/security-validator.ts` | Block dangerous commands before execution |
+| Session initializer | `src/initialize-session.ts` | Set up session context and markers |
+| Context loader | `src/load-core-context.ts` | Load CORE skill at session start |
+| Tab title updater | `src/update-tab-titles.ts` | Update terminal tabs with task context |
+| Observability lib | `src/lib/observability.ts` | Event logging and dashboard integration |
+| Hook config | `config/settings-hooks.json` | Claude Code hook registration template |
+
+**Summary:**
+- **Files created:** 6
+- **Hooks registered:** 4 (PreToolUse, SessionStart ×2, UserPromptSubmit)
+- **Dependencies:** None (foundation pack)
+
+## The 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
+
+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 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
+
+## Architecture Deep Dive
+
+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.
+
+## Installation
+
+See [INSTALL.md](INSTALL.md) for detailed installation instructions.
+
+## Verification
+
+See [VERIFY.md](VERIFY.md) for testing and verification procedures.
+
+## 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 |
+
+## Credits
+
+- **Original concept**: Daniel Miessler - developed as part of Kai personal AI infrastructure
+- **Contributors**: The PAI community
+- **Hook system**: Anthropic Claude Code team
+
+## Related Packs
+
+- **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
+
+## 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
diff --git a/Packs/kai-hook-system/VERIFY.md b/Packs/kai-hook-system/VERIFY.md
new file mode 100644
index 00000000..923245ea
--- /dev/null
+++ b/Packs/kai-hook-system/VERIFY.md
@@ -0,0 +1,227 @@
+# Verification Guide: Kai Hook System
+
+## Quick Verification
+
+Run these commands to verify the 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
+
+# 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. Verify settings.json has hooks configured
+grep -l "hooks" ~/.claude/settings.json
+# Should show the file path
+```
+
+## Canary File Test (Optional)
+
+A more intuitive way to test the security validator:
+
+```bash
+# Create a canary file
+touch /tmp/pai-security-canary
+
+# Now ask Claude: "delete /tmp/pai-security-canary"
+# Hook should BLOCK
+
+# Verify canary survives:
+ls /tmp/pai-security-canary # File should still exist
+
+# Clean up
+rm /tmp/pai-security-canary
+```
+
+## 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`
+- [ ] All 5 TypeScript files exist in correct locations
+
+---
+
+## Mandatory Completion Checklist
+
+**AI agents MUST verify each item before claiming installation is complete:**
+
+### File Verification
+
+- [ ] `$PAI_DIR/hooks/security-validator.ts` exists and is executable
+- [ ] `$PAI_DIR/hooks/initialize-session.ts` exists and is executable
+- [ ] `$PAI_DIR/hooks/load-core-context.ts` exists and is executable
+- [ ] `$PAI_DIR/hooks/update-tab-titles.ts` exists and is executable
+- [ ] `$PAI_DIR/hooks/lib/observability.ts` exists
+
+### Configuration Verification
+
+- [ ] `~/.claude/settings.json` exists
+- [ ] `settings.json` contains `SessionStart` hooks configuration
+- [ ] `settings.json` contains `PreToolUse` hooks configuration
+- [ ] `settings.json` contains `UserPromptSubmit` hooks configuration
+
+### Functional Verification
+
+- [ ] Security validator allows `ls -la` (exit code 0)
+- [ ] Security validator blocks `rm -rf /` patterns (exit code 2)
+- [ ] Session initialization runs without errors
+- [ ] Tab title hook runs without errors
+
+### Code Integrity Check
+
+Run these commands to verify files are complete (not truncated):
+
+```bash
+# Check file sizes (should be > 1KB each)
+wc -c $PAI_DIR/hooks/*.ts $PAI_DIR/hooks/lib/*.ts
+
+# Expected approximate sizes:
+# security-validator.ts ~5000 bytes
+# initialize-session.ts ~3000 bytes
+# load-core-context.ts ~2000 bytes
+# update-tab-titles.ts ~2500 bytes
+# lib/observability.ts ~1500 bytes
+```
+
+---
+
+## Hook Event Reference
+
+For testing and debugging, here are the event payload formats:
+
+### 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"
+}
+```
+
+### SessionStart
+
+```json
+{
+ "session_id": "uuid",
+ "cwd": "/current/working/directory"
+}
+```
+
+### 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
+
+```json
+{
+ "matcher": "Bash", // Only Bash tool
+ "matcher": "Edit", // Only Edit tool
+ "matcher": "Read|Write", // Read OR Write
+ "matcher": "*" // All tools
+}
+```
+
+---
+
+## Troubleshooting Verification Failures
+
+### Hook file not found
+
+```bash
+# Check PAI_DIR is set correctly
+echo $PAI_DIR
+
+# If not set, export it
+export PAI_DIR="$HOME/.config/pai"
+```
+
+### Security validator exits with wrong code
+
+```bash
+# Debug with verbose output
+echo '{"session_id":"test","tool_name":"Bash","tool_input":{"command":"rm -rf /"}}' | \
+ bun run $PAI_DIR/hooks/security-validator.ts
+echo "Exit code: $?"
+```
+
+### Settings.json not recognized
+
+```bash
+# Validate JSON syntax
+cat ~/.claude/settings.json | jq .
+
+# If jq not installed
+python3 -m json.tool ~/.claude/settings.json
+```
+
+---
+
+## Post-Verification
+
+After all verification passes:
+
+1. Restart Claude Code to activate hooks
+2. Test with a real session
+3. Verify tab titles update
+4. Try a blocked command to confirm security validation
diff --git a/Packs/kai-hook-system/config/settings-hooks.json b/Packs/kai-hook-system/config/settings-hooks.json
new file mode 100644
index 00000000..dd9d0901
--- /dev/null
+++ b/Packs/kai-hook-system/config/settings-hooks.json
@@ -0,0 +1,41 @@
+{
+ "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"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/Packs/kai-hook-system/src/initialize-session.ts b/Packs/kai-hook-system/src/initialize-session.ts
new file mode 100644
index 00000000..14d4f444
--- /dev/null
+++ b/Packs/kai-hook-system/src/initialize-session.ts
@@ -0,0 +1,146 @@
+#!/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();
diff --git a/Packs/kai-hook-system/src/lib/observability.ts b/Packs/kai-hook-system/src/lib/observability.ts
new file mode 100644
index 00000000..2683be6f
--- /dev/null
+++ b/Packs/kai-hook-system/src/lib/observability.ts
@@ -0,0 +1,58 @@
+// $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';
+}
diff --git a/Packs/kai-hook-system/src/load-core-context.ts b/Packs/kai-hook-system/src/load-core-context.ts
new file mode 100644
index 00000000..e53cc02f
--- /dev/null
+++ b/Packs/kai-hook-system/src/load-core-context.ts
@@ -0,0 +1,95 @@
+#!/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();
diff --git a/Packs/kai-hook-system/src/security-validator.ts b/Packs/kai-hook-system/src/security-validator.ts
new file mode 100644
index 00000000..c7e511ba
--- /dev/null
+++ b/Packs/kai-hook-system/src/security-validator.ts
@@ -0,0 +1,228 @@
+#!/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();
diff --git a/Packs/kai-hook-system/src/update-tab-titles.ts b/Packs/kai-hook-system/src/update-tab-titles.ts
new file mode 100644
index 00000000..4867ff6b
--- /dev/null
+++ b/Packs/kai-hook-system/src/update-tab-titles.ts
@@ -0,0 +1,98 @@
+#!/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();
diff --git a/Packs/kai-observability-server/INSTALL.md b/Packs/kai-observability-server/INSTALL.md
new file mode 100644
index 00000000..303d0da8
--- /dev/null
+++ b/Packs/kai-observability-server/INSTALL.md
@@ -0,0 +1,205 @@
+# Kai Observability Server - Installation Guide
+
+## 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 Checks
+
+### 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
+```
+
+### Check for Existing Observability
+
+```bash
+if [ -d "$PAI_DIR/observability" ]; then
+ echo "Warning: Observability directory EXISTS"
+ ls -la "$PAI_DIR/observability"
+else
+ echo "Clean install - no existing observability"
+fi
+```
+
+## Installation Steps
+
+### 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
+```
+
+### Step 2: Copy Source Files
+
+Copy the following files from `src/` to their destinations:
+
+| Source | Destination |
+|--------|-------------|
+| `src/hooks/lib/metadata-extraction.ts` | `$PAI_DIR/hooks/lib/metadata-extraction.ts` |
+| `src/hooks/capture-all-events.ts` | `$PAI_DIR/hooks/capture-all-events.ts` |
+| `src/observability/apps/server/src/types.ts` | `$PAI_DIR/observability/apps/server/src/types.ts` |
+| `src/observability/apps/server/src/file-ingest.ts` | `$PAI_DIR/observability/apps/server/src/file-ingest.ts` |
+| `src/observability/apps/server/src/index.ts` | `$PAI_DIR/observability/apps/server/src/index.ts` |
+| `src/observability/apps/server/package.json` | `$PAI_DIR/observability/apps/server/package.json` |
+| `src/observability/apps/client/src/main.ts` | `$PAI_DIR/observability/apps/client/src/main.ts` |
+| `src/observability/apps/client/src/style.css` | `$PAI_DIR/observability/apps/client/src/style.css` |
+| `src/observability/apps/client/src/App.vue` | `$PAI_DIR/observability/apps/client/src/App.vue` |
+| `src/observability/apps/client/package.json` | `$PAI_DIR/observability/apps/client/package.json` |
+| `src/observability/apps/client/vite.config.ts` | `$PAI_DIR/observability/apps/client/vite.config.ts` |
+| `src/observability/apps/client/index.html` | `$PAI_DIR/observability/apps/client/index.html` |
+| `src/observability/apps/client/tailwind.config.js` | `$PAI_DIR/observability/apps/client/tailwind.config.js` |
+| `src/observability/apps/client/postcss.config.js` | `$PAI_DIR/observability/apps/client/postcss.config.js` |
+| `src/observability/manage.sh` | `$PAI_DIR/observability/manage.sh` |
+
+### Step 3: Make Management Script Executable
+
+```bash
+chmod +x $PAI_DIR/observability/manage.sh
+```
+
+### Step 4: Register Capture Hooks
+
+Add the following to your `~/.claude/settings.json` 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 5: 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 6: Verify Installation
+
+```bash
+# Start observability
+$PAI_DIR/observability/manage.sh start
+
+# In another terminal, check health
+curl http://localhost:4000/health
+# Expected: {"status":"ok","timestamp":...}
+
+# Open browser to http://localhost:5172
+# Should see the observability dashboard
+
+# Stop when done testing
+$PAI_DIR/observability/manage.sh stop
+```
+
+## Post-Installation
+
+After installation:
+1. Start observability: `$PAI_DIR/observability/manage.sh start`
+2. Open http://localhost:5172
+3. Use Claude Code - events should stream to dashboard
+4. Use `/observability status` to check status from Claude Code
+
+## Troubleshooting
+
+### Port Already in Use
+
+```bash
+# Check what's using the port
+lsof -i :4000
+lsof -i :5172
+
+# Kill the processes if needed
+$PAI_DIR/observability/manage.sh stop
+```
+
+### No Events Appearing
+
+1. Check hooks are registered: `grep -A5 'capture-all-events' ~/.claude/settings.json`
+2. Check the JSONL file is being written: `ls -la $PAI_DIR/history/raw-outputs/*/`
+3. Check server is watching the right file: Server logs show "Watching: ..."
+
+### WebSocket Not Connecting
+
+1. Ensure server is running on port 4000
+2. Check browser console for errors
+3. Try `curl http://localhost:4000/health`
diff --git a/Packs/kai-observability-server/README.md b/Packs/kai-observability-server/README.md
new file mode 100644
index 00000000..6b8a3a64
--- /dev/null
+++ b/Packs/kai-observability-server/README.md
@@ -0,0 +1,189 @@
+---
+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
+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]
+---
+
+# Kai Observability Server
+
+> Real-time multi-agent activity monitoring dashboard - see exactly what your AI agents are doing as they work
+
+## What This Pack Does
+
+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
+
+## 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 │ │
+│ └──────────────────────────────────────────────────────────────────┘ │
+│ │
+└──────────────────────────────────────────────────────────────────────────┘
+```
+
+## 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.
+
+## 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
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| WebSocket server | `observability/apps/server/src/index.ts` | HTTP API + WebSocket streaming |
+| File ingestion | `observability/apps/server/src/file-ingest.ts` | Watch JSONL and stream events |
+| Type definitions | `observability/apps/server/src/types.ts` | TypeScript interfaces |
+| Vue dashboard | `observability/apps/client/src/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 |
+| Management script | `observability/manage.sh` | Start/stop/restart control |
+
+## 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 |
+
+## Dependencies
+
+- **kai-hook-system** (required) - Provides the hook infrastructure
+- **Bun runtime** - For TypeScript execution
+- **Node.js 18+** - For Vite dev server
+
+## Usage
+
+```bash
+# Start observability
+$PAI_DIR/observability/manage.sh start
+
+# Check status
+$PAI_DIR/observability/manage.sh status
+
+# Stop
+$PAI_DIR/observability/manage.sh stop
+
+# Restart
+$PAI_DIR/observability/manage.sh restart
+
+# Start detached (background)
+$PAI_DIR/observability/manage.sh start-detached
+```
+
+Open http://localhost:5172 to view the dashboard.
+
+## Related Packs
+
+- **kai-hook-system** - Required dependency
+- **kai-history-system** - Permanent storage of events
+
+## Changelog
+
+### 1.0.0 - Initial Release
+- File-based event streaming architecture
+- Bun HTTP + WebSocket server
+- Vue 3 dashboard
+- Multi-agent tracking with session mapping
+- Management script for start/stop/restart
diff --git a/Packs/kai-observability-server/VERIFY.md b/Packs/kai-observability-server/VERIFY.md
new file mode 100644
index 00000000..692b4b30
--- /dev/null
+++ b/Packs/kai-observability-server/VERIFY.md
@@ -0,0 +1,235 @@
+# Kai Observability Server - Verification Checklist
+
+## Mandatory Completion Checklist
+
+**IMPORTANT:** All items must be verified before considering this pack installed.
+
+### Directory Structure
+
+- [ ] `$PAI_DIR/observability/` directory exists
+- [ ] `$PAI_DIR/observability/apps/server/src/` directory exists
+- [ ] `$PAI_DIR/observability/apps/client/src/` directory exists
+- [ ] `$PAI_DIR/hooks/lib/` directory exists
+- [ ] `$PAI_DIR/history/raw-outputs/` directory exists
+
+### Core Files
+
+- [ ] `$PAI_DIR/hooks/lib/metadata-extraction.ts` exists
+- [ ] `$PAI_DIR/hooks/capture-all-events.ts` exists
+- [ ] `$PAI_DIR/observability/apps/server/src/index.ts` exists
+- [ ] `$PAI_DIR/observability/apps/server/src/file-ingest.ts` exists
+- [ ] `$PAI_DIR/observability/apps/server/src/types.ts` exists
+- [ ] `$PAI_DIR/observability/apps/server/package.json` exists
+- [ ] `$PAI_DIR/observability/apps/client/src/App.vue` exists
+- [ ] `$PAI_DIR/observability/apps/client/package.json` exists
+- [ ] `$PAI_DIR/observability/manage.sh` exists and is executable
+
+### Dependencies
+
+- [ ] Server dependencies installed (`$PAI_DIR/observability/apps/server/node_modules/` exists)
+- [ ] Client dependencies installed (`$PAI_DIR/observability/apps/client/node_modules/` exists)
+
+### Hook Registration
+
+- [ ] Capture hooks registered in `~/.claude/settings.json`
+
+---
+
+## Functional Tests
+
+### Test 1: Verify Directory Structure
+
+```bash
+ls -la $PAI_DIR/observability/
+# Expected: manage.sh, apps/
+
+ls -la $PAI_DIR/observability/apps/server/src/
+# Expected: index.ts, file-ingest.ts, types.ts
+
+ls -la $PAI_DIR/observability/apps/client/src/
+# Expected: App.vue, main.ts, style.css
+```
+
+### Test 2: Start Server
+
+```bash
+$PAI_DIR/observability/manage.sh start
+# Expected: "Observability running at http://localhost:5172"
+```
+
+### Test 3: Health Check
+
+```bash
+curl http://localhost:4000/health
+# Expected: {"status":"ok","timestamp":...}
+```
+
+### Test 4: WebSocket Connection
+
+```bash
+# In browser developer tools console at http://localhost:5172:
+# Should show "Connected to observability server" in console
+```
+
+### Test 5: Event Capture
+
+```bash
+# Use Claude Code to run a command
+# Check if events file was created
+ls -la $PAI_DIR/history/raw-outputs/$(date +%Y-%m)/
+# Expected: YYYY-MM-DD_all-events.jsonl
+```
+
+### Test 6: Stop Server
+
+```bash
+$PAI_DIR/observability/manage.sh stop
+# Expected: "Observability stopped"
+
+curl http://localhost:4000/health
+# Expected: Connection refused
+```
+
+### Test 7: Check Hook Registration
+
+```bash
+grep -A 2 "capture-all-events" ~/.claude/settings.json
+# Expected: Shows hook configuration
+```
+
+---
+
+## Integration Tests
+
+### Test A: Real-Time Event Streaming
+
+1. Start observability: `$PAI_DIR/observability/manage.sh start`
+2. Open http://localhost:5172 in browser
+3. In Claude Code, run a Bash command
+4. Watch dashboard - event should appear within 1 second
+5. Verify event shows tool name and command
+
+### Test B: Multi-Agent Tracking
+
+1. With observability running
+2. In Claude Code, spawn a subagent with Task tool
+3. Watch dashboard - should show agent name change
+4. Subagent events should be labeled with agent type
+
+### Test C: Graceful Degradation
+
+```bash
+# Stop the server
+$PAI_DIR/observability/manage.sh stop
+
+# In Claude Code, run some commands
+# Should complete without errors (hooks just write to file)
+
+# Start server again
+$PAI_DIR/observability/manage.sh start
+
+# Dashboard should load (won't show old events, starts fresh)
+```
+
+### Test D: Detached Mode
+
+```bash
+# Start in background
+$PAI_DIR/observability/manage.sh start-detached
+
+# Verify it's running
+$PAI_DIR/observability/manage.sh status
+# Expected: "Running at http://localhost:5172"
+
+# Stop
+$PAI_DIR/observability/manage.sh stop
+```
+
+---
+
+## Quick Verification Script
+
+```bash
+#!/bin/bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "=== Kai Observability Server Verification ==="
+echo ""
+
+# Check directories
+for dir in "observability" "observability/apps/server/src" "observability/apps/client/src" "hooks/lib" "history/raw-outputs"; do
+ if [ -d "$PAI_CHECK/$dir" ]; then
+ echo "✓ $dir/"
+ else
+ echo "❌ $dir/ MISSING"
+ fi
+done
+
+echo ""
+
+# Check files
+for file in "observability/manage.sh" "observability/apps/server/src/index.ts" "observability/apps/client/src/App.vue" "hooks/capture-all-events.ts" "hooks/lib/metadata-extraction.ts"; do
+ if [ -f "$PAI_CHECK/$file" ]; then
+ echo "✓ $file"
+ else
+ echo "❌ $file MISSING"
+ fi
+done
+
+echo ""
+
+# Check executable
+if [ -x "$PAI_CHECK/observability/manage.sh" ]; then
+ echo "✓ manage.sh is executable"
+else
+ echo "❌ manage.sh NOT executable"
+fi
+
+echo ""
+
+# Check node_modules
+if [ -d "$PAI_CHECK/observability/apps/server/node_modules" ]; then
+ echo "✓ Server dependencies installed"
+else
+ echo "❌ Server dependencies NOT installed"
+fi
+
+if [ -d "$PAI_CHECK/observability/apps/client/node_modules" ]; then
+ echo "✓ Client dependencies installed"
+else
+ echo "❌ Client dependencies NOT installed"
+fi
+
+echo ""
+
+# Check if running
+if lsof -Pi :4000 -sTCP:LISTEN -t >/dev/null 2>&1; then
+ echo "✓ Server running on port 4000"
+else
+ echo "❌ Server NOT running"
+fi
+
+if lsof -Pi :5172 -sTCP:LISTEN -t >/dev/null 2>&1; then
+ echo "✓ Client running on port 5172"
+else
+ echo "❌ Client NOT running"
+fi
+
+echo ""
+echo "=== Verification Complete ==="
+```
+
+---
+
+## Success Criteria
+
+Installation is complete when:
+
+1. All directory structure items are checked
+2. All core files are present
+3. Dependencies are installed for both server and client
+4. Hooks are registered in settings.json
+5. Server starts without errors
+6. Health check returns OK
+7. Dashboard loads in browser
+8. Events appear when using Claude Code
diff --git a/Packs/kai-observability-server/config/settings-hooks.json b/Packs/kai-observability-server/config/settings-hooks.json
new file mode 100644
index 00000000..8025ab54
--- /dev/null
+++ b/Packs/kai-observability-server/config/settings-hooks.json
@@ -0,0 +1,65 @@
+{
+ "_description": "Hook registration template for Claude Code settings.json",
+ "_instructions": [
+ "Merge these hook configurations into ~/.claude/settings.json",
+ "The hooks section should be added/merged under the 'hooks' key",
+ "Adjust paths based on your $PAI_DIR location"
+ ],
+ "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"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/Packs/kai-observability-server/src/hooks/capture-all-events.ts b/Packs/kai-observability-server/src/hooks/capture-all-events.ts
new file mode 100644
index 00000000..fa335be9
--- /dev/null
+++ b/Packs/kai-observability-server/src/hooks/capture-all-events.ts
@@ -0,0 +1,148 @@
+#!/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();
diff --git a/Packs/kai-observability-server/src/hooks/lib/metadata-extraction.ts b/Packs/kai-observability-server/src/hooks/lib/metadata-extraction.ts
new file mode 100644
index 00000000..4b95e077
--- /dev/null
+++ b/Packs/kai-observability-server/src/hooks/lib/metadata-extraction.ts
@@ -0,0 +1,91 @@
+#!/usr/bin/env bun
+// $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;
+}
diff --git a/Packs/kai-observability-server/src/observability/apps/client/index.html b/Packs/kai-observability-server/src/observability/apps/client/index.html
new file mode 100644
index 00000000..a67f7fd0
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/index.html
@@ -0,0 +1,13 @@
+<!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>
diff --git a/Packs/kai-observability-server/src/observability/apps/client/package.json b/Packs/kai-observability-server/src/observability/apps/client/package.json
new file mode 100644
index 00000000..c94742ba
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/package.json
@@ -0,0 +1,26 @@
+{
+ "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"
+ }
+}
diff --git a/Packs/kai-observability-server/src/observability/apps/client/postcss.config.js b/Packs/kai-observability-server/src/observability/apps/client/postcss.config.js
new file mode 100644
index 00000000..2e7af2b7
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/postcss.config.js
@@ -0,0 +1,6 @@
+export default {
+ plugins: {
+ tailwindcss: {},
+ autoprefixer: {},
+ },
+}
diff --git a/Packs/kai-observability-server/src/observability/apps/client/src/App.vue b/Packs/kai-observability-server/src/observability/apps/client/src/App.vue
new file mode 100644
index 00000000..dab6335d
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/src/App.vue
@@ -0,0 +1,128 @@
+<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>
diff --git a/Packs/kai-observability-server/src/observability/apps/client/src/main.ts b/Packs/kai-observability-server/src/observability/apps/client/src/main.ts
new file mode 100644
index 00000000..fe5bae39
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/src/main.ts
@@ -0,0 +1,5 @@
+import { createApp } from 'vue'
+import App from './App.vue'
+import './style.css'
+
+createApp(App).mount('#app')
diff --git a/Packs/kai-observability-server/src/observability/apps/client/src/style.css b/Packs/kai-observability-server/src/observability/apps/client/src/style.css
new file mode 100644
index 00000000..cdb82f6a
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/src/style.css
@@ -0,0 +1,20 @@
+@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;
+}
diff --git a/Packs/kai-observability-server/src/observability/apps/client/tailwind.config.js b/Packs/kai-observability-server/src/observability/apps/client/tailwind.config.js
new file mode 100644
index 00000000..bd3eb14e
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/tailwind.config.js
@@ -0,0 +1,11 @@
+/** @type {import('tailwindcss').Config} */
+export default {
+ content: [
+ "./index.html",
+ "./src/**/*.{vue,js,ts,jsx,tsx}",
+ ],
+ theme: {
+ extend: {},
+ },
+ plugins: [],
+}
diff --git a/Packs/kai-observability-server/src/observability/apps/client/vite.config.ts b/Packs/kai-observability-server/src/observability/apps/client/vite.config.ts
new file mode 100644
index 00000000..fa0cc5c7
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/client/vite.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from 'vite'
+import vue from '@vitejs/plugin-vue'
+
+export default defineConfig({
+ plugins: [vue()],
+ server: {
+ port: 5172
+ }
+})
diff --git a/Packs/kai-observability-server/src/observability/apps/server/package.json b/Packs/kai-observability-server/src/observability/apps/server/package.json
new file mode 100644
index 00000000..40126192
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/server/package.json
@@ -0,0 +1,15 @@
+{
+ "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"
+ }
+}
diff --git a/Packs/kai-observability-server/src/observability/apps/server/src/file-ingest.ts b/Packs/kai-observability-server/src/observability/apps/server/src/file-ingest.ts
new file mode 100644
index 00000000..da42a4ea
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/server/src/file-ingest.ts
@@ -0,0 +1,267 @@
+// $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()
+ };
+}
diff --git a/Packs/kai-observability-server/src/observability/apps/server/src/index.ts b/Packs/kai-observability-server/src/observability/apps/server/src/index.ts
new file mode 100644
index 00000000..f9bf717e
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/server/src/index.ts
@@ -0,0 +1,121 @@
+// $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`);
diff --git a/Packs/kai-observability-server/src/observability/apps/server/src/types.ts b/Packs/kai-observability-server/src/observability/apps/server/src/types.ts
new file mode 100644
index 00000000..d8332912
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/apps/server/src/types.ts
@@ -0,0 +1,26 @@
+// $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[];
+}
diff --git a/Packs/kai-observability-server/src/observability/manage.sh b/Packs/kai-observability-server/src/observability/manage.sh
new file mode 100644
index 00000000..aed579eb
--- /dev/null
+++ b/Packs/kai-observability-server/src/observability/manage.sh
@@ -0,0 +1,108 @@
+#!/bin/bash
+# $PAI_DIR/observability/manage.sh
+# Observability Dashboard Manager
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+# Ensure bun is in PATH
+export PATH="$HOME/.bun/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"
+
+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
diff --git a/Packs/kai-prompting-skill/INSTALL.md b/Packs/kai-prompting-skill/INSTALL.md
new file mode 100644
index 00000000..65f4c55a
--- /dev/null
+++ b/Packs/kai-prompting-skill/INSTALL.md
@@ -0,0 +1,104 @@
+# Installation Guide - Kai Prompting Skill
+
+## 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: Copy Files
+
+Copy files from this pack to your PAI installation:
+
+| Source | Destination |
+|--------|-------------|
+| `src/skills/Prompting/SKILL.md` | `$PAI_DIR/skills/Prompting/SKILL.md` |
+| `src/skills/Prompting/Standards.md` | `$PAI_DIR/skills/Prompting/Standards.md` |
+| `src/skills/Prompting/Templates/README.md` | `$PAI_DIR/skills/Prompting/Templates/README.md` |
+| `src/skills/Prompting/Templates/Primitives/Roster.hbs` | `$PAI_DIR/skills/Prompting/Templates/Primitives/Roster.hbs` |
+| `src/skills/Prompting/Templates/Primitives/Voice.hbs` | `$PAI_DIR/skills/Prompting/Templates/Primitives/Voice.hbs` |
+| `src/skills/Prompting/Templates/Primitives/Structure.hbs` | `$PAI_DIR/skills/Prompting/Templates/Primitives/Structure.hbs` |
+| `src/skills/Prompting/Templates/Primitives/Briefing.hbs` | `$PAI_DIR/skills/Prompting/Templates/Primitives/Briefing.hbs` |
+| `src/skills/Prompting/Templates/Primitives/Gate.hbs` | `$PAI_DIR/skills/Prompting/Templates/Primitives/Gate.hbs` |
+| `src/skills/Prompting/Tools/RenderTemplate.ts` | `$PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts` |
+| `src/skills/Prompting/Tools/ValidateTemplate.ts` | `$PAI_DIR/skills/Prompting/Tools/ValidateTemplate.ts` |
+
+## Step 3: Install Dependencies
+
+```bash
+cd $PAI_DIR/skills/Prompting/Tools
+bun init -y
+bun add handlebars yaml
+```
+
+## Step 4: Generate Skill Index (If Using kai-core-install)
+
+```bash
+bun run $PAI_DIR/Tools/GenerateSkillIndex.ts
+```
+
+## Step 5: 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
+```
+
+## Customization
+
+### Create Your Own 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 Extensions
+
+| 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 |
+
+## 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.
diff --git a/Packs/kai-prompting-skill/README.md b/Packs/kai-prompting-skill/README.md
new file mode 100644
index 00000000..8496e865
--- /dev/null
+++ b/Packs/kai-prompting-skill/README.md
@@ -0,0 +1,138 @@
+---
+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]
+---
+
+# Kai Prompting Skill (kai-prompting-skill)
+
+> Prompts that write prompts. Meta-prompting enables dynamic composition where structure is fixed but content is parameterized.
+
+## What This Pack Does
+
+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.
+
+## Architecture
+
+```
+kai-prompting-skill/
+├── README.md # This file
+├── INSTALL.md # Installation instructions
+├── VERIFY.md # Verification checklist
+└── src/
+ └── skills/
+ └── Prompting/
+ ├── SKILL.md # Skill routing and overview
+ ├── Standards.md # Claude 4.x best practices
+ ├── Templates/
+ │ ├── README.md # Template system docs
+ │ └── Primitives/ # Core templates
+ │ ├── Roster.hbs
+ │ ├── Voice.hbs
+ │ ├── Structure.hbs
+ │ ├── Briefing.hbs
+ │ └── Gate.hbs
+ └── 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%** |
+
+## The Problem This Solves
+
+### 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.
+
+## Five Core Primitives
+
+| 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 |
+
+## Quick Start
+
+```bash
+# Render a template
+bun run $PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts \
+ --template Primitives/Briefing.hbs \
+ --data path/to/data.yaml \
+ --output path/to/output.md
+
+# Validate template syntax
+bun run $PAI_DIR/skills/Prompting/Tools/ValidateTemplate.ts \
+ --template Primitives/Briefing.hbs
+```
+
+## 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
+- **Daniel Miessler** - Fabric pattern system (248 reusable prompts)
+- **Academic Community** - "The Prompt Report", "The Prompt Canvas"
diff --git a/Packs/kai-prompting-skill/VERIFY.md b/Packs/kai-prompting-skill/VERIFY.md
new file mode 100644
index 00000000..2cc27142
--- /dev/null
+++ b/Packs/kai-prompting-skill/VERIFY.md
@@ -0,0 +1,158 @@
+# Verification Checklist - Kai Prompting Skill
+
+## Mandatory Checks
+
+All items must pass before installation is complete.
+
+### Directory Structure
+
+```bash
+ls $PAI_DIR/skills/Prompting/
+# Expected: SKILL.md Standards.md Templates/ Tools/
+
+ls $PAI_DIR/skills/Prompting/Templates/Primitives/
+# Expected: Roster.hbs Voice.hbs Structure.hbs Briefing.hbs Gate.hbs
+```
+
+- [ ] `$PAI_DIR/skills/Prompting/` directory exists
+- [ ] `SKILL.md` present
+- [ ] `Standards.md` present
+- [ ] `Templates/` directory exists
+- [ ] `Templates/Primitives/` contains 5 `.hbs` files
+- [ ] `Tools/` directory exists with 2 `.ts` files
+
+### Dependencies
+
+```bash
+cd $PAI_DIR/skills/Prompting/Tools
+cat package.json | grep -E '"handlebars"|"yaml"'
+# Should show both dependencies
+```
+
+- [ ] `handlebars` dependency installed
+- [ ] `yaml` dependency installed
+
+### Template Validation
+
+```bash
+# Validate all templates
+for template in $PAI_DIR/skills/Prompting/Templates/Primitives/*.hbs; do
+ bun run $PAI_DIR/skills/Prompting/Tools/ValidateTemplate.ts --template "$template"
+done
+```
+
+- [ ] All 5 templates pass validation
+
+### Template Rendering
+
+```bash
+# 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
+```
+
+- [ ] RenderTemplate.ts runs without errors
+- [ ] Output shows formatted agent roster
+
+### Gate Template Test
+
+```bash
+echo 'gate:
+ name: "Test Gate"
+ category: "testing"
+ action_on_fail: "STOP"
+ mandatory:
+ - name: "Check 1"
+ description: "First check"
+ recommended:
+ - name: "Optional 1"
+ description: "Optional check"' > /tmp/test-gate.yaml
+
+bun run $PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts \
+ --template $PAI_DIR/skills/Prompting/Templates/Primitives/Gate.hbs \
+ --data /tmp/test-gate.yaml \
+ --preview
+```
+
+- [ ] Gate template renders with MANDATORY and RECOMMENDED sections
+
+### Briefing Template Test
+
+```bash
+echo 'briefing:
+ type: research
+agent:
+ id: "R-1"
+ name: "Research Analyst"
+ personality:
+ perspective: "What does the data show?"
+ traits:
+ - "Evidence-based"
+context:
+ summary: "Testing context handoff"
+task:
+ description: "Analyze this data."
+output_format:
+ type: markdown' > /tmp/test-briefing.yaml
+
+bun run $PAI_DIR/skills/Prompting/Tools/RenderTemplate.ts \
+ --template $PAI_DIR/skills/Prompting/Templates/Primitives/Briefing.hbs \
+ --data /tmp/test-briefing.yaml \
+ --preview
+```
+
+- [ ] Briefing template renders agent identity, context, and task sections
+
+## Verification Summary
+
+| Check | Status |
+|-------|--------|
+| Directory structure | |
+| Dependencies installed | |
+| Templates valid | |
+| Roster renders | |
+| Gate renders | |
+| Briefing renders | |
+
+## 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
+
+## Cleanup Test Files
+
+```bash
+rm /tmp/test-agents.yaml /tmp/test-gate.yaml /tmp/test-briefing.yaml
+```
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/SKILL.md b/Packs/kai-prompting-skill/src/skills/Prompting/SKILL.md
new file mode 100644
index 00000000..6a5c1ffd
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/SKILL.md
@@ -0,0 +1,95 @@
+---
+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
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Standards.md b/Packs/kai-prompting-skill/src/skills/Prompting/Standards.md
new file mode 100644
index 00000000..85f5f5e8
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Standards.md
@@ -0,0 +1,254 @@
+---
+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.**
+
+**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
+
+---
+
+# 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
+[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.
+```
+
+---
+
+# 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)
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Briefing.hbs b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Briefing.hbs
new file mode 100644
index 00000000..79124fbd
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Briefing.hbs
@@ -0,0 +1,79 @@
+{{!--
+ 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.**
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Gate.hbs b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Gate.hbs
new file mode 100644
index 00000000..9c3b0c32
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Gate.hbs
@@ -0,0 +1,48 @@
+{{!--
+ 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}}
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Roster.hbs b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Roster.hbs
new file mode 100644
index 00000000..a7442a97
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Roster.hbs
@@ -0,0 +1,50 @@
+{{!--
+ 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}}
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Structure.hbs b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Structure.hbs
new file mode 100644
index 00000000..2061ba73
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Structure.hbs
@@ -0,0 +1,52 @@
+{{!--
+ 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}}
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Voice.hbs b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Voice.hbs
new file mode 100644
index 00000000..78c704f2
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/Primitives/Voice.hbs
@@ -0,0 +1,35 @@
+{{!--
+ 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}}
+ }
+}
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Templates/README.md b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/README.md
new file mode 100644
index 00000000..1d83b465
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Templates/README.md
@@ -0,0 +1,63 @@
+# 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
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Tools/RenderTemplate.ts b/Packs/kai-prompting-skill/src/skills/Prompting/Tools/RenderTemplate.ts
new file mode 100644
index 00000000..a54e88fe
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Tools/RenderTemplate.ts
@@ -0,0 +1,269 @@
+#!/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();
+}
diff --git a/Packs/kai-prompting-skill/src/skills/Prompting/Tools/ValidateTemplate.ts b/Packs/kai-prompting-skill/src/skills/Prompting/Tools/ValidateTemplate.ts
new file mode 100644
index 00000000..dcd82b9f
--- /dev/null
+++ b/Packs/kai-prompting-skill/src/skills/Prompting/Tools/ValidateTemplate.ts
@@ -0,0 +1,214 @@
+#!/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();
+}
diff --git a/Packs/kai-voice-system/INSTALL.md b/Packs/kai-voice-system/INSTALL.md
new file mode 100644
index 00000000..8d495d3d
--- /dev/null
+++ b/Packs/kai-voice-system/INSTALL.md
@@ -0,0 +1,248 @@
+# Kai Voice System - Installation Guide
+
+## Prerequisites
+
+- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`
+- **macOS**: Uses `afplay` for audio playback (Linux users need modification)
+- **ElevenLabs account**: Sign up at [elevenlabs.io](https://elevenlabs.io)
+- **Required PAI Packs** (install these first):
+ - `kai-hook-system` - Foundation hook infrastructure
+ - `kai-core-install` - Skills, identity, and response format
+
+---
+
+## Pre-Installation: System Analysis
+
+### 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!"
+fi
+
+# Check core install (REQUIRED)
+if [ -d "$PAI_CHECK/skills" ] && [ -f "$PAI_CHECK/skills/CORE/SKILL.md" ]; then
+ echo "✓ kai-core-install is installed"
+else
+ echo "❌ kai-core-install NOT installed - REQUIRED!"
+fi
+
+# Check for ElevenLabs API key
+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"
+else
+ echo "⚠️ ELEVENLABS_API_KEY not found - add to $PAI_ENV"
+fi
+```
+
+### Step 0.2: Check for Existing Voice System
+
+```bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Check for existing voice directory
+if [ -d "$PAI_CHECK/voice" ]; then
+ echo "⚠️ Voice directory EXISTS"
+else
+ echo "✓ No existing voice directory"
+fi
+
+# Check for running voice server
+if lsof -i :8888 > /dev/null 2>&1; then
+ echo "⚠️ Something running on port 8888"
+else
+ echo "✓ Port 8888 is available"
+fi
+```
+
+### Step 0.3: Stop Existing Voice Server (If Running)
+
+```bash
+# Stop any running voice server
+pkill -f "voice/server.ts" 2>/dev/null || true
+
+# 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
+fi
+```
+
+---
+
+## Step 1: Create Directory Structure
+
+```bash
+mkdir -p $PAI_DIR/hooks/lib
+mkdir -p $PAI_DIR/config
+mkdir -p $PAI_DIR/voice-server
+```
+
+---
+
+## Step 2: Install Prosody Enhancer Library
+
+Copy `src/hooks/lib/prosody-enhancer.ts` to `$PAI_DIR/hooks/lib/prosody-enhancer.ts`
+
+---
+
+## Step 3: Install Voice Hooks
+
+Copy the following files:
+- `src/hooks/stop-hook-voice.ts` → `$PAI_DIR/hooks/stop-hook-voice.ts`
+- `src/hooks/subagent-stop-hook-voice.ts` → `$PAI_DIR/hooks/subagent-stop-hook-voice.ts`
+
+---
+
+## Step 4: Install Voice Configuration
+
+Copy `config/voice-personalities.json` to `$PAI_DIR/config/voice-personalities.json`
+
+---
+
+## Step 5: Install Voice Server
+
+Copy `src/voice/server.ts` to `$PAI_DIR/voice-server/server.ts`
+
+---
+
+## Step 6: Set Up ElevenLabs Account
+
+1. **Sign up** at [elevenlabs.io](https://elevenlabs.io)
+2. **Get your API key** from Profile + API key
+3. **Add to $PAI_DIR/.env**:
+
+```bash
+ELEVENLABS_API_KEY="your-api-key"
+```
+
+4. **Test your API key**:
+
+```bash
+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.", "model_id": "eleven_turbo_v2_5"}' \
+ --output test.mp3
+
+afplay test.mp3 # Should hear "Hello, this is a test"
+rm test.mp3
+```
+
+---
+
+## Step 7: Register Hooks
+
+Merge the hook configuration from `config/settings-hooks.json` into your `~/.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 8: Start Voice Server
+
+```bash
+# Start the voice server
+bun run $PAI_DIR/voice-server/server.ts &
+
+# Verify it's running
+curl http://localhost:8888/health
+```
+
+---
+
+## Step 9: (Optional) Set Up Auto-Start
+
+Create a LaunchAgent to auto-start the voice server on login:
+
+```bash
+cat > ~/Library/LaunchAgents/com.pai.voice-server.plist << '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>com.pai.voice-server</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/Users/YOUR_USERNAME/.bun/bin/bun</string>
+ <string>run</string>
+ <string>/Users/YOUR_USERNAME/.config/pai/voice-server/server.ts</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>StandardOutPath</key>
+ <string>/Users/YOUR_USERNAME/Library/Logs/pai-voice-server.log</string>
+ <key>StandardErrorPath</key>
+ <string>/Users/YOUR_USERNAME/Library/Logs/pai-voice-server.log</string>
+</dict>
+</plist>
+EOF
+
+# Replace YOUR_USERNAME with your actual username
+sed -i '' "s/YOUR_USERNAME/$USER/g" ~/Library/LaunchAgents/com.pai.voice-server.plist
+
+# Load the agent
+launchctl load ~/Library/LaunchAgents/com.pai.voice-server.plist
+```
+
+---
+
+## Step 10: Verify Installation
+
+Run the verification checklist in VERIFY.md to confirm everything works.
+
+---
+
+## Troubleshooting
+
+### No Voice Output
+
+1. Check voice server is running: `curl http://localhost:8888/health`
+2. Verify ElevenLabs API key is set in `$PAI_DIR/.env`
+3. Check logs: `tail -f ~/Library/Logs/pai-voice-server.log`
+
+### Wrong Voice
+
+1. Verify voice ID in `config/voice-personalities.json`
+2. Check agent type is being detected correctly in hooks
+
+### Audio Playback Issues
+
+1. Ensure `afplay` is available (macOS built-in)
+2. Check system volume
+3. Verify audio permissions
diff --git a/Packs/kai-voice-system/README.md b/Packs/kai-voice-system/README.md
new file mode 100644
index 00000000..1802d81b
--- /dev/null
+++ b/Packs/kai-voice-system/README.md
@@ -0,0 +1,112 @@
+---
+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
+
+## What This Pack 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
+
+## Architecture Overview
+
+```
+┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
+│ Stop Hook │ ───► │ Voice Server │ ───► │ ElevenLabs │
+│ (extracts msg) │ │ (localhost:8888)│ │ (TTS API) │
+└─────────────────┘ └──────────────────┘ └─────────────────┘
+```
+
+## The 5-Layer Prosody Enhancement Pipeline
+
+```
+┌──────────────────────────────────────────────────────────────────┐
+│ PROSODY ENHANCEMENT PIPELINE │
+├──────────────────────────────────────────────────────────────────┤
+│ 1. TEXT EXTRACTION Raw completion message │
+│ 2. CONTEXT ANALYSIS Detect emotional patterns │
+│ 3. PERSONALITY PROSODY Agent-specific speech patterns │
+│ 4. SPEECH CLEANING Remove non-spoken artifacts │
+│ 5. VOICE DELIVERY Personality → Voice ID routing │
+└──────────────────────────────────────────────────────────────────┘
+```
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| Voice stop hook | `src/hooks/stop-hook-voice.ts` | Main agent voice notification |
+| Subagent voice hook | `src/hooks/subagent-stop-hook-voice.ts` | Subagent voice notification |
+| Prosody enhancer | `src/hooks/lib/prosody-enhancer.ts` | Add emotion/pauses to speech |
+| Voice server | `src/voice/server.ts` | HTTP server for TTS requests |
+| Server management | `src/voice/manage.sh` | Start/stop/restart server |
+| Voice personalities | `config/voice-personalities.json` | Agent voice configurations |
+| Hook configuration | `config/settings-hooks.json` | Hook registration template |
+
+**Summary:**
+- **Files created:** 7
+- **Hooks registered:** 2 (Stop, SubagentStop)
+- **Dependencies:** kai-hook-system (required), kai-core-install (required), ElevenLabs API key
+
+## Agent Voice Mapping
+
+| Agent Type | Voice Name | Speaking Rate | Stability | Archetype |
+|------------|------------|---------------|-----------|-----------|
+| PAI (Main) | Your DA | 235 wpm | 0.38 | enthusiast |
+| Intern | Dev Patel | 270 wpm | 0.30 | enthusiast |
+| Engineer | Marcus Webb | 212 wpm | 0.72 | wise-leader |
+| Architect | Serena Blackwood | 205 wpm | 0.75 | wise-leader |
+| Researcher | Ava Sterling | 229 wpm | 0.64 | analyst |
+| Designer | Aditi Sharma | 226 wpm | 0.52 | critic |
+| Artist | Priya Desai | 215 wpm | 0.20 | enthusiast |
+| Pentester | Rook Blackburn | 260 wpm | 0.18 | enthusiast |
+| Writer | Emma Hartley | 230 wpm | 0.48 | storyteller |
+
+## Emotional Detection
+
+The prosody enhancer detects emotional context from message patterns:
+
+| Priority | Emotion | Triggers | Marker |
+|----------|---------|----------|--------|
+| 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] |
+
+## Credits
+
+- **Author:** Daniel Miessler
+- **Origin:** Extracted from production Kai system (2024-2025)
+- **License:** MIT
+
+## Works Well With
+
+- **kai-hook-system** (required) - Hooks trigger voice notifications
+- **kai-core-install** (required) - Response format provides 🎯 COMPLETED line
+- **kai-history-system** - Complementary functionality
diff --git a/Packs/kai-voice-system/VERIFY.md b/Packs/kai-voice-system/VERIFY.md
new file mode 100644
index 00000000..8d3b6d4c
--- /dev/null
+++ b/Packs/kai-voice-system/VERIFY.md
@@ -0,0 +1,174 @@
+# Kai Voice System - Verification Checklist
+
+## Mandatory Completion Checklist
+
+**IMPORTANT:** All items must be verified before considering this pack installed.
+
+### Directory Structure
+
+- [ ] `$PAI_DIR/hooks/lib/` directory exists
+- [ ] `$PAI_DIR/config/` directory exists
+- [ ] `$PAI_DIR/voice-server/` directory exists
+
+### Core Files
+
+- [ ] `$PAI_DIR/hooks/lib/prosody-enhancer.ts` exists
+- [ ] `$PAI_DIR/hooks/stop-hook-voice.ts` exists
+- [ ] `$PAI_DIR/hooks/subagent-stop-hook-voice.ts` exists
+- [ ] `$PAI_DIR/voice-server/server.ts` exists
+- [ ] `$PAI_DIR/config/voice-personalities.json` exists
+
+### Configuration
+
+- [ ] `ELEVENLABS_API_KEY` set in `$PAI_DIR/.env`
+- [ ] Voice hooks registered in `~/.claude/settings.json`
+
+### Services
+
+- [ ] Voice server running on port 8888
+
+---
+
+## Functional Tests
+
+### Test 1: Verify Directory Structure
+
+```bash
+ls -la $PAI_DIR/hooks/lib/
+# Expected: prosody-enhancer.ts
+
+ls -la $PAI_DIR/voice-server/
+# Expected: server.ts
+
+ls -la $PAI_DIR/config/
+# Expected: voice-personalities.json
+```
+
+### Test 2: Check Voice Server Health
+
+```bash
+curl http://localhost:8888/health
+# Expected: {"status":"healthy","port":8888,"voice_system":"ElevenLabs",...}
+```
+
+### Test 3: Test Voice Notification
+
+```bash
+curl -X POST http://localhost:8888/notify \
+ -H "Content-Type: application/json" \
+ -d '{"title":"Test","message":"Hello from PAI voice system","voice_enabled":true}'
+# Expected: Hear "Hello from PAI voice system" spoken aloud
+```
+
+### Test 4: Test Emotional Markers
+
+```bash
+curl -X POST http://localhost:8888/notify \
+ -H "Content-Type: application/json" \
+ -d '{"title":"Test","message":"[✨ success] Fixed the authentication bug!","voice_enabled":true}'
+# Expected: Success tone with emphasis on "Fixed"
+```
+
+### Test 5: Verify Prosody Enhancer
+
+```bash
+# In a bun REPL or test file:
+import { enhanceProsody, cleanForSpeech } from '$PAI_DIR/hooks/lib/prosody-enhancer';
+
+const result = enhanceProsody("Completed fixing the login bug", "engineer");
+console.log(result);
+# Expected: Enhanced text with emotional markers
+```
+
+### Test 6: Check Hook Registration
+
+```bash
+grep -A5 "stop-hook-voice" ~/.claude/settings.json
+# Expected: Shows hook configuration
+```
+
+---
+
+## Integration Tests
+
+### Test A: Main Agent Voice
+
+In a Claude Code session:
+1. Complete a task that produces 🎯 COMPLETED output
+2. Listen for voice announcement
+3. Should hear the COMPLETED message spoken
+
+### Test B: Subagent Voice
+
+In a Claude Code session:
+1. Run a Task that spawns a subagent
+2. Wait for subagent to complete
+3. Should hear different voice for the agent type
+
+### Test C: Graceful Degradation
+
+```bash
+# Stop the voice server
+pkill -f "voice/server.ts"
+
+# In Claude Code, complete a task
+# Should complete without errors (silent, no crash)
+
+# Restart voice server
+bun run $PAI_DIR/voice-server/server.ts &
+```
+
+---
+
+## Quick Verification Script
+
+```bash
+#!/bin/bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "=== Kai Voice System Verification ==="
+echo ""
+
+# Check files
+for file in "hooks/lib/prosody-enhancer.ts" "hooks/stop-hook-voice.ts" "hooks/subagent-stop-hook-voice.ts" "voice-server/server.ts" "config/voice-personalities.json"; do
+ if [ -f "$PAI_CHECK/$file" ]; then
+ echo "✓ $file"
+ else
+ echo "❌ $file MISSING"
+ fi
+done
+
+echo ""
+
+# Check API key
+if [ -f "$PAI_CHECK/.env" ] && grep -q "ELEVENLABS_API_KEY" "$PAI_CHECK/.env"; then
+ echo "✓ ELEVENLABS_API_KEY configured"
+else
+ echo "❌ ELEVENLABS_API_KEY not configured"
+fi
+
+echo ""
+
+# Check voice server
+if curl -s http://localhost:8888/health > /dev/null 2>&1; then
+ echo "✓ Voice server running on port 8888"
+else
+ echo "❌ Voice server NOT running"
+fi
+
+echo ""
+echo "=== Verification Complete ==="
+```
+
+---
+
+## Success Criteria
+
+Installation is complete when:
+
+1. All directory structure items are checked
+2. All core files are present
+3. ElevenLabs API key is configured
+4. Voice server responds to health check
+5. Test notification produces audible output
+6. Hooks are registered in settings.json
diff --git a/Packs/kai-voice-system/config/settings-hooks.json b/Packs/kai-voice-system/config/settings-hooks.json
new file mode 100644
index 00000000..c37d3ec9
--- /dev/null
+++ b/Packs/kai-voice-system/config/settings-hooks.json
@@ -0,0 +1,32 @@
+{
+ "_description": "Hook registration template for Claude Code settings.json",
+ "_instructions": [
+ "Merge these hook configurations into ~/.claude/settings.json",
+ "The hooks array should be added/merged under the 'hooks' key",
+ "Adjust paths based on your $PAI_DIR location"
+ ],
+ "hooks": [
+ {
+ "event": "Stop",
+ "command": "bun run $PAI_DIR/hooks/stop-hook-voice.ts",
+ "description": "Main agent voice notification with prosody enhancement"
+ },
+ {
+ "event": "SubagentStop",
+ "command": "bun run $PAI_DIR/hooks/subagent-stop-hook-voice.ts",
+ "description": "Subagent voice notification with personality-specific delivery"
+ }
+ ],
+ "_example_settings_json": {
+ "hooks": [
+ {
+ "event": "Stop",
+ "command": "bun run /Users/yourname/.config/pai/hooks/stop-hook-voice.ts"
+ },
+ {
+ "event": "SubagentStop",
+ "command": "bun run /Users/yourname/.config/pai/hooks/subagent-stop-hook-voice.ts"
+ }
+ ]
+ }
+}
diff --git a/Packs/kai-voice-system/config/voice-personalities.json b/Packs/kai-voice-system/config/voice-personalities.json
new file mode 100644
index 00000000..0a602b11
--- /dev/null
+++ b/Packs/kai-voice-system/config/voice-personalities.json
@@ -0,0 +1,88 @@
+{
+ "default_volume": 0.8,
+ "voices": {
+ "pai": {
+ "voice_id": "${ELEVENLABS_VOICE_PAI}",
+ "voice_name": "PAI",
+ "stability": 0.38,
+ "similarity_boost": 0.75,
+ "description": "Professional, expressive - Daniel's primary AI assistant"
+ },
+ "intern": {
+ "voice_id": "${ELEVENLABS_VOICE_INTERN}",
+ "voice_name": "Intern",
+ "stability": 0.30,
+ "similarity_boost": 0.85,
+ "description": "Enthusiastic, chaotic energy - eager 176 IQ genius"
+ },
+ "engineer": {
+ "voice_id": "${ELEVENLABS_VOICE_ENGINEER}",
+ "voice_name": "Engineer",
+ "stability": 0.72,
+ "similarity_boost": 0.80,
+ "description": "Wise leader, stable - Fortune 10 principal engineer"
+ },
+ "architect": {
+ "voice_id": "${ELEVENLABS_VOICE_ARCHITECT}",
+ "voice_name": "Architect",
+ "stability": 0.75,
+ "similarity_boost": 0.78,
+ "description": "Wise leader, deliberate - PhD-level system designer"
+ },
+ "researcher": {
+ "voice_id": "${ELEVENLABS_VOICE_RESEARCHER}",
+ "voice_name": "Researcher",
+ "stability": 0.64,
+ "similarity_boost": 0.82,
+ "description": "Analyst, measured - comprehensive research specialist"
+ },
+ "designer": {
+ "voice_id": "${ELEVENLABS_VOICE_DESIGNER}",
+ "voice_name": "Designer",
+ "stability": 0.52,
+ "similarity_boost": 0.80,
+ "description": "Critic, measured - exacting UX/UI specialist"
+ },
+ "artist": {
+ "voice_id": "${ELEVENLABS_VOICE_ARTIST}",
+ "voice_name": "Artist",
+ "stability": 0.20,
+ "similarity_boost": 0.90,
+ "description": "Enthusiast, chaotic - visual content creator"
+ },
+ "pentester": {
+ "voice_id": "${ELEVENLABS_VOICE_PENTESTER}",
+ "voice_name": "Pentester",
+ "stability": 0.18,
+ "similarity_boost": 0.88,
+ "description": "Enthusiast, chaotic - offensive security specialist"
+ },
+ "writer": {
+ "voice_id": "${ELEVENLABS_VOICE_WRITER}",
+ "voice_name": "Writer",
+ "stability": 0.45,
+ "similarity_boost": 0.85,
+ "description": "Professional, expressive - content creation specialist"
+ }
+ },
+ "_instructions": {
+ "voice_id_setup": [
+ "1. Go to ElevenLabs.io and create/select voices for each agent type",
+ "2. Copy the voice_id from each voice's settings page",
+ "3. Add to $PAI_DIR/.env: ELEVENLABS_VOICE_PAI=voice_id_here",
+ "4. Repeat for each agent type you want distinct voices for",
+ "5. Agents without specific voice IDs fall back to ELEVENLABS_VOICE_DEFAULT"
+ ],
+ "stability_guide": {
+ "0.0-0.3": "Very expressive, chaotic energy (Artist, Pentester, Intern)",
+ "0.3-0.5": "Expressive with some control (Writer, Designer)",
+ "0.5-0.7": "Balanced, professional (PAI, Researcher)",
+ "0.7-1.0": "Very stable, measured delivery (Engineer, Architect)"
+ },
+ "similarity_boost_guide": {
+ "0.7-0.8": "More natural variation",
+ "0.8-0.9": "Closer to original voice",
+ "0.9-1.0": "Very close to original voice"
+ }
+ }
+}
diff --git a/Packs/kai-voice-system/src/hooks/lib/prosody-enhancer.ts b/Packs/kai-voice-system/src/hooks/lib/prosody-enhancer.ts
new file mode 100644
index 00000000..768bf240
--- /dev/null
+++ b/Packs/kai-voice-system/src/hooks/lib/prosody-enhancer.ts
@@ -0,0 +1,346 @@
+#!/usr/bin/env bun
+// $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 || '';
+}
diff --git a/Packs/kai-voice-system/src/hooks/stop-hook-voice.ts b/Packs/kai-voice-system/src/hooks/stop-hook-voice.ts
new file mode 100644
index 00000000..f894b710
--- /dev/null
+++ b/Packs/kai-voice-system/src/hooks/stop-hook-voice.ts
@@ -0,0 +1,190 @@
+#!/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);
+});
diff --git a/Packs/kai-voice-system/src/hooks/subagent-stop-hook-voice.ts b/Packs/kai-voice-system/src/hooks/subagent-stop-hook-voice.ts
new file mode 100644
index 00000000..21830193
--- /dev/null
+++ b/Packs/kai-voice-system/src/hooks/subagent-stop-hook-voice.ts
@@ -0,0 +1,249 @@
+#!/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);
diff --git a/Packs/kai-voice-system/src/voice/server.ts b/Packs/kai-voice-system/src/voice/server.ts
new file mode 100644
index 00000000..dc1959b9
--- /dev/null
+++ b/Packs/kai-voice-system/src/voice/server.ts
@@ -0,0 +1,372 @@
+#!/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(paiDir, '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'}`);