⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
fix(release/v5.0.0): include PAI-Install in published release
Daniel Miessler9e114d3d1f74
diff --git a/Releases/v5.0.0/.claude/.gitignore b/Releases/v5.0.0/.claude/.gitignoreindex e529fee3..5b815dd0 100755--- a/Releases/v5.0.0/.claude/.gitignore+++ b/Releases/v5.0.0/.claude/.gitignore@@ -114,7 +114,6 @@ PAI/Releases/PAI/ide/PAI/IDE/PAI/voice-server-PAI/PAI-Install/PAI/PAIWorker/# Wrangler/Playwright caches (inside Arbol and elsewhere)diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/.gitignore b/Releases/v5.0.0/.claude/PAI/PAI-Install/.gitignorenew file mode 100644index 00000000..c4ba0851--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/.gitignore@@ -0,0 +1,13 @@+# Dependencies+electron/node_modules/+node_modules/++# Build artifacts+*.tsbuildinfo++# OS files+.DS_Store+Thumbs.db++# Install state (user-specific)+install-state.jsondiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/README.md b/Releases/v5.0.0/.claude/PAI/PAI-Install/README.mdnew file mode 100644index 00000000..d6bf43ec--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/README.md@@ -0,0 +1,349 @@+# PAI Installer v5.0++> Install [PAI (Personal AI Infrastructure)](https://github.com/danielmiessler/PAI) with a single command.++## Quick Start++```bash+bash PAI-Install/install.sh+```++That's it. The script handles everything:++1. Detects your operating system and installed tools+2. Installs **Bun** and **Git** if missing+3. Launches a guided Web UI installer+4. Walks you through identity, voice, and configuration+5. Validates the installation before finishing++### Requirements++- **bash** and **curl** — that's all you need to start+- macOS or Linux+- Internet connection++Everything else (Bun, Git, Claude Code) is installed automatically.++---++## Installation Steps++The installer runs 8 steps in dependency order:++| # | Step | What It Does |+|---|------|-------------|+| 1 | **System Detection** | Detects OS, architecture, shell, installed tools (Bun, Git, Claude Code), timezone, and any existing PAI installation |+| 2 | **Prerequisites** | Installs missing tools: Git via Xcode CLT or package manager, Bun via official installer, Claude Code via npm |+| 3 | **API Keys** | Auto-completes — key collection happens during the Voice step |+| 4 | **Identity** | Prompts for your name, AI assistant name, timezone, and a personal catchphrase |+| 5 | **PAI Repository** | Clones the PAI repo to `~/.claude/` (or updates if already present) |+| 6 | **Configuration** | Generates `settings.json`, `.env`, directory structure, `pai` shell alias, and patches version files |+| 7 | **DA Voice + Pulse** | Collects ElevenLabs API key, selects voice type (Female/Male/Custom), prompts to install Pulse (voice + Life Dashboard + observability on port 31337) and the Pulse menu bar app via launchd |+| 8 | **Validation** | Verifies directory structure, settings file, API keys, Pulse health on 31337, launchd plist, shell alias — reports pass/fail for each |++### Voice + Pulse Setup++The voice step handles Digital Assistant voice configuration **and** Pulse install in one cohesive step:++1. Collects or auto-discovers your ElevenLabs API key (checks `~/.claude/PAI/.env`)+2. Validates the key against the ElevenLabs API+3. **Asks (Y/n) to install Pulse** as a launchd service — Pulse is the unified PAI runtime that serves the Life Dashboard at `http://localhost:31337`, handles voice notifications (TTS via ElevenLabs), and runs observability + scheduled jobs. Installing as a launchd agent makes it auto-start on login.+4. Presents voice selection: **Female** (Rachel), **Male** (Adam), or **Custom Voice ID** with audio previews+5. **Asks (Y/n) to install the Pulse menu bar app** — adds a status icon to your macOS menu bar, second launchd plist, auto-starts on login+6. Tests TTS via Pulse with a personalized greeting using your name and AI name++In PAI 5.0 the standalone voice server was absorbed into Pulse: there is no separate process — Pulse on port 31337 embeds the voice module, the Life Dashboard, observability, and scheduled jobs in one launchd-managed runtime.++Voice + Pulse are optional. Skip the ElevenLabs key and the installer continues without voice. Skip the Pulse install and you can run it later: `bash ~/.claude/PAI/PULSE/manage.sh install`.++### Graceful Degradation++The installer is designed to recover from partial failures:++- No ElevenLabs key → voice features skipped, Pulse can still install for dashboard + observability+- No existing PAI → fresh install (vs. upgrade if detected)+- Pulse install declined or fails → configuration saved, voice notifications unavailable until Pulse is installed manually+- Menu bar install declined or fails → Pulse keeps running; menu bar can be installed later+- Claude Code not installed → attempts installation, continues if it fails+- Port conflicts → installer port configurable via `PAI_INSTALL_PORT` environment variable++---++## Architecture++### Two-Layer Design++1. **Bootstrap** (`install.sh`) — Pure bash. Only needs bash + curl. Installs Bun and Git, then hands off to the TypeScript installer.+2. **Engine + UI** (`engine/` + `web/` + `public/`) — TypeScript (Bun). All install logic, web server, and frontend.++### Launch Modes++The installer supports three modes via `main.ts`:++| Mode | Command | Description |+|------|---------|-------------|+| **GUI** (default) | `--mode gui` | Launches Electron window wrapping the web server. Audio autoplay works. This is what `install.sh` uses. |+| **Web** | `--mode web` | Starts the Bun HTTP/WebSocket server on port 1337. Open in any browser. |+| **CLI** | `--mode cli` | Terminal-only wizard with ANSI colors and progress bars. No browser needed. |++GUI mode auto-installs Electron dependencies on first run and clears macOS quarantine flags.++### Directory Structure++```+PAI-Install/+├── install.sh # Bash bootstrap entry point+├── main.ts # Mode router (gui/web/cli)+├── generate-welcome.ts # Welcome audio generator (build-time)+│+├── engine/ # Core install logic (shared across all modes)+│ ├── types.ts # TypeScript interfaces (InstallState, messages, events)+│ ├── detect.ts # System detection (OS, tools, existing install)+│ ├── steps.ts # Step definitions + dependency graph+│ ├── actions.ts # Install action functions (clone, configure, voice, etc.)+│ ├── config-gen.ts # Fallback settings.json generator+│ ├── validate.ts # Post-install validation checks+│ ├── state.ts # State persistence (resume interrupted installs)+│ └── index.ts # Re-exports+│+├── web/ # Web server (GUI and Web modes)+│ ├── server.ts # Bun HTTP + WebSocket server (port 1337)+│ └── routes.ts # WebSocket message handler + install orchestrator+│+├── cli/ # CLI frontend+│ ├── index.ts # CLI entry point+│ └── display.ts # ANSI colors, progress bars, banners+│+├── public/ # Static web assets+│ ├── index.html # Single-page application shell+│ ├── styles.css # Dark theme with glassmorphic effects+│ ├── app.js # Frontend JavaScript (WebSocket client, UI rendering)+│ └── assets/ # Logos, fonts, welcome audio, voice previews+│+├── electron/ # Electron native wrapper+│ ├── main.js # Spawns Bun server + opens BrowserWindow+│ └── package.json # Electron dependency+│+└── README.md # This file+```++---++## WebSocket Protocol++The Web UI communicates with the install engine over WebSocket. The server runs on `ws://localhost:1337/ws`.++### Client → Server++| Type | Payload | Description |+|------|---------|-------------|+| `client_ready` | — | Client connected and ready |+| `start_install` | — | User clicked "Begin Installation" |+| `user_input` | `{ requestId, value }` | Response to a text/password input prompt |+| `user_choice` | `{ requestId, value }` | Response to a multiple-choice prompt |++### Server → Client++| Type | Payload | Description |+|------|---------|-------------|+| `connected` | — | Connection acknowledged |+| `step_update` | `{ step, status }` | Step status changed (pending/active/completed/skipped/failed) |+| `detection_result` | `{ data }` | System detection results (OS, tools, existing install) |+| `message` | `{ role, content, speak? }` | Chat message (assistant/system/error) |+| `input_request` | `{ id, prompt, inputType, placeholder }` | Request text/password input from user |+| `choice_request` | `{ id, prompt, choices[] }` | Request selection from options |+| `progress` | `{ step, percent, detail }` | Progress bar update for long operations |+| `validation_result` | `{ checks[] }` | Array of validation check results |+| `install_complete` | `{ summary }` | Installation finished with summary data |+| `error` | `{ message }` | Error message |++Messages include a `replayed` flag for reconnect replay — replayed messages skip animations and TTS.++### Message Flow Example++```+Client Server+ │ │+ ├── client_ready ──────────────→│+ │←─────────────── connected ────┤+ │ │+ ├── start_install ─────────────→│+ │←──────────── step_update ─────┤ (system-detect → active)+ │←──────── detection_result ────┤ (OS, tools, etc.)+ │←──────────── step_update ─────┤ (system-detect → completed)+ │ │+ │←──────── input_request ───────┤ ("What is your name?")+ ├── user_input ────────────────→│+ │←──────────── message ─────────┤ ("Welcome, {{PRINCIPAL_NAME}}!")+ │ │+ │←──────── choice_request ──────┤ ("Select voice type")+ ├── user_choice ───────────────→│+ │←──────────── progress ────────┤ (voice server install: 40%)+ │←──────────── step_update ─────┤ (voice → completed)+ │ │+ │←──── validation_result ───────┤ (all checks)+ │←──── install_complete ────────┤ (summary card)+```++---++## Configuration++### Settings Merge Strategy++PAI ships a complete `settings.json` template in the release repository. This template includes:++- **Hooks** — 20+ event hooks for session management, security, voice, etc.+- **Status line** — Terminal status bar configuration+- **Spinner verbs** — Activity indicator messages+- **Context files** — Files loaded into Claude Code context++The installer **does NOT generate hooks or status line config**. Instead, it:++1. Clones the PAI repository (which includes the full `settings.json` template)+2. Merges only user-specific fields into the existing template:+ - `principal` — user name, timezone+ - `daidentity` — AI name, voice ID, personality+ - `env` — PAI_DIR, PROJECTS_DIR+ - `pai` — version info+3. Preserves all hooks, status line, spinner verbs, and context files from the template++This ensures fresh installs get the full PAI configuration without the installer needing to know about every hook.++### Generated Files++| File | Location | Contents |+|------|----------|----------|+| `settings.json` | `~/.claude/settings.json` | Merged config (template + user fields) |+| `.env` | `~/.claude/PAI/.env` | `ELEVENLABS_API_KEY=...` |+| `LATEST` | `~/.claude/PAI/Algorithm/LATEST` | Algorithm version (patched to current) |+| Shell alias | `~/.zshrc` | `alias pai='cd ~/.claude && claude'` |++### Directory Structure Created++```+~/.claude/+├── settings.json+├── hooks/+├── skills/+├── MEMORY/+│ ├── WORK/+│ ├── STATE/+│ ├── LEARNING/+│ └── VOICE/+├── Plans/+└── Projects/+```++### Banner and Counts++On first launch after installation, the PAI banner displays system statistics (skills, hooks, workflows, signals, files). These counts are:++1. **Calculated by the installer** during the Configuration step (initial values)+2. **Updated by the StopOrchestrator hook** at the end of each Claude Code session++The Algorithm version displayed in the banner reads from `PAI/Algorithm/LATEST`.++---++## Web UI Features++- **Electron wrapper** — Opens in a controlled 1280x820 window with audio autoplay enabled+- **Dark theme** — Deep navy/black with PAI blue accents and glassmorphic card effects+- **Step sidebar** — All 8 steps with live status indicators (pending/active/completed/skipped/failed)+- **Progress bar** — Header shows overall completion percentage+- **Voice previews** — Listen to Female/Male voice samples before selecting+- **Welcome audio** — Pre-recorded MP3 plays on launch+- **Auto-reconnect** — WebSocket reconnects on disconnect with 2-second retry and full message replay+- **Input masking** — API keys are masked in the chat display (shows first 8 chars only)+- **Choice buttons** — Styled selection cards with descriptions and optional audio previews++---++## Post-Installation++After the installer completes, open a terminal and run:++```bash+source ~/.zshrc && pai+```++This reloads your shell config (activates the `pai` alias) and launches PAI for the first time.++### First-run: populate your personal context++Once PAI is running, kick off the phased interview to populate your TELOS, identity, preferences, and life dimensions:++```+/interview+```++The interview is conversational and resumable. It runs in 4 phases:++1. **Phase 1 — Foundational TELOS:** Mission, Goals, Problems, Strategies, Challenges, Narratives, Beliefs, Wisdom, Models, Frames+2. **Phase 2 — IDEAL_STATE:** Health, Money, Freedom, Relationships, Creative+3. **Phase 3 — Preferences:** Books, Authors, Bands, Movies, Restaurants, Food, Learning, Civic+4. **Phase 4 — Identity:** Light review of PRINCIPAL_IDENTITY and current state++Each section is skippable. If you have existing data (Obsidian, Notion, journals, prior PAI install), bring it in via the `Migrate` skill **before** running `/interview` — it intakes external content, classifies chunks against the PAI taxonomy, and writes them into the right files with provenance, so the interview only fills the genuine gaps.++---++## Troubleshooting++| Issue | Solution |+|-------|----------|+| `bun: command not found` | Run `curl -fsSL https://bun.sh/install \| bash` then restart terminal |+| Port 1337 in use | Set `PAI_INSTALL_PORT=8080` before running install.sh |+| ElevenLabs key invalid | Verify at elevenlabs.io — ensure no trailing spaces, key starts with `xi-` or `sk_` |+| Permission denied | Run `chmod -R 755 ~/.claude` |+| `pai` command not found | Run `source ~/.zshrc` to reload shell config |+| Pulse / voice notifications not working | Check port 31337 is free: `lsof -ti:31337`. Restart Pulse: `bash ~/.claude/PAI/PULSE/manage.sh restart`. Check status: `bash ~/.claude/PAI/PULSE/manage.sh status`. |+| Pulse menu bar icon missing | Install or reinstall: `bash ~/.claude/PAI/PULSE/MenuBar/install.sh`. Verify launchd plist: `ls ~/Library/LaunchAgents/com.pai.pulse-menubar.plist`. |+| Banner shows wrong algorithm version | Check `~/.claude/PAI/Algorithm/LATEST` contains correct version |+| Banner counts all show 0 | Normal on first launch — counts populate after your first Claude Code session ends |+| WebSocket "Connection lost" | The installer auto-reconnects. If persistent, check if another process is using port 1337 |+| Electron window blank | Try `--mode web` instead and open `http://localhost:1337` in your browser |++### Recovery++The installer saves state to disk. If interrupted, re-run `install.sh` — it will detect the existing installation and offer to resume or start fresh.++---++## Development++### Running Locally++```bash+# Web mode (development)+bun run PAI-Install/main.ts --mode web++# CLI mode+bun run PAI-Install/main.ts --mode cli++# GUI mode (Electron — installs deps on first run)+bun run PAI-Install/main.ts --mode gui+```++### Key Design Decisions++- **No framework dependencies** — Frontend is vanilla JavaScript. No React, no build step.+- **Bun-native server** — Uses `Bun.serve()` for HTTP and WebSocket in one process.+- **Async Pulse install** — Pulse install via `manage.sh install` uses async `spawn` (not `execSync`) to avoid blocking the event loop and killing WebSocket connections. PAI 5.0 absorbed the standalone voice server into Pulse on port 31337 — there is no separate voice-server process.+- **Safe process cleanup** — Port cleanup uses `lsof -sTCP:LISTEN` to kill only the listening process, not client connections.+- **Template-based settings** — Installer merges user fields into the release template rather than generating a complete settings.json from scratch.++---++## Known Limitations++- **macOS and Linux only** — Windows is not supported+- **Internet connection required** — Downloads tools, clones repository, validates API keys+- **Voice requires ElevenLabs** — Voice synthesis is optional but needs an ElevenLabs API key+- **Single-user** — Installs to `~/.claude/` for the current user only+- **Electron optional** — If Electron fails to install, use `--mode web` as fallback++## License++Part of [PAI — Personal AI Infrastructure](https://github.com/danielmiessler/PAI).diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/display.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/display.tsnew file mode 100644index 00000000..8d551bed--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/display.ts@@ -0,0 +1,249 @@+/**+ * PAI Installer v5.0 — CLI Display Helpers+ * ANSI colors, progress bars, banners, and formatted output.+ */++// ─── ANSI Colors ─────────────────────────────────────────────────++export const c = {+ reset: "\x1b[0m",+ bold: "\x1b[1m",+ dim: "\x1b[2m",+ italic: "\x1b[3m",+ blue: "\x1b[38;2;59;130;246m",+ lightBlue: "\x1b[38;2;147;197;253m",+ navy: "\x1b[38;2;30;58;138m",+ green: "\x1b[38;2;34;197;94m",+ yellow: "\x1b[38;2;234;179;8m",+ red: "\x1b[38;2;239;68;68m",+ gray: "\x1b[38;2;100;116;139m",+ steel: "\x1b[38;2;51;65;85m",+ silver: "\x1b[38;2;203;213;225m",+ white: "\x1b[38;2;203;213;225m",+ cyan: "\x1b[36m",+};++const ANSI_PATTERN = /\x1b\[[0-9;]*m/g;++export function print(text: string): void {+ process.stdout.write(text + "\n");+}++export function printSuccess(text: string): void {+ print(` ${c.green}✓${c.reset} ${text}`);+}++export function printError(text: string): void {+ print(` ${c.red}✗${c.reset} ${text}`);+}++export function printWarning(text: string): void {+ print(` ${c.yellow}⚠${c.reset} ${text}`);+}++export function printInfo(text: string): void {+ print(` ${c.blue}ℹ${c.reset} ${text}`);+}++export function printStep(num: number, total: number, name: string): void {+ // Loud, unambiguous section frame — heavy double-line border in PAI blue,+ // step number prominent, generous whitespace above and below so the+ // reader's eye lands on it first when the wizard moves to a new section.+ const label = ` STEP ${num} / ${total} — ${name.toUpperCase()} `;+ const inner = label.length;+ const border = "═".repeat(inner);+ print("");+ print("");+ print(` ${c.blue}╔${border}╗${c.reset}`);+ print(` ${c.blue}║${c.bold}${c.lightBlue}${label}${c.reset}${c.blue}║${c.reset}`);+ print(` ${c.blue}╚${border}╝${c.reset}`);+ print("");+}++function padVisible(text: string, width: number): string {+ return text + " ".repeat(Math.max(0, width - visibleLength(text)));+}++export function printSectionHeader(title: string, subtitle?: string, stepNumber?: number): void {+ const stepLabel = stepNumber ? `Step ${stepNumber}/9` : "";+ const leftLabel = `${c.bold}${c.white}▸ ${title}${c.reset}`;+ const innerWidth = Math.max(+ 53,+ visibleLength(`▸ ${title}`) + (stepLabel ? stepLabel.length + 4 : 0),+ subtitle ? subtitle.length + 4 : 0+ );+ const rightPadding = stepLabel ? Math.max(2, innerWidth - visibleLength(`▸ ${title}`) - stepLabel.length) : 0;++ print("");+ print(` ${c.lightBlue}╭${"─".repeat(innerWidth + 2)}╮${c.reset}`);+ print(` ${c.lightBlue}│${c.reset} ${leftLabel}${stepLabel ? `${" ".repeat(rightPadding)}${c.gray}${stepLabel}${c.reset}` : padVisible("", innerWidth)} ${c.lightBlue}│${c.reset}`);+ if (subtitle) {+ print(` ${c.lightBlue}│${c.reset} ${c.gray}${padVisible(subtitle, innerWidth)}${c.reset} ${c.lightBlue}│${c.reset}`);+ }+ print(` ${c.lightBlue}╰${"─".repeat(innerWidth + 2)}╯${c.reset}`);+}++/**+ * Render a question prompt with a distinct visual frame so it stands out+ * from informational messages and progress lines. The wizard's answers go+ * BELOW the box; the question stays inside. Used by cli/prompts.ts for+ * promptText / promptChoice / promptConfirm / promptSecret.+ */+function visibleLength(text: string): number {+ return text.replace(ANSI_PATTERN, "").length;+}++export function printQuestion(text: string, daName: string = "{{DA_NAME}}"): void {+ const borderColor = c.lightBlue;+ const header = `${daName} asks`;+ const lines = text.split("\n");+ const innerWidth = Math.max(header.length, ...lines.map(visibleLength));++ print("");+ print(` ${borderColor}╭─ ${header} ${"─".repeat(Math.max(0, innerWidth - header.length))}╮${c.reset}`);+ for (const line of lines) {+ print(` ${borderColor}│${c.reset} ${c.white}${line}${c.reset}${" ".repeat(Math.max(0, innerWidth - visibleLength(line)))} ${borderColor}│${c.reset}`);+ }+ print(` ${borderColor}╰${"─".repeat(innerWidth + 2)}╯${c.reset}`);+}++// ─── Progress Bar ────────────────────────────────────────────────++export function progressBar(percent: number, width: number = 30): string {+ const filled = Math.round((percent / 100) * width);+ const empty = width - filled;+ return `${c.blue}${"▓".repeat(filled)}${c.gray}${"░".repeat(empty)}${c.reset} ${percent}%`;+}++// ─── Banner ──────────────────────────────────────────────────────++export function printBanner(): void {+ const sep = `${c.steel}│${c.reset}`;+ const bar = `${c.steel}────────────────────────${c.reset}`;++ print("");+ print(`${c.steel}┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓${c.reset}`);+ print("");+ print(` ${c.navy}P${c.reset}${c.blue}A${c.reset}${c.lightBlue}I${c.reset} ${c.steel}|${c.reset} ${c.gray}Personal AI Infrastructure${c.reset}`);+ print("");+ print(` ${c.italic}${c.lightBlue}"Magnifying human capabilities..."${c.reset}`);+ print("");+ print("");+ print(` ${c.navy}████████████████${c.reset}${c.lightBlue}████${c.reset} ${sep} ${c.gray}"${c.reset}${c.lightBlue}{{DA_NAME}} here, ready to go${c.reset}${c.gray}..."${c.reset}`);+ print(` ${c.navy}████████████████${c.reset}${c.lightBlue}████${c.reset} ${sep} ${bar}`);+ print(` ${c.navy}████${c.reset} ${c.navy}████${c.reset}${c.lightBlue}████${c.reset} ${sep} ${c.navy}⬢${c.reset} ${c.gray}PAI${c.reset} ${c.silver}v5.0.0${c.reset}`);+ print(` ${c.navy}████${c.reset} ${c.navy}████${c.reset}${c.lightBlue}████${c.reset} ${sep} ${c.navy}⚙${c.reset} ${c.gray}Algo${c.reset} ${c.silver}v1.4.0${c.reset}`);+ print(` ${c.navy}████████████████${c.reset}${c.lightBlue}████${c.reset} ${sep} ${c.lightBlue}✦${c.reset} ${c.gray}Installer${c.reset} ${c.silver}v5.0${c.reset}`);+ print(` ${c.navy}████████████████${c.reset}${c.lightBlue}████${c.reset} ${sep} ${bar}`);+ print(` ${c.navy}████${c.reset} ${c.blue}████${c.reset}${c.lightBlue}████${c.reset} ${sep}`);+ print(` ${c.navy}████${c.reset} ${c.blue}████${c.reset}${c.lightBlue}████${c.reset} ${sep} ${c.yellow}⚠ Alpha — rough edges expected${c.reset}`);+ print(` ${c.navy}████${c.reset} ${c.blue}████${c.reset}${c.lightBlue}████${c.reset} ${sep}`);+ print(` ${c.navy}████${c.reset} ${c.blue}████${c.reset}${c.lightBlue}████${c.reset} ${sep}`);+ print("");+ print("");+ print(` ${c.steel}→${c.reset} ${c.blue}github.com/danielmiessler/PAI${c.reset}`);+ print("");+ print(`${c.steel}┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛${c.reset}`);+ print("");+}++// ─── Detection Display ───────────────────────────────────────────++import type { DetectionResult } from "../engine/types";++export function printDetection(det: DetectionResult): void {+ printSuccess(`Operating System: ${det.os.name} (${det.os.arch})`);+ printSuccess(`Shell: ${det.shell.name} ${det.shell.version ? `v${det.shell.version.substring(0, 20)}` : ""}`);++ if (det.tools.bun.installed) {+ printSuccess(`Bun: v${det.tools.bun.version}`);+ } else {+ printError("Bun: not found — will install");+ }++ if (det.tools.git.installed) {+ printSuccess(`Git: v${det.tools.git.version}`);+ } else {+ printError("Git: not found — will install");+ }++ if (det.tools.claude.installed) {+ printSuccess(`Claude Code: v${det.tools.claude.version}`);+ } else {+ printWarning("Claude Code: not found — will install");+ }++ if (det.existing.paiInstalled) {+ printInfo(`Existing PAI: v${det.existing.paiVersion || "unknown"} (fresh install will restore from backup if you allow it)`);+ } else {+ printInfo("Existing PAI: not detected (fresh install)");+ }++ // Scan-first findings — surface pre-fillable values so the user sees what+ // the wizard already has answers for.+ if (det.principal?.name) {+ printSuccess(`Detected name: ${det.principal.name}`);+ }+ if (det.principal?.email) {+ printInfo(`Detected email: ${det.principal.email}`);+ }+ if (det.existing.daName) {+ printSuccess(`Detected DA name: ${det.existing.daName} (from prior install/backup)`);+ }+ const apiHits: string[] = [];+ if (det.existing.apiKeys?.elevenLabs) apiHits.push("ElevenLabs");+ if (det.existing.apiKeys?.anthropic) apiHits.push("Anthropic");+ if (det.existing.apiKeys?.openai) apiHits.push("OpenAI");+ if (det.existing.apiKeys?.google) apiHits.push("Google");+ if (det.existing.apiKeys?.xai) apiHits.push("xAI/Grok");+ if (det.existing.apiKeys?.perplexity) apiHits.push("Perplexity");+ if (apiHits.length > 0) {+ printSuccess(`Detected API keys: ${apiHits.join(", ")} (from shell rc files / .env)`);+ }+ if (det.voice?.systemDefault) {+ printInfo(`System voice: ${det.voice.systemDefault}`);+ }++ printInfo(`Timezone: ${det.timezone}`);+}++// ─── Validation Display ──────────────────────────────────────────++import type { ValidationCheck, InstallSummary } from "../engine/types";++export function printValidation(checks: ValidationCheck[]): void {+ print("");+ print(`${c.bold} Validation Results${c.reset}`);+ print(`${c.gray} ${"─".repeat(40)}${c.reset}`);++ for (const check of checks) {+ if (check.passed) {+ printSuccess(`${check.name}: ${check.detail}`);+ } else if (check.critical) {+ printError(`${check.name}: ${check.detail}`);+ } else {+ printWarning(`${check.name}: ${check.detail}`);+ }+ }+}++export function printSummary(summary: InstallSummary): void {+ const installTypeLabel = summary.installType === "upgrade" ? "fresh + backup migration" : "fresh";++ print("");+ print(`${c.navy}╔══════════════════════════════════════════════════╗${c.reset}`);+ print(`${c.navy}║${c.reset} ${c.green}${c.bold}SYSTEM ONLINE${c.reset} ${c.navy}║${c.reset}`);+ print(`${c.navy}╠══════════════════════════════════════════════════╣${c.reset}`);+ print(`${c.navy}║${c.reset} PAI Version: ${c.white}v${summary.paiVersion}${c.reset} ${c.navy}║${c.reset}`);+ print(`${c.navy}║${c.reset} Principal: ${c.white}${summary.principalName}${c.reset}${" ".repeat(Math.max(0, 33 - summary.principalName.length))}${c.navy}║${c.reset}`);+ print(`${c.navy}║${c.reset} AI Name: ${c.white}${summary.aiName}${c.reset}${" ".repeat(Math.max(0, 33 - summary.aiName.length))}${c.navy}║${c.reset}`);+ print(`${c.navy}║${c.reset} Timezone: ${c.white}${summary.timezone}${c.reset}${" ".repeat(Math.max(0, 33 - summary.timezone.length))}${c.navy}║${c.reset}`);+ print(`${c.navy}║${c.reset} Voice: ${c.white}${summary.voiceEnabled ? summary.voiceMode : "Disabled"}${c.reset}${" ".repeat(Math.max(0, 33 - (summary.voiceEnabled ? summary.voiceMode.length : 8)))}${c.navy}║${c.reset}`);+ print(`${c.navy}║${c.reset} Install Type: ${c.white}${installTypeLabel}${c.reset}${" ".repeat(Math.max(0, 33 - installTypeLabel.length))}${c.navy}║${c.reset}`);+ print(`${c.navy}╠══════════════════════════════════════════════════╣${c.reset}`);+ print(`${c.navy}║${c.reset} ${c.navy}║${c.reset}`);+ print(`${c.navy}║${c.reset} ${c.lightBlue}Run: ${c.bold}source ~/.zshrc && pai${c.reset} ${c.navy}║${c.reset}`);+ print(`${c.navy}║${c.reset} ${c.navy}║${c.reset}`);+ print(`${c.navy}╚══════════════════════════════════════════════════╝${c.reset}`);+ print("");+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/index.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/index.tsnew file mode 100644index 00000000..4b5c5bad--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/index.ts@@ -0,0 +1,325 @@+/**+ * PAI Installer v5.0 — CLI Wizard+ * Interactive command-line installation experience.+ */++import type { EngineEvent, InstallState, StepId } from "../engine/types";+import { STEPS, getProgress } from "../engine/steps";+import {+ createFreshState,+ hasSavedState,+ loadState,+ saveState,+ clearState,+ completeStep,+} from "../engine/state";+import {+ runSystemDetect,+ runPrerequisites,+ runApiKeys,+ runIdentity,+ runRepository,+ runConfiguration,+ runVoiceSetup,+ runTelegramSetup,+} from "../engine/actions";+import { runValidation, generateSummary } from "../engine/validate";+import {+ printBanner,+ printStep,+ printSectionHeader,+ printDetection,+ printValidation,+ printSummary,+ print,+ printSuccess,+ printError,+ printWarning,+ printInfo,+ progressBar,+ c,+} from "./display";+import { promptText, promptSecret, promptChoice, promptChoiceWithPreview, promptConfirm } from "./prompts";++type CLIChoice = {+ label: string;+ value: string;+ description?: string;+ voiceId?: string;+};++async function previewVoiceViaPulse(+ choice: { label: string; value: string; voiceId?: string },+ previewText: string+): Promise<void> {+ if (!choice.voiceId) {+ throw new Error("no preview available");+ }++ try {+ const response = await fetch("http://localhost:31337/notify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ message: previewText,+ voice_id: choice.voiceId,+ voice_settings: { stability: 0.35, similarity_boost: 0.80, style: 0.90, speed: 1.1 },+ }),+ signal: AbortSignal.timeout(8000),+ });++ if (!response.ok) {+ throw new Error(response.statusText ? `${response.status} ${response.statusText}` : `HTTP ${response.status}`);+ }+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ throw new Error(reason);+ }+}++/**+ * Handle engine events in CLI mode.+ */+function createEventHandler(): (event: EngineEvent) => void {+ return (event: EngineEvent) => {+ switch (event.event) {+ case "step_start":+ // Handled by the main loop with printStep+ break;+ case "section_header":+ printSectionHeader(event.title, event.subtitle, event.stepNumber);+ break;+ case "step_complete":+ printSuccess("Step complete");+ break;+ case "step_skip":+ printInfo(`Skipped: ${event.reason}`);+ break;+ case "step_error":+ printError(`Error: ${event.error}`);+ break;+ case "progress":+ print(` ${progressBar(event.percent)} ${c.gray}${event.detail}${c.reset}`);+ break;+ case "message":+ print(`\n ${event.content}\n`);+ break;+ case "error":+ printError(event.message);+ break;+ }+ };+}++/**+ * CLI input adapter — bridges engine's input requests to readline prompts.+ */+async function getInput(+ id: string,+ prompt: string,+ type: "text" | "password" | "key",+ placeholder?: string,+ daName?: string+): Promise<string> {+ if (type === "key" || type === "password") {+ return promptSecret(prompt, placeholder, daName);+ }+ return promptText(prompt, placeholder, daName);+}++/**+ * CLI choice adapter.+ */+async function getChoice(+ id: string,+ prompt: string,+ choices: CLIChoice[],+ daName?: string+): Promise<string> {+ return promptChoice(prompt, choices, daName);+}++async function getChoiceWithPreview(+ id: string,+ prompt: string,+ choices: CLIChoice[],+ previewText: string,+ daName?: string+): Promise<string> {+ return promptChoiceWithPreview(+ prompt,+ choices,+ async (choice) => previewVoiceViaPulse(choice, previewText),+ daName+ );+}++/**+ * Run the full CLI installation wizard.+ */+export async function runCLI(): Promise<void> {+ printBanner();++ const emit = createEventHandler();++ // Check for resume+ let state: InstallState;++ if (hasSavedState()) {+ const saved = loadState();+ if (saved) {+ print(` ${c.yellow}Found previous installation in progress.${c.reset}`);+ print(` ${c.gray}Started: ${saved.startedAt}${c.reset}`);+ print(` ${c.gray}Progress: ${getProgress(saved)}% (${saved.completedSteps.length} steps completed)${c.reset}`);+ print("");++ const resume = await promptConfirm("Resume previous installation?");+ if (resume) {+ state = saved;+ state.mode = "cli";+ print(`\n ${c.green}Resuming from step: ${state.currentStep}${c.reset}\n`);+ } else {+ state = createFreshState("cli");+ }+ } else {+ state = createFreshState("cli");+ }+ } else {+ state = createFreshState("cli");+ }++ try {+ // ── Step 1: System Detection ──+ if (!state.completedSteps.includes("system-detect")) {+ const step = STEPS[0];+ printStep(step.number, 9, step.name);+ const detection = await runSystemDetect(state, emit, getChoice);+ printDetection(detection);+ completeStep(state, "system-detect");+ state.currentStep = "prerequisites";+ }++ // ── Step 2: Prerequisites ──+ if (!state.completedSteps.includes("prerequisites")) {+ const step = STEPS[1];+ printStep(step.number, 9, step.name);+ await runPrerequisites(state, emit);+ completeStep(state, "prerequisites");+ state.currentStep = "api-keys";+ }++ // ── Step 3: API Keys ──+ if (!state.completedSteps.includes("api-keys")) {+ const step = STEPS[2];+ printStep(step.number, 9, step.name);+ await runApiKeys(state, emit, getInput, getChoice);+ completeStep(state, "api-keys");+ state.currentStep = "identity";+ }++ // ── Step 4: Identity ──+ if (!state.completedSteps.includes("identity")) {+ const step = STEPS[3];+ printStep(step.number, 9, step.name);+ await runIdentity(state, emit, getInput);+ completeStep(state, "identity");+ state.currentStep = "repository";+ }++ // ── Step 5: Repository ──+ if (!state.completedSteps.includes("repository")) {+ const step = STEPS[4];+ printStep(step.number, 9, step.name);+ await runRepository(state, emit);+ completeStep(state, "repository");+ state.currentStep = "configuration";+ }++ // ── Step 6: Configuration ──+ if (!state.completedSteps.includes("configuration")) {+ const step = STEPS[5];+ printStep(step.number, 9, step.name);+ await runConfiguration(state, emit);+ completeStep(state, "configuration");+ state.currentStep = "voice";+ }++ // ── Step 7: Voice ──+ if (!state.completedSteps.includes("voice") && !state.skippedSteps.includes("voice")) {+ const step = STEPS[6];+ printStep(step.number, 9, step.name);+ await runVoiceSetup(state, emit, getChoice, getInput, getChoiceWithPreview);+ completeStep(state, "voice");+ state.currentStep = "telegram";+ }++ // ── Step 8: Telegram (optional) ──+ if (!state.completedSteps.includes("telegram") && !state.skippedSteps.includes("telegram")) {+ const step = STEPS[7];+ printStep(step.number, 9, step.name);+ await runTelegramSetup(state, emit, getChoice, getInput);+ // runTelegramSetup either completes or marks the step skipped internally;+ // ensure something is recorded so the loop advances.+ if (!state.completedSteps.includes("telegram") && !state.skippedSteps.includes("telegram")) {+ completeStep(state, "telegram");+ }+ state.currentStep = "validation";+ }++ // ── Step 9: Validation ──+ if (!state.completedSteps.includes("validation")) {+ const step = STEPS[8];+ printStep(step.number, 9, step.name);++ const checks = await runValidation(state, emit);+ printValidation(checks);++ const allCritical = checks.filter((c) => c.critical).every((c) => c.passed);+ if (allCritical) {+ completeStep(state, "validation");+ } else {+ printError("\nSome critical checks failed. Please review and fix the issues above.");+ }+ }++ // ── Summary ──+ const summary = generateSummary(state);+ printSummary(summary);++ // Clean up state file on success+ clearState();++ print(` ${c.green}${c.bold}Installation complete!${c.reset}`);+ print("");+ print(` ${c.lightBlue}${c.bold}You have a working PAI, but it's a generic shell.${c.reset}`);+ print(` ${c.gray}To make it ${c.bold}yours${c.reset}${c.gray}, you tell it who you are, what you're working on,${c.reset}`);+ print(` ${c.gray}and how you think. Two paths to do that:${c.reset}`);+ print("");+ print(` ${c.lightBlue}${c.bold}Fast path — let the DA interview you:${c.reset}`);+ print(` ${c.gray}1.${c.reset} Run ${c.bold}source ~/.zshrc && pai${c.reset}${c.gray} to launch PAI.${c.reset}`);+ print(` ${c.gray}2.${c.reset} Type ${c.bold}/interview${c.reset}${c.gray} — the DA walks through TELOS, identity, projects, preferences. Pause and resume anytime.${c.reset}`);+ print(` ${c.gray}(Already have goals/journals/notes in Obsidian, Notion, etc.? Run the ${c.bold}Migrate${c.reset}${c.gray} skill first so the interview fills gaps instead of asking you to re-type.)${c.reset}`);+ print("");+ print(` ${c.lightBlue}${c.bold}Manual path — edit the files yourself:${c.reset}`);+ print(` ${c.gray}Each subdirectory under ~/.claude/PAI/USER/ has a README.md explaining what goes inside and how to customize it.${c.reset}`);+ print(` ${c.gray}Start with:${c.reset}`);+ print(` ${c.bold}~/.claude/PAI/USER/README.md${c.reset} ${c.gray}— full layout map${c.reset}`);+ print(` ${c.bold}~/.claude/PAI/USER/TELOS/README.md${c.reset} ${c.gray}— missions, goals, problems, strategies${c.reset}`);+ print(` ${c.bold}~/.claude/PAI/USER/DA/README.md${c.reset} ${c.gray}— your DA's identity, voice, personality${c.reset}`);+ print(` ${c.bold}~/.claude/PAI/USER/PROJECTS/README.md${c.reset} ${c.gray}— project registry + routing aliases${c.reset}`);+ print(` ${c.bold}~/.claude/PAI/USER/SECURITY/README.md${c.reset} ${c.gray}— bash/path rules (already has working defaults)${c.reset}`);+ print(` ${c.bold}~/.claude/PAI/USER/Config/README.md${c.reset} ${c.gray}— credentials and PAI config${c.reset}`);+ print("");+ print(` ${c.lightBlue}${c.bold}While you're here:${c.reset}`);+ print(` ${c.gray}•${c.reset} Visit the Life Dashboard at ${c.bold}http://localhost:31337${c.reset}${c.gray} (Pulse).${c.reset}`);+ print(` ${c.gray}•${c.reset} Anything you write under ${c.bold}PAI/USER/${c.reset}${c.gray} stays on your machine — it never ships in any PAI release.${c.reset}`);+ print("");++ process.exit(0);+ } catch (error: any) {+ printError(`\nInstallation failed: ${error.message}`);+ printInfo("Your progress has been saved. Run the installer again to resume.");+ saveState(state);+ process.exit(1);+ }+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/prompts.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/prompts.tsnew file mode 100644index 00000000..3a171d0a--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/cli/prompts.ts@@ -0,0 +1,224 @@+/**+ * PAI Installer v5.0 — CLI Interactive Prompts+ * readline-based input collection with proper cleanup.+ *+ * Non-interactive mode: when PAI_TEST_AUTOMATED=1 or stdin is not a TTY+ * (CI, ssh-without-tty, headless test harnesses), every prompt returns the+ * documented sensible default without ever touching readline. This keeps+ * the wizard runnable end-to-end from automation.+ */++import * as readline from "readline";+import { c, print, printError, printQuestion, printWarning } from "./display";++const ANSWER_PREFIX = ` ${c.green}❯ you:${c.reset} `;++type PromptChoiceOption = {+ label: string;+ value: string;+ description?: string;+ voiceId?: string;+};++function isAutomated(): boolean {+ return process.env.PAI_TEST_AUTOMATED === "1" || process.stdin.isTTY === false;+}++/**+ * Prompt for text input with optional default value.+ *+ * In automated mode we return an empty string and let the caller's own+ * fallback ("User", "PAI", etc.) take effect. The `defaultValue` here is+ * really a UI placeholder hint ("Your name", "e.g., Atlas, Nova, Sage"),+ * NOT a sensible install-time default — returning it as the answer+ * persisted those literal hint strings into settings.json on automated+ * runs.+ */+export async function promptText(+ question: string,+ defaultValue?: string,+ daName?: string+): Promise<string> {+ if (isAutomated()) return "";++ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ const defaultHint = defaultValue ? ` ${c.gray}(default: ${defaultValue})${c.reset}` : "";++ printQuestion(question + defaultHint, daName);+ return new Promise<string>((resolve) => {+ rl.question(ANSWER_PREFIX, (answer) => {+ rl.close();+ resolve(answer.trim() || defaultValue || "");+ });+ });+}++/**+ * Prompt for a password/key (masked input).+ */+export async function promptSecret(+ question: string,+ placeholder?: string,+ daName?: string+): Promise<string> {+ if (isAutomated()) return "";++ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ const hint = placeholder ? ` ${c.gray}(${placeholder})${c.reset}` : "";++ printQuestion(question + hint + `\n${c.dim}(input will be visible — paste your key)${c.reset}`, daName);+ return new Promise<string>((resolve) => {+ rl.question(ANSWER_PREFIX, (answer) => {+ rl.close();+ resolve(answer.trim());+ });+ });+}++/**+ * Prompt for a choice from a list.+ */+export async function promptChoice(+ question: string,+ choices: PromptChoiceOption[],+ daName?: string+): Promise<string> {+ if (isAutomated()) return choices[0]?.value ?? "";++ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ printQuestion(question, daName);+ for (let i = 0; i < choices.length; i++) {+ const choice = choices[i];+ print(` ${c.blue}${i + 1})${c.reset} ${c.bold}${choice.label}${c.reset}${choice.description ? ` ${c.gray}— ${choice.description}${c.reset}` : ""}`);+ }++ return new Promise<string>((resolve) => {+ rl.question(ANSWER_PREFIX, (answer) => {+ rl.close();+ const idx = parseInt(answer.trim()) - 1;+ if (idx >= 0 && idx < choices.length) {+ resolve(choices[idx].value);+ } else {+ // Default to first choice+ resolve(choices[0].value);+ }+ });+ });+}++export async function promptChoiceWithPreview(+ question: string,+ choices: { label: string; value: string; description?: string; voiceId?: string }[],+ onPreview: (choice: { label: string; value: string; voiceId?: string }) => Promise<void>,+ daName?: string,+): Promise<string> {+ if (isAutomated()) return choices[0]?.value ?? "";++ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ const ask = (prompt: string): Promise<string> => new Promise((resolve) => {+ rl.question(prompt, resolve);+ });++ printQuestion(question, daName);+ for (let i = 0; i < choices.length; i++) {+ const choice = choices[i];+ print(` ${c.lightBlue}┌────────────────────────────────────────────────────────────┐${c.reset}`);+ print(` ${c.lightBlue}│${c.reset} ${c.blue}${i + 1})${c.reset} ${c.bold}${choice.label}${c.reset}${choice.voiceId ? ` ${c.gray}— ${choice.voiceId}${c.reset}` : ""}`);+ if (choice.description) {+ print(` ${c.lightBlue}│${c.reset} ${c.gray}${choice.description}${c.reset}`);+ }+ print(` ${c.lightBlue}│${c.reset} ${choice.voiceId ? `${c.lightBlue}▶ p${i + 1} to preview${c.reset}` : `${c.gray}No preview available${c.reset}`}`);+ print(` ${c.lightBlue}└────────────────────────────────────────────────────────────┘${c.reset}`);+ }++ try {+ while (true) {+ const trimmed = (await ask(ANSWER_PREFIX)).trim();++ if (trimmed === "") {+ continue;+ }++ const selectedMatch = /^(\d+)$/.exec(trimmed);+ if (selectedMatch) {+ const idx = parseInt(selectedMatch[1], 10) - 1;+ if (idx >= 0 && idx < choices.length) {+ return choices[idx].value;+ }+ printWarning(`pick a number between 1 and ${choices.length}`);+ continue;+ }++ const previewMatch = /^p(\d+)$/i.exec(trimmed);+ if (previewMatch) {+ const idx = parseInt(previewMatch[1], 10) - 1;+ if (idx < 0 || idx >= choices.length) {+ printWarning(`preview number must be between 1 and ${choices.length}`);+ continue;+ }++ const choice = choices[idx];+ if (!choice.voiceId) {+ printWarning("no preview available");+ continue;+ }++ try {+ await onPreview({ label: choice.label, value: choice.value, voiceId: choice.voiceId });+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ printError(`preview unavailable: ${reason}`);+ }+ continue;+ }++ printWarning(`didn't understand ${trimmed}`);+ }+ } finally {+ rl.close();+ }+}++/**+ * Prompt for yes/no confirmation.+ */+export async function promptConfirm(+ question: string,+ defaultYes: boolean = true,+ daName?: string+): Promise<boolean> {+ if (isAutomated()) return defaultYes;++ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ const hint = defaultYes ? `${c.gray}(Y/n)${c.reset}` : `${c.gray}(y/N)${c.reset}`;++ printQuestion(`${question} ${hint}`, daName);+ return new Promise<boolean>((resolve) => {+ rl.question(ANSWER_PREFIX, (answer) => {+ rl.close();+ const val = answer.trim().toLowerCase();+ if (val === "") resolve(defaultYes);+ else resolve(val === "y" || val === "yes");+ });+ });+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/main.js b/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/main.jsnew file mode 100644index 00000000..e5c0d38d--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/main.js@@ -0,0 +1,149 @@+/**+ * PAI Installer — Electron Wrapper+ * Spawns the Bun web server, then opens a frameless window.+ * Audio autoplay is enabled (no browser restrictions).+ */++const { app, BrowserWindow } = require("electron");+const { spawn } = require("child_process");+const path = require("path");+const net = require("net");++// Force autoplay at the Chromium level (belt + suspenders with webPreferences)+app.commandLine.appendSwitch("autoplay-policy", "no-user-gesture-required");++const PORT = parseInt(process.env.PAI_INSTALL_PORT || "1337");+const INSTALLER_DIR = path.resolve(__dirname, "..");++let serverProcess = null;+let mainWindow = null;++// ─── Single Instance Lock ────────────────────────────────────────+// Prevents launching 20 copies of the installer++const gotLock = app.requestSingleInstanceLock();+if (!gotLock) {+ app.quit();+} else {+ app.on("second-instance", () => {+ if (mainWindow) {+ if (mainWindow.isMinimized()) mainWindow.restore();+ mainWindow.focus();+ }+ });+}++// ─── Wait for server to be ready ─────────────────────────────────++function waitForServer(port, timeout = 15000) {+ const start = Date.now();+ return new Promise((resolve, reject) => {+ function tryConnect() {+ if (Date.now() - start > timeout) {+ return reject(new Error("Server start timeout"));+ }+ const socket = new net.Socket();+ socket.setTimeout(500);+ socket.once("connect", () => {+ socket.destroy();+ resolve();+ });+ socket.once("error", () => {+ socket.destroy();+ setTimeout(tryConnect, 200);+ });+ socket.once("timeout", () => {+ socket.destroy();+ setTimeout(tryConnect, 200);+ });+ socket.connect(port, "127.0.0.1");+ }+ tryConnect();+ });+}++// ─── Start Bun server ────────────────────────────────────────────++function startServer() {+ const mainTs = path.join(INSTALLER_DIR, "main.ts");+ serverProcess = spawn("bun", ["run", mainTs, "--mode", "web"], {+ cwd: INSTALLER_DIR,+ env: { ...process.env, PAI_INSTALL_PORT: String(PORT) },+ stdio: ["ignore", "pipe", "pipe"],+ });++ serverProcess.stdout.on("data", (data) => {+ process.stdout.write(data);+ });++ serverProcess.stderr.on("data", (data) => {+ process.stderr.write(data);+ });++ serverProcess.on("error", (err) => {+ console.error("Failed to start server:", err.message);+ app.quit();+ });++ serverProcess.on("exit", (code) => {+ if (code !== 0 && code !== null) {+ console.error(`Server exited with code ${code}`);+ }+ });+}++// ─── Create Window ───────────────────────────────────────────────++function createWindow() {+ mainWindow = new BrowserWindow({+ width: 1280,+ height: 820,+ minWidth: 900,+ minHeight: 600,+ backgroundColor: "#0f0f14",+ title: "PAI Installer",+ autoHideMenuBar: true,+ webPreferences: {+ autoplayPolicy: "no-user-gesture-required",+ nodeIntegration: false,+ contextIsolation: true,+ },+ });++ mainWindow.loadURL(`http://127.0.0.1:${PORT}/`);++ mainWindow.on("closed", () => {+ mainWindow = null;+ });+}++// ─── App Lifecycle ───────────────────────────────────────────────++app.whenReady().then(async () => {+ startServer();++ try {+ await waitForServer(PORT);+ } catch (err) {+ console.error("Could not start installer server:", err.message);+ app.quit();+ return;+ }++ createWindow();+});++app.on("window-all-closed", () => {+ if (serverProcess) {+ serverProcess.kill();+ serverProcess = null;+ }+ app.quit();+});++app.on("before-quit", () => {+ if (serverProcess) {+ serverProcess.kill();+ serverProcess = null;+ }+});diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/package-lock.json b/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/package-lock.jsonnew file mode 100644index 00000000..5eee08e2--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/package-lock.json@@ -0,0 +1,801 @@+{+ "name": "pai-installer",+ "version": "3.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "pai-installer",+ "version": "3.0.0",+ "dependencies": {+ "electron": "^34.0.0"+ }+ },+ "node_modules/@electron/get": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-2.0.3.tgz",+ "integrity": "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "env-paths": "^2.2.0",+ "fs-extra": "^8.1.0",+ "got": "^11.8.5",+ "progress": "^2.0.3",+ "semver": "^6.2.0",+ "sumchecker": "^3.0.1"+ },+ "engines": {+ "node": ">=12"+ },+ "optionalDependencies": {+ "global-agent": "^3.0.0"+ }+ },+ "node_modules/@sindresorhus/is": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",+ "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@szmarczak/http-timer": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",+ "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",+ "license": "MIT",+ "dependencies": {+ "defer-to-connect": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@types/cacheable-request": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",+ "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==",+ "license": "MIT",+ "dependencies": {+ "@types/http-cache-semantics": "*",+ "@types/keyv": "^3.1.4",+ "@types/node": "*",+ "@types/responselike": "^1.0.0"+ }+ },+ "node_modules/@types/http-cache-semantics": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",+ "integrity": "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==",+ "license": "MIT"+ },+ "node_modules/@types/keyv": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",+ "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/node": {+ "version": "20.19.33",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.33.tgz",+ "integrity": "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/responselike": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz",+ "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/yauzl": {+ "version": "2.10.3",+ "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",+ "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/boolean": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",+ "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",+ "license": "MIT",+ "optional": true+ },+ "node_modules/buffer-crc32": {+ "version": "0.2.13",+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",+ "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",+ "license": "MIT",+ "engines": {+ "node": "*"+ }+ },+ "node_modules/cacheable-lookup": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",+ "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",+ "license": "MIT",+ "engines": {+ "node": ">=10.6.0"+ }+ },+ "node_modules/cacheable-request": {+ "version": "7.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",+ "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",+ "license": "MIT",+ "dependencies": {+ "clone-response": "^1.0.2",+ "get-stream": "^5.1.0",+ "http-cache-semantics": "^4.0.0",+ "keyv": "^4.0.0",+ "lowercase-keys": "^2.0.0",+ "normalize-url": "^6.0.1",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/clone-response": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",+ "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^3.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/decompress-response/node_modules/mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/defer-to-connect": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",+ "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/define-data-property": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0",+ "es-errors": "^1.3.0",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/define-properties": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-data-property": "^1.0.1",+ "has-property-descriptors": "^1.0.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/detect-node": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",+ "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/electron": {+ "version": "34.5.8",+ "resolved": "https://registry.npmjs.org/electron/-/electron-34.5.8.tgz",+ "integrity": "sha512-vxLD65mabTzYmEVa9KceMHM0+zO+vqgrhcyNVlmTd0IGV5J7XZ8v/qElm0o4YQ4wPeq7olZkUjZkBQQEdr23/g==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "@electron/get": "^2.0.0",+ "@types/node": "^20.9.0",+ "extract-zip": "^2.0.1"+ },+ "bin": {+ "electron": "cli.js"+ },+ "engines": {+ "node": ">= 12.20.55"+ }+ },+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },+ "node_modules/env-paths": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",+ "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es6-error": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",+ "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/extract-zip": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",+ "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "debug": "^4.1.1",+ "get-stream": "^5.1.0",+ "yauzl": "^2.10.0"+ },+ "bin": {+ "extract-zip": "cli.js"+ },+ "engines": {+ "node": ">= 10.17.0"+ },+ "optionalDependencies": {+ "@types/yauzl": "^2.9.1"+ }+ },+ "node_modules/fd-slicer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",+ "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",+ "license": "MIT",+ "dependencies": {+ "pend": "~1.2.0"+ }+ },+ "node_modules/fs-extra": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",+ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^4.0.0",+ "universalify": "^0.1.0"+ },+ "engines": {+ "node": ">=6 <7 || >=8"+ }+ },+ "node_modules/get-stream": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",+ "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",+ "license": "MIT",+ "dependencies": {+ "pump": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/global-agent": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",+ "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "es6-error": "^4.1.1",+ "matcher": "^3.0.0",+ "roarr": "^2.15.3",+ "semver": "^7.3.2",+ "serialize-error": "^7.0.1"+ },+ "engines": {+ "node": ">=10.0"+ }+ },+ "node_modules/global-agent/node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "license": "ISC",+ "optional": true,+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/globalthis": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-properties": "^1.2.1",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/got": {+ "version": "11.8.6",+ "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz",+ "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==",+ "license": "MIT",+ "dependencies": {+ "@sindresorhus/is": "^4.0.0",+ "@szmarczak/http-timer": "^4.0.5",+ "@types/cacheable-request": "^6.0.1",+ "@types/responselike": "^1.0.0",+ "cacheable-lookup": "^5.0.3",+ "cacheable-request": "^7.0.2",+ "decompress-response": "^6.0.0",+ "http2-wrapper": "^1.0.0-beta.5.2",+ "lowercase-keys": "^2.0.0",+ "p-cancelable": "^2.0.0",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/got?sponsor=1"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "license": "ISC"+ },+ "node_modules/has-property-descriptors": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/http-cache-semantics": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",+ "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",+ "license": "BSD-2-Clause"+ },+ "node_modules/http2-wrapper": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz",+ "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==",+ "license": "MIT",+ "dependencies": {+ "quick-lru": "^5.1.1",+ "resolve-alpn": "^1.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ }+ },+ "node_modules/json-buffer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",+ "license": "MIT"+ },+ "node_modules/json-stringify-safe": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",+ "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",+ "license": "ISC",+ "optional": true+ },+ "node_modules/jsonfile": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",+ "license": "MIT",+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/keyv": {+ "version": "4.5.4",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",+ "license": "MIT",+ "dependencies": {+ "json-buffer": "3.0.1"+ }+ },+ "node_modules/lowercase-keys": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",+ "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/matcher": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",+ "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "escape-string-regexp": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/mimic-response": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",+ "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/normalize-url": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",+ "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/object-keys": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/p-cancelable": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",+ "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/pend": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",+ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",+ "license": "MIT"+ },+ "node_modules/progress": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/pump": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz",+ "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==",+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },+ "node_modules/quick-lru": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",+ "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/resolve-alpn": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",+ "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==",+ "license": "MIT"+ },+ "node_modules/responselike": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",+ "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",+ "license": "MIT",+ "dependencies": {+ "lowercase-keys": "^2.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/roarr": {+ "version": "2.15.4",+ "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",+ "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "detect-node": "^2.0.4",+ "globalthis": "^1.0.1",+ "json-stringify-safe": "^5.0.1",+ "semver-compare": "^1.0.0",+ "sprintf-js": "^1.1.2"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/semver-compare": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",+ "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/serialize-error": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",+ "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "type-fest": "^0.13.1"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/sprintf-js": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",+ "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",+ "license": "BSD-3-Clause",+ "optional": true+ },+ "node_modules/sumchecker": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",+ "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",+ "license": "Apache-2.0",+ "dependencies": {+ "debug": "^4.1.0"+ },+ "engines": {+ "node": ">= 8.0"+ }+ },+ "node_modules/type-fest": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",+ "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",+ "license": "(MIT OR CC0-1.0)",+ "optional": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "license": "MIT"+ },+ "node_modules/universalify": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",+ "license": "MIT",+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/yauzl": {+ "version": "2.10.0",+ "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",+ "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",+ "license": "MIT",+ "dependencies": {+ "buffer-crc32": "~0.2.3",+ "fd-slicer": "~1.1.0"+ }+ }+ }+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/package.json b/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/package.jsonnew file mode 100644index 00000000..3b0bdd58--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/electron/package.json@@ -0,0 +1,12 @@+{+ "name": "pai-installer",+ "version": "5.0.0",+ "description": "PAI Installer — Electron wrapper",+ "main": "main.js",+ "scripts": {+ "start": "electron ."+ },+ "dependencies": {+ "electron": "^34.5.8"+ }+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/actions.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/actions.tsnew file mode 100644index 00000000..b0ecb383--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/actions.ts@@ -0,0 +1,2337 @@+/**+ * PAI Installer v5.0 — Install Actions+ * Pure action functions called by both CLI and web frontends.+ * Each action takes state + event emitter, performs work, returns result.+ */++import { execSync, spawn } from "child_process";+import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, symlinkSync, unlinkSync, chmodSync, lstatSync, cpSync, rmSync, readlinkSync } from "fs";+import { homedir } from "os";+import { join, basename, dirname } from "path";+import type { InstallState, EngineEventHandler, DetectionResult, ExistingUserContentDetection, StepId } from "./types";+import { PAI_VERSION, ALGORITHM_VERSION, DEFAULT_VOICES } from "./types";+import { detectSystem, detectExistingUserContent, scanApiKeys, validateElevenLabsKey } from "./detect";+import { generateSettingsJson } from "./config-gen";++type ChoiceOption = {+ label: string;+ value: string;+ description?: string;+ voiceId?: string;+};++type InputPrompt = (+ id: string,+ prompt: string,+ type: "text" | "password" | "key",+ placeholder?: string,+ daName?: string+) => Promise<string>;++type ChoicePrompt = (+ id: string,+ prompt: string,+ choices: ChoiceOption[],+ daName?: string+) => Promise<string>;++type ChoicePreviewPrompt = (+ id: string,+ prompt: string,+ choices: ChoiceOption[],+ previewText: string,+ daName?: string+) => Promise<string>;++const PLACEHOLDER_LITERALS = new Set([+ "Your name",+ "e.g., Atlas, Nova, Sage",+ "Ready to go",+ "User",+ "PAI",+]);++const USER_MIGRATION_IDENTITY_FILES = [+ "PRINCIPAL_IDENTITY.md",+ "DA_IDENTITY.md",+ "DA_IDENTITY.yaml",+] as const;++const USER_MIGRATION_FULL_ENTRIES = [+ "TELOS",+ "CONTACTS.md",+ "OPINIONS.md",+ "PROJECTS",+ "BUSINESS",+ "FINANCES",+ "HEALTH",+ "WORKINGSTYLE.md",+ "RHETORICALSTYLE.md",+ "AI_WRITING_PATTERNS.md",+ "FEED.md",+ "RESUME.md",+ "OUR_STORY.md",+ "DEFINITIONS.md",+ "CORECONTENT.md",+ "BELIEFS.md",+] as const;++function isPlaceholderValue(value: string): boolean {+ return /^\{.+\}$/.test(value) || /^e\.g\./i.test(value.trim()) || PLACEHOLDER_LITERALS.has(value.trim());+}++function computeBackupPath(home: string): string {+ const ts = new Date().toISOString().replace(/[:.]/g, "-");+ return join(home, `.claude.backup-${ts}`);+}++async function emitSectionHeader(+ emit: EngineEventHandler,+ sectionId: string,+ title: string,+ subtitle?: string,+ stepNumber?: number+): Promise<void> {+ await emit({ event: "section_header", sectionId, title, subtitle, stepNumber });+}++function summariseExistingUserContent(content: ExistingUserContentDetection): string {+ const telosParts: string[] = [];+ if (content.telos.mission) telosParts.push("MISSION ✓");+ if (content.telos.goals) {+ const goalsSuffix = content.telos.goalsCount > 0 ? ` (${content.telos.goalsCount} entries)` : "";+ telosParts.push(`GOALS ✓${goalsSuffix}`);+ }+ if (content.telos.activeProblems) telosParts.push("ACTIVE_PROBLEMS ✓");+ if (content.telos.strategy) telosParts.push("STRATEGY ✓");+ if (content.telos.principles) telosParts.push("PRINCIPLES ✓");+ if (content.telos.areas) telosParts.push("AREAS ✓");+ if (content.telos.now) telosParts.push("NOW ✓");++ const identityParts: string[] = [];+ if (content.identity.principalIdentity) identityParts.push("PRINCIPAL_IDENTITY ✓");+ if (content.identity.daIdentity) identityParts.push("DA_IDENTITY ✓");+ if (content.identity.daIdentityYaml) identityParts.push("DA_IDENTITY.yaml ✓");+ if (content.identity.workingStyle) identityParts.push("WORKINGSTYLE ✓");+ if (content.identity.rhetoricalStyle) identityParts.push("RHETORICALSTYLE ✓");+ if (content.identity.aiWritingPatterns) identityParts.push("AI_WRITING_PATTERNS ✓");+ if (content.identity.feed) identityParts.push("FEED ✓");+ if (content.identity.resume) identityParts.push("RESUME ✓");+ if (content.identity.ourStory) identityParts.push("OUR_STORY ✓");+ if (content.identity.definitions) identityParts.push("DEFINITIONS ✓");+ if (content.identity.coreContent) identityParts.push("CORECONTENT ✓");+ if (content.identity.beliefs) identityParts.push("BELIEFS ✓");++ const sections: string[] = [];+ if (telosParts.length > 0) sections.push(`TELOS: ${telosParts.join(", ")}`);+ if (identityParts.length > 0) sections.push(`IDENTITY: ${identityParts.join(", ")}`);+ if (content.contacts.contacts) {+ const contactsSuffix = content.contacts.count > 0 ? ` (${content.contacts.count} entries)` : "";+ sections.push(`CONTACTS: CONTACTS.md ✓${contactsSuffix}`);+ }+ if (content.opinions.opinions) sections.push("OPINIONS: OPINIONS.md ✓");+ if (content.projects.projectsIndex || content.projects.projectsDirectory) {+ const projectBits: string[] = [];+ if (content.projects.projectsIndex) {+ const projectCountSuffix = content.projects.count > 0 ? ` (${content.projects.count} entries)` : "";+ projectBits.push(`PROJECTS.md ✓${projectCountSuffix}`);+ }+ if (content.projects.projectsDirectory) projectBits.push("PROJECTS/ ✓");+ sections.push(`PROJECTS: ${projectBits.join(", ")}`);+ }+ if (content.business.present) sections.push("BUSINESS: present ✓");+ if (content.finances.present) sections.push("FINANCES: present ✓");+ if (content.health.present) sections.push("HEALTH: present ✓");++ return sections.join(" | ");+}++/**+ * Remove duplicate bun PATH entries from shell config.+ * The bun.sh installer appends entries on every run — if install is+ * interrupted and retried, the config file accumulates duplicates.+ * Fixes: https://github.com/danielmiessler/Personal_AI_Infrastructure/issues/954+ */+function deduplicateBunShellEntries(): void {+ const home = homedir();+ const shell = process.env.SHELL || "/bin/zsh";++ let rcFile: string;+ if (shell.includes("fish")) {+ rcFile = join(home, ".config", "fish", "config.fish");+ } else if (shell.includes("bash")) {+ rcFile = join(home, ".bashrc");+ } else {+ rcFile = join(home, ".zshrc");+ }++ if (!existsSync(rcFile)) return;++ try {+ const content = readFileSync(rcFile, "utf-8");++ // Match bun config blocks: "# bun" line followed by export/set lines+ const bunBlockPattern = shell.includes("fish")+ ? /\n?# bun\nset --export BUN_INSTALL "[^"]*"\nset --export PATH \$BUN_INSTALL\/bin \$PATH\n?/g+ : /\n?# bun\nexport BUN_INSTALL="[^"]*"\nexport PATH="?\$BUN_INSTALL\/bin:\$PATH"?\n?/g;++ const matches = content.match(bunBlockPattern);+ if (!matches || matches.length <= 1) return; // 0 or 1 block = nothing to deduplicate++ // Keep the first block, remove all subsequent duplicates+ let deduplicated = content;+ let firstFound = false;+ deduplicated = deduplicated.replace(bunBlockPattern, (match) => {+ if (!firstFound) {+ firstFound = true;+ return match; // Keep the first occurrence+ }+ return ""; // Remove duplicates+ });++ // Clean up any resulting double blank lines+ deduplicated = deduplicated.replace(/\n{3,}/g, "\n\n");++ if (deduplicated !== content) {+ writeFileSync(rcFile, deduplicated, "utf-8");+ }+ } catch {+ // Non-critical — silently ignore errors+ }+}++/**+ * Read an env-style file and extract a key's value. Returns "" if missing.+ */+function readKeyFromFile(envPath: string, keyName: string): string {+ try {+ if (!existsSync(envPath)) return "";+ const content = readFileSync(envPath, "utf-8");+ const match = content.match(new RegExp(`^${keyName}=(.+)$`, "m"));+ return match && match[1].trim() ? match[1].trim() : "";+ } catch {+ return "";+ }+}++/**+ * Check primary key locations only — current process env, ~/.claude/.env,+ * ~/.config/PAI/.env. These are the user's own active install; no permission+ * prompt needed.+ */+function findExistingEnvKey(keyName: string): string {+ const home = homedir();+ const primary = [+ join(home, ".claude", ".env"),+ join(home, ".config", "PAI", ".env"),+ ];+ for (const envPath of primary) {+ const value = readKeyFromFile(envPath, keyName);+ if (value) return value;+ }+ return process.env[keyName] || "";+}++/**+ * List backup .claude* directories that have an .env containing the key.+ * Returns paths only — does NOT read or use the values until the caller+ * gets explicit user permission. Used by setupVoice to ask before scanning.+ */+function findKeyInBackupDirs(keyName: string): { path: string; value: string }[] {+ const home = homedir();+ const found: { path: string; value: string }[] = [];+ try {+ const homeEntries = readdirSync(home);+ for (const entry of homeEntries) {+ if (!entry.startsWith(".claude") || entry === ".claude") continue;+ for (const candidate of [+ join(home, entry, ".env"),+ join(home, entry, ".config", "PAI", ".env"),+ ]) {+ const value = readKeyFromFile(candidate, keyName);+ if (value) found.push({ path: candidate, value });+ }+ }+ } catch {+ // Permission errors on home listing — return what we have+ }+ return found;+}++/**+ * Inventory what existing PAI configuration is present on this machine,+ * WITHOUT importing anything. Read-only check used to decide whether to+ * ask the user permission before proceeding with import.+ *+ * Scope (deliberately narrow — the just-installed `~/.claude/` is excluded):+ * 1. `~/.config/PAI/.env` — PAI's canonical key store. Lives outside+ * `~/.claude/` so it survives `rm -rf ~/.claude` between installs.+ * This is where a prior install's key actually persists.+ * 2. ANY directory in `$HOME` whose name starts with `.claude` EXCEPT+ * `~/.claude/` itself — covers `.claude.bak`, `.claude-bak`,+ * `.claude.backup.20260101`, `.claude.previous`, `.claude_old`, etc.+ * Inside each, both `<dir>/.env` AND `<dir>/.config/PAI/.env` are+ * checked, plus `<dir>/settings.json` for the voice ID.+ *+ * The active `~/.claude/.env` and `~/.claude/settings.json` are NOT+ * inventoried — they're the install we just built, not prior state to ask+ * about importing. Returns a list of human-readable signals — a fresh+ * machine returns []. Any non-empty result triggers the upfront "may I+ * import?" prompt at the top of runVoiceSetup. The user must explicitly+ * opt in before any prior key or voice ID gets pulled into the new install.+ */+function inventoryExistingConfig(): { signals: string[] } {+ const home = homedir();+ const signals: string[] = [];+ // (1) `~/.config/PAI/.env` — outside `~/.claude/`, often holds the prior key.+ const configEnv = join(home, ".config", "PAI", ".env");+ if (readKeyFromFile(configEnv, "ELEVENLABS_API_KEY")) {+ signals.push(`ElevenLabs key in ${configEnv.replace(home, "~")}`);+ }+ // (2) Every `.claude*` directory in $HOME EXCEPT `~/.claude/` itself.+ // Pattern matches `.claude.bak`, `.claude-bak`, `.claude.backup.20260101`,+ // `.claude.previous`, `.claude_old`, `.claude20251215`, etc.+ try {+ for (const entry of readdirSync(home)) {+ if (!entry.startsWith(".claude") || entry === ".claude") continue;+ for (const candidate of [join(home, entry, ".env"), join(home, entry, ".config", "PAI", ".env")]) {+ if (readKeyFromFile(candidate, "ELEVENLABS_API_KEY")) {+ signals.push(`ElevenLabs key in ${candidate.replace(home, "~")}`);+ }+ }+ const settingsPath = join(home, entry, "settings.json");+ if (existsSync(settingsPath)) {+ try {+ const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));+ const voiceId = settings.daidentity?.voices?.main?.voiceId || settings.daidentity?.voiceId;+ if (voiceId && !/^\{.+\}$/.test(voiceId)) {+ signals.push(`voice ID in ${settingsPath.replace(home, "~")}`);+ }+ } catch { /* malformed settings.json — skip */ }+ }+ }+ } catch { /* permission errors on home listing — return what we have */ }+ return { signals };+}++/**+ * Search existing .claude directories for settings.json voice configuration.+ * Returns { voiceId, aiName, source } if found, or null.+ */+function findExistingVoiceConfig(): { voiceId: string; aiName: string; source: string } | null {+ const home = homedir();+ const candidates: string[] = [];++ // Primary location first+ candidates.push(join(home, ".claude", "settings.json"));++ // Scan all .claude* directories (backups, renamed, etc.)+ try {+ const homeEntries = readdirSync(home);+ for (const entry of homeEntries) {+ if (entry.startsWith(".claude") && entry !== ".claude") {+ candidates.push(join(home, entry, "settings.json"));+ }+ }+ } catch {+ // Ignore permission errors+ }++ for (const settingsPath of candidates) {+ try {+ if (!existsSync(settingsPath)) continue;+ const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));+ const voiceId = settings.daidentity?.voices?.main?.voiceId+ || settings.daidentity?.voiceId;+ if (voiceId && !/^\{.+\}$/.test(voiceId)) {+ const dirName = basename(join(settingsPath, ".."));+ return {+ voiceId,+ aiName: settings.daidentity?.name || "",+ source: dirName,+ };+ }+ } catch {+ // Ignore parse errors+ }+ }+ return null;+}++function tryExec(cmd: string, timeout = 30000): string | null {+ try {+ return execSync(cmd, { timeout, stdio: ["pipe", "pipe", "pipe"] }).toString().trim();+ } catch {+ return null;+ }+}++// ─── User Context Migration (v2.5/v3.0 → v5.x) ─────────────────+//+// In v2.5–v3.0, user context (ABOUTME.md, TELOS/, CONTACTS.md, etc.)+// lived at skills/PAI/USER/ (or skills/CORE/USER/ in v2.4).+// In v4.0, user context moved to PAI/USER/ and CONTEXT_ROUTING.md+// points there. But the installer never migrated existing files,+// leaving user data stranded at the old path while the new path+// stayed empty. This function copies user files to the canonical+// location and replaces the legacy directory with a symlink so+// both routing systems resolve to the same place.++/**+ * Recursively copy files from src to dst, skipping files that+ * already exist at the destination. Only copies regular files.+ */+function copyMissing(src: string, dst: string): number {+ let copied = 0;+ if (!existsSync(src)) return copied;++ const stat = lstatSync(src);+ if (stat.isFile()) {+ if (!existsSync(dst)) {+ try {+ mkdirSync(dirname(dst), { recursive: true });+ cpSync(src, dst);+ copied++;+ } catch {+ // Skip files that can't be copied (permission errors)+ }+ }+ return copied;+ }++ for (const entry of readdirSync(src, { withFileTypes: true })) {+ const srcPath = join(src, entry.name);+ const dstPath = join(dst, entry.name);++ if (entry.isDirectory()) {+ if (!existsSync(dstPath)) mkdirSync(dstPath, { recursive: true });+ copied += copyMissing(srcPath, dstPath);+ } else if (entry.isFile()) {+ if (!existsSync(dstPath)) {+ try {+ cpSync(srcPath, dstPath);+ copied++;+ } catch {+ // Skip files that can't be copied (permission errors)+ }+ }+ }+ }+ return copied;+}++function shouldOverwriteTemplateDestination(dstPath: string): boolean {+ if (!existsSync(dstPath)) return true;++ try {+ const stat = lstatSync(dstPath);+ if (!stat.isFile()) return false;+ if (stat.size === 0) return true;+ const content = readFileSync(dstPath, "utf-8");+ return (+ content.includes("{PRINCIPAL.NAME}") ||+ content.includes("{DA.NAME}") ||+ content.includes("Your name") ||+ content.includes("e.g., Atlas, Nova, Sage")+ );+ } catch {+ return false;+ }+}++function copyOverwriteTemplates(src: string, dst: string): { copied: number; failed: number } {+ const result = { copied: 0, failed: 0 };+ if (!existsSync(src)) return result;++ try {+ const srcStat = lstatSync(src);+ if (srcStat.isDirectory()) {+ if (!existsSync(dst)) mkdirSync(dst, { recursive: true });+ for (const entry of readdirSync(src, { withFileTypes: true })) {+ const child = copyOverwriteTemplates(join(src, entry.name), join(dst, entry.name));+ result.copied += child.copied;+ result.failed += child.failed;+ }+ return result;+ }++ if (!srcStat.isFile()) return result;+ if (!shouldOverwriteTemplateDestination(dst)) return result;+ mkdirSync(dirname(dst), { recursive: true });+ cpSync(src, dst);+ result.copied++;+ return result;+ } catch {+ result.failed++;+ return result;+ }+}++/**+ * Migrate user context from legacy skills/PAI/USER or skills/CORE/USER+ * to the canonical PAI/USER location. Replaces the legacy directory+ * with a symlink so the skill's relative USER/ paths still resolve.+ */+async function migrateUserContext(+ paiDir: string,+ emit: EngineEventHandler+): Promise<void> {+ const newUserDir = join(paiDir, "PAI", "USER");+ if (!existsSync(newUserDir)) return; // PAI/USER/ not set up yet++ const legacyPaths = [+ join(paiDir, "skills", "PAI", "USER"), // v2.5–v3.0+ join(paiDir, "skills", "CORE", "USER"), // v2.4 and earlier+ ];++ for (const legacyDir of legacyPaths) {+ if (!existsSync(legacyDir)) continue;++ // Skip if already a symlink (migration already ran)+ try {+ if (lstatSync(legacyDir).isSymbolicLink()) continue;+ } catch {+ continue;+ }++ const label = legacyDir.includes("CORE") ? "skills/CORE/USER" : "skills/PAI/USER";+ await emit({ event: "progress", step: "repository", percent: 70, detail: `Migrating user context from ${label}...` });++ const copied = copyMissing(legacyDir, newUserDir);+ if (copied > 0) {+ await emit({ event: "message", content: `Migrated ${copied} user context files from ${label} to PAI/USER.` });+ }++ // Replace legacy dir with symlink so skill-relative paths still work+ try {+ rmSync(legacyDir, { recursive: true });+ // Symlink target is relative: from skills/PAI/ or skills/CORE/ → ../../PAI/USER+ symlinkSync(join("..", "..", "PAI", "USER"), legacyDir);+ await emit({ event: "message", content: `Replaced ${label} with symlink to PAI/USER.` });+ } catch {+ await emit({ event: "message", content: `Could not replace ${label} with symlink. User files were copied but old directory remains.` });+ }+ }+}++function collectTopLevelExtraMarkdown(userDir: string, alreadyIncluded: Set<string>): string[] {+ if (!existsSync(userDir)) return [];++ try {+ return readdirSync(userDir, { withFileTypes: true })+ .filter((entry) => entry.isFile())+ .map((entry) => entry.name)+ .filter((name) => name.endsWith(".md"))+ .filter((name) => !alreadyIncluded.has(name))+ .filter((name) => ![".DS_Store"].includes(name));+ } catch {+ return [];+ }+}++function copyMigrationEntry(+ srcPath: string,+ dstPath: string+): { copied: number; failed: number } {+ const copiedMissing = copyMissing(srcPath, dstPath);+ const overwritten = copyOverwriteTemplates(srcPath, dstPath);+ return {+ copied: copiedMissing + overwritten.copied,+ failed: overwritten.failed,+ };+}++export async function migrateUserContentFromBackup(+ state: InstallState,+ emit: EngineEventHandler+): Promise<void> {+ if (!state.backupPath || state.collected.scanConsent === "no") return;++ const backupUserDir = join(state.backupPath, "PAI", "USER");+ if (!existsSync(backupUserDir)) {+ await emit({ event: "message", content: `No PAI/USER content found in backup at ${state.backupPath}.` });+ return;+ }++ const targetUserDir = join(state.detection?.paiDir || join(homedir(), ".claude"), "PAI", "USER");+ if (!existsSync(targetUserDir)) mkdirSync(targetUserDir, { recursive: true });++ const entries =+ state.collected.scanConsent === "yes-id"+ ? [...USER_MIGRATION_IDENTITY_FILES]+ : (() => {+ const included = new Set<string>([+ ...USER_MIGRATION_IDENTITY_FILES,+ ...USER_MIGRATION_FULL_ENTRIES,+ ]);+ return [+ ...USER_MIGRATION_IDENTITY_FILES,+ ...USER_MIGRATION_FULL_ENTRIES,+ ...collectTopLevelExtraMarkdown(backupUserDir, included),+ ];+ })();++ let totalCopied = 0;+ let totalFailed = 0;++ for (const entry of entries) {+ if (entry === ".git" || entry === "node_modules" || entry === ".DS_Store") continue;+ const srcPath = join(backupUserDir, entry);+ if (!existsSync(srcPath)) continue;++ const dstPath = join(targetUserDir, entry);+ const result = copyMigrationEntry(srcPath, dstPath);+ totalCopied += result.copied;+ totalFailed += result.failed;++ if (result.copied > 0) {+ const label = entry.endsWith(".md") || entry.endsWith(".yaml")+ ? `Migrated ${entry} from backup.`+ : `Migrated ${result.copied} files from ${entry}/.`;+ await emit({ event: "message", content: label });+ } else if (result.failed > 0) {+ await emit({ event: "message", content: `Could not migrate ${entry} from backup.` });+ }+ }++ const failureSuffix = totalFailed > 0 ? ` ${totalFailed} file${totalFailed === 1 ? "" : "s"} could not be copied.` : "";+ await emit({ event: "message", content: `Migrated ${totalCopied} files from backup to fresh install.${failureSuffix}` });+}++function pathLooksLikeExistingClaudeRoot(claudeDir: string): boolean {+ return existsSync(join(claudeDir, "settings.json")) || existsSync(join(claudeDir, "skills"));+}++export async function moveExistingClaudeToBackup(+ state: InstallState,+ emit: EngineEventHandler+): Promise<void> {+ if (!state.backupPath) return;++ const claudeDir = state.detection?.paiDir || join(homedir(), ".claude");+ if (!existsSync(claudeDir) || !pathLooksLikeExistingClaudeRoot(claudeDir)) return;++ try {+ mkdirSync(dirname(state.backupPath), { recursive: true });+ cpSync(claudeDir, state.backupPath, { recursive: true });+ await emit({+ event: "message",+ content: `Copied existing ~/.claude to ${state.backupPath.replace(homedir(), "~")} before installing the fresh tree.`,+ });+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ await emit({ event: "message", content: `Could not back up ~/.claude before reinstall: ${reason}` });+ throw err instanceof Error ? err : new Error(reason);+ }++ // The installer is executing from ~/.claude/PAI/PAI-Install right now.+ // Never remove ~/.claude wholesale here; instead clear only the parts the+ // fresh install will replace and explicitly preserve PAI/PAI-Install.+ const removableRoots = [+ "skills",+ "hooks",+ "MEMORY",+ "Plans",+ "tasks",+ "settings.json",+ ".env",+ "CLAUDE.md",+ ];++ for (const relPath of removableRoots) {+ const fullPath = join(claudeDir, relPath);+ if (!existsSync(fullPath)) continue;+ try {+ rmSync(fullPath, { recursive: true, force: true });+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ await emit({ event: "message", content: `Could not clear ${fullPath.replace(homedir(), "~")}: ${reason}` });+ }+ }++ const paiRoot = join(claudeDir, "PAI");+ if (existsSync(paiRoot)) {+ try {+ for (const entry of readdirSync(paiRoot)) {+ if (entry === "PAI-Install") continue;+ rmSync(join(paiRoot, entry), { recursive: true, force: true });+ }+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ await emit({ event: "message", content: `Could not fully clear ~/.claude/PAI before reinstall: ${reason}` });+ }+ }+}++// ─── Step 1: System Detection ────────────────────────────────────++export async function runSystemDetect(+ state: InstallState,+ emit: EngineEventHandler,+ getChoice?: ChoicePrompt+): Promise<DetectionResult> {+ await emit({ event: "step_start", step: "system-detect" });+ await emitSectionHeader(+ emit,+ "DETECTING-YOUR-SYSTEM",+ "DETECTING YOUR SYSTEM",+ "Reading OS, tools, and prior installs (no writes yet)",+ 1+ );+ await emit({ event: "progress", step: "system-detect", percent: 10, detail: "Detecting operating system..." });++ const detection = detectSystem();+ state.detection = detection;++ await emit({ event: "progress", step: "system-detect", percent: 50, detail: "Checking installed tools..." });++ // Determine install type+ if (detection.existing.paiInstalled) {+ state.installType = "upgrade";+ state.backupPath = computeBackupPath(detection.homeDir);+ await emitSectionHeader(+ emit,+ "EXISTING-INSTALLATION-FOUND",+ "EXISTING INSTALLATION FOUND",+ `Will copy ~/.claude → ${state.backupPath.replace(detection.homeDir, "~")} before installing fresh`+ );++ const consent = getChoice+ ? await getChoice(+ "backup-and-scan-consent",+ `Found existing PAI installation (v${detection.existing.paiVersion || "unknown"}). I'll copy ~/.claude to ${state.backupPath.replace(detection.homeDir, "~")} (your old install stays there until you remove it manually), then install a fresh tree.\n\nHow much of the old install should I read for pre-fill and migration?`,+ [+ {+ label: "Yes — full scan and migrate USER content",+ value: "yes-full",+ description: "Reads prior settings, identity, API keys, and PAI/USER content so it can be migrated into the fresh install.",+ },+ {+ label: "Yes — identity/config only",+ value: "yes-id",+ description: "Reads prior settings and API keys, but skips PAI/USER content scanning and migration.",+ },+ {+ label: "No — install fresh without reading it",+ value: "no",+ description: "Leaves the old tree in the backup only. No pre-fill and no content migration.",+ },+ ],+ state.collected.aiName+ )+ : "yes-full";+ state.collected.scanConsent = consent as InstallState["collected"]["scanConsent"];+ } else {+ state.installType = "fresh";+ state.backupPath = undefined;+ state.collected.scanConsent = "yes-full";+ await emit({ event: "message", content: "No existing PAI installation found. Starting fresh install." });+ }++ if (state.collected.scanConsent !== "no") {+ if (detection.existing.paiInstalled) {+ await emitSectionHeader(+ emit,+ "READING-YOUR-EXISTING-CONFIG",+ "READING YOUR EXISTING CONFIG",+ "Using the consented scope to pre-fill the fresh install"+ );+ }++ if (detection.existing.paiInstalled && detection.existing.settingsPath) {+ try {+ const settings = JSON.parse(readFileSync(detection.existing.settingsPath, "utf-8"));+ detection.existing.paiVersion = settings.pai?.version || settings.paiVersion || "unknown";+ if (settings.principal?.name && !isPlaceholderValue(settings.principal.name)) state.collected.principalName = settings.principal.name;+ if (settings.principal?.timezone && !isPlaceholderValue(settings.principal.timezone)) state.collected.timezone = settings.principal.timezone;+ if (settings.daidentity?.name && !isPlaceholderValue(settings.daidentity.name)) {+ state.collected.aiName = settings.daidentity.name;+ detection.existing.daName = settings.daidentity.name;+ }+ if (settings.daidentity?.startupCatchphrase && !isPlaceholderValue(settings.daidentity.startupCatchphrase)) state.collected.catchphrase = settings.daidentity.startupCatchphrase;+ if (settings.env?.PROJECTS_DIR && !isPlaceholderValue(settings.env.PROJECTS_DIR)) state.collected.projectsDir = settings.env.PROJECTS_DIR;+ if (settings.preferences?.temperatureUnit) state.collected.temperatureUnit = settings.preferences.temperatureUnit;+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ await emit({ event: "message", content: `Could not read prior settings.json: ${reason}` });+ }+ }++ detection.existing.apiKeys = scanApiKeys(detection.homeDir, detection.configDir);+ detection.existing.elevenLabsKeyFound = !!detection.existing.apiKeys.elevenLabs;+ detection.existing.hasApiKeys = Object.values(detection.existing.apiKeys).some(Boolean);++ if (!state.collected.principalName && detection.principal?.name) {+ state.collected.principalName = detection.principal.name;+ }+ if (!state.collected.elevenLabsKey && detection.existing.apiKeys?.elevenLabs) {+ state.collected.elevenLabsKey = detection.existing.apiKeys.elevenLabs;+ }+ if (!state.collected.timezone && detection.timezone) {+ state.collected.timezone = detection.timezone;+ }++ if (state.collected.scanConsent === "yes-full" && state.backupPath) {+ const liveUserDir = join(detection.paiDir, "PAI", "USER");+ const backupUserDir = join(state.backupPath, "PAI", "USER");+ if (existsSync(liveUserDir)) {+ try {+ mkdirSync(join(state.backupPath, "PAI"), { recursive: true });+ cpSync(liveUserDir, backupUserDir, { recursive: true });+ detection.existingUserContent = detectExistingUserContent(backupUserDir);+ await emit({+ event: "message",+ content: `Found in your backup: ${summariseExistingUserContent(detection.existingUserContent)}. These will be migrated forward to the new install.`,+ });+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ await emit({ event: "message", content: `Could not inspect backup user content: ${reason}` });+ }+ }+ }++ const preFills: string[] = [];+ if (state.collected.principalName) preFills.push(`name=${state.collected.principalName}`);+ if (state.collected.aiName) preFills.push(`DA=${state.collected.aiName}`);+ if (detection.principal?.email) preFills.push(`email=${detection.principal.email}`);+ if (state.collected.timezone) preFills.push(`timezone=${state.collected.timezone}`);+ const apiHits: string[] = [];+ if (detection.existing.apiKeys?.elevenLabs) apiHits.push("ElevenLabs");+ if (detection.existing.apiKeys?.anthropic) apiHits.push("Anthropic");+ if (detection.existing.apiKeys?.openai) apiHits.push("OpenAI");+ if (detection.existing.apiKeys?.google) apiHits.push("Google");+ if (detection.existing.apiKeys?.xai) apiHits.push("xAI/Grok");+ if (detection.existing.apiKeys?.perplexity) apiHits.push("Perplexity");+ if (apiHits.length > 0) preFills.push(`keys=${apiHits.join(",")}`);+ if (preFills.length > 0) {+ await emit({+ event: "message",+ content: `Pre-filled (from your consented scan): ${preFills.join(" · ")}.`,+ });+ }+ }++ await emit({ event: "progress", step: "system-detect", percent: 100, detail: "Detection complete" });+ await emit({ event: "step_complete", step: "system-detect" });+ return detection;+}++// ─── Step 2: Prerequisites ───────────────────────────────────────++export async function runPrerequisites(+ state: InstallState,+ emit: EngineEventHandler+): Promise<void> {+ await emit({ event: "step_start", step: "prerequisites" });+ await emitSectionHeader(+ emit,+ "INSTALLING-PREREQUISITES",+ "INSTALLING PREREQUISITES",+ "Making sure Bun, Git, and Claude Code are available",+ 2+ );+ const det = state.detection!;++ // Install Git if missing+ if (!det.tools.git.installed) {+ await emit({ event: "progress", step: "prerequisites", percent: 10, detail: "Installing Git..." });++ if (det.os.platform === "darwin") {+ if (det.tools.brew.installed) {+ const result = tryExec("brew install git", 120000);+ if (result !== null) {+ await emit({ event: "message", content: "Git installed via Homebrew." });+ } else {+ await emit({ event: "message", content: "Xcode Command Line Tools should include Git. Run: xcode-select --install" });+ }+ } else {+ await emit({ event: "message", content: "Please install Git: xcode-select --install" });+ }+ } else {+ // Linux+ const pkgMgr = tryExec("which apt-get") ? "apt-get" : tryExec("which yum") ? "yum" : null;+ if (pkgMgr) {+ tryExec(`sudo ${pkgMgr} install -y git`, 120000);+ await emit({ event: "message", content: `Git installed via ${pkgMgr}.` });+ }+ }+ } else {+ await emit({ event: "progress", step: "prerequisites", percent: 20, detail: `Git found: v${det.tools.git.version}` });+ }++ // Check for unzip — required by bun installer but missing on minimal Linux installs+ // Fixes: https://github.com/danielmiessler/Personal_AI_Infrastructure/issues/856+ if (!det.tools.bun.installed && det.os.platform === "linux") {+ const hasUnzip = tryExec("which unzip", 5000);+ if (hasUnzip === null) {+ await emit({ event: "progress", step: "prerequisites", percent: 35, detail: "Installing unzip (required by Bun)..." });++ // Try common package managers+ const installed =+ tryExec("sudo apt-get install -y unzip 2>/dev/null", 30000) !== null ||+ tryExec("sudo dnf install -y unzip 2>/dev/null", 30000) !== null ||+ tryExec("sudo yum install -y unzip 2>/dev/null", 30000) !== null ||+ tryExec("sudo pacman -S --noconfirm unzip 2>/dev/null", 30000) !== null;++ if (installed) {+ await emit({ event: "message", content: "unzip installed successfully." });+ } else {+ await emit({+ event: "message",+ content: "Could not install 'unzip' automatically. Bun requires it.\n Please install manually: sudo apt install unzip (Debian/Ubuntu) or sudo dnf install unzip (Fedora/RHEL)",+ });+ }+ }+ }++ // Bun should already be installed by bootstrap script, but verify+ if (!det.tools.bun.installed) {+ await emit({ event: "progress", step: "prerequisites", percent: 40, detail: "Installing Bun..." });+ const result = tryExec("curl -fsSL https://bun.sh/install | bash", 60000);+ if (result !== null) {+ // Update PATH+ const bunBin = join(homedir(), ".bun", "bin");+ process.env.PATH = `${bunBin}:${process.env.PATH}`;+ await emit({ event: "message", content: "Bun installed successfully." });+ deduplicateBunShellEntries(); // Fix #954: clean up duplicate entries from retries+ }+ } else {+ await emit({ event: "progress", step: "prerequisites", percent: 50, detail: `Bun found: v${det.tools.bun.version}` });+ }++ // Install Claude Code if missing+ if (!det.tools.claude.installed) {+ await emit({ event: "progress", step: "prerequisites", percent: 70, detail: "Installing Claude Code..." });++ // Try npm first (most common), then bun+ const npmResult = tryExec("npm install -g @anthropic-ai/claude-code", 120000);+ if (npmResult !== null) {+ await emit({ event: "message", content: "Claude Code installed via npm." });+ } else {+ // Try with bun+ const bunResult = tryExec("bun install -g @anthropic-ai/claude-code", 120000);+ if (bunResult !== null) {+ await emit({ event: "message", content: "Claude Code installed via bun." });+ } else {+ await emit({+ event: "message",+ content: "Could not install Claude Code automatically. Please install manually: npm install -g @anthropic-ai/claude-code",+ });+ }+ }+ } else {+ await emit({ event: "progress", step: "prerequisites", percent: 80, detail: `Claude Code found: v${det.tools.claude.version}` });+ }++ await emit({ event: "progress", step: "prerequisites", percent: 100, detail: "All prerequisites ready" });+ await emit({ event: "step_complete", step: "prerequisites" });+}++// ─── Step 3: API Keys (passthrough — key collection moved to Voice Setup) ──++export async function runApiKeys(+ state: InstallState,+ emit: EngineEventHandler,+ _getInput: InputPrompt,+ _getChoice: ChoicePrompt+): Promise<void> {+ // ElevenLabs key collection is now handled in the Voice Setup step+ // This step auto-completes to keep the step numbering consistent+ await emit({ event: "step_start", step: "api-keys" });+ await emitSectionHeader(+ emit,+ "API-KEYS",+ "API KEYS",+ "Voice-related keys are collected later when they are actually needed",+ 3+ );+ await emit({ event: "message", content: "API keys will be collected during Voice Setup." });+ await emit({ event: "step_complete", step: "api-keys" });+}++// ─── Step 4: Identity ────────────────────────────────────────────++export async function runIdentity(+ state: InstallState,+ emit: EngineEventHandler,+ getInput: InputPrompt+): Promise<void> {+ await emit({ event: "step_start", step: "identity" });+ await emitSectionHeader(+ emit,+ "YOUR-IDENTITY",+ "YOUR IDENTITY",+ "Confirming the human and DA details that personalize this install",+ 4+ );++ // Name — pre-fill the input with first name only (not full name).+ // The placeholder is the value the input shows by default; the frontend+ // renders it into both `value=` (so Enter accepts) and `placeholder=`.+ const fullDetectedName = state.collected.principalName || "";+ const detectedFirstName = fullDetectedName.split(/\s+/)[0] || "";+ const namePrompt = detectedFirstName+ ? `What is your first name? (Press Enter to keep: ${detectedFirstName})`+ : "What is your first name?";+ const name = await getInput(+ "principal-name",+ namePrompt,+ "text",+ detectedFirstName,+ state.collected.aiName+ );+ state.collected.principalName = name.trim() || detectedFirstName || "User";++ // Timezone+ const detectedTz = state.detection?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;+ const tz = await getInput(+ "timezone",+ `Detected timezone: ${detectedTz}. Press Enter to confirm or type a different one.`,+ "text",+ detectedTz,+ state.collected.aiName+ );+ state.collected.timezone = tz.trim() || detectedTz;++ // Temperature unit+ const defaultTempUnit = state.collected.temperatureUnit || "fahrenheit";+ const tempUnit = await getInput(+ "temperature-unit",+ `Temperature unit? Type F for Fahrenheit or C for Celsius. (Default: ${defaultTempUnit === "celsius" ? "C" : "F"})`,+ "text",+ defaultTempUnit === "celsius" ? "C" : "F",+ state.collected.aiName+ );+ const trimmedUnit = tempUnit.trim().toLowerCase();+ state.collected.temperatureUnit = (trimmedUnit === "c" || trimmedUnit === "celsius") ? "celsius" : "fahrenheit";++ // AI Name+ const defaultAi = state.collected.aiName || "";+ const aiPrompt = defaultAi+ ? `What would you like to name your AI assistant? (Press Enter to keep: ${defaultAi})`+ : "What would you like to name your AI assistant?";+ const aiName = await getInput(+ "ai-name",+ aiPrompt,+ "text",+ "e.g., Atlas, Nova, Sage",+ state.collected.aiName+ );+ state.collected.aiName = aiName.trim() || defaultAi || "PAI";++ // Catchphrase+ const defaultCatch = state.collected.catchphrase || `${state.collected.aiName} here, ready to go`;+ const catchphrase = await getInput(+ "catchphrase",+ `Startup catchphrase for ${state.collected.aiName}?`,+ "text",+ defaultCatch,+ state.collected.aiName+ );+ state.collected.catchphrase = catchphrase.trim() || defaultCatch;++ // Projects directory (optional)+ const defaultProjects = state.collected.projectsDir || "";+ const projDir = await getInput(+ "projects-dir",+ "Projects directory (optional, press Enter to skip):",+ "text",+ defaultProjects || "~/Projects",+ state.collected.aiName+ );+ if (projDir.trim()) {+ state.collected.projectsDir = projDir.trim().replace(/^~/, homedir());+ }++ await emit({+ event: "message",+ content: `Identity configured: ${state.collected.principalName} with AI assistant ${state.collected.aiName}.`,+ speak: true,+ });+ await emit({ event: "step_complete", step: "identity" });+}++// ─── Step 5: Repository ──────────────────────────────────────────++// ─── Local Bundle Detection & Install ───────────────────────────+//+// install.sh exports PAI_BUNDLE_DIR pointing to its own directory — the+// root of the v5 release bundle. The wizard prefers installing from this+// local bundle over git-cloning the public repo, because the public repo+// may lag the current release. The bundle is the canonical source of+// truth for the version it represents.+//+// Marker files prove the bundle is complete; missing markers fall back+// to git clone so users who run main.ts directly (no bundle) still work.++const BUNDLE_MARKERS = [+ "install.sh",+ "settings.json",+ "hooks/SecurityPipeline.hook.ts",+ "PAI/PAI-Install/main.ts",+];++const BUNDLE_COPY_EXCLUDES = new Set([+ ".git",+ "node_modules",+ "PAI_RELEASES",+ "install-state.json",+ ".DS_Store",+ ".tmp",+ ".quote-cache",+]);++function detectLocalBundle(): string | null {+ const bundleRoot = process.env.PAI_BUNDLE_DIR;+ if (!bundleRoot || !existsSync(bundleRoot)) return null;+ for (const marker of BUNDLE_MARKERS) {+ if (!existsSync(join(bundleRoot, marker))) return null;+ }+ return bundleRoot;+}++function copyBundleTree(+ src: string,+ dst: string,+ stats: { files: number; bytes: number } = { files: 0, bytes: 0 }+): { files: number; bytes: number } {+ if (!existsSync(dst)) mkdirSync(dst, { recursive: true });++ for (const entry of readdirSync(src, { withFileTypes: true })) {+ if (BUNDLE_COPY_EXCLUDES.has(entry.name)) continue;++ const srcPath = join(src, entry.name);+ const dstPath = join(dst, entry.name);++ if (entry.isDirectory()) {+ copyBundleTree(srcPath, dstPath, stats);+ } else if (entry.isSymbolicLink()) {+ try {+ const target = readlinkSync(srcPath);+ if (existsSync(dstPath)) unlinkSync(dstPath);+ symlinkSync(target, dstPath);+ } catch {+ // skip broken symlinks+ }+ } else if (entry.isFile()) {+ try {+ cpSync(srcPath, dstPath);+ stats.files++;+ stats.bytes += lstatSync(srcPath).size;+ } catch {+ // permission errors are non-fatal+ }+ }+ }+ return stats;+}++async function installFromLocalBundle(+ bundleDir: string,+ targetDir: string,+ emit: EngineEventHandler+): Promise<{ files: number; bytes: number }> {+ await emit({+ event: "progress",+ step: "repository",+ percent: 30,+ detail: `Installing from local v5 bundle...`,+ });+ if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });+ const stats = copyBundleTree(bundleDir, targetDir);+ await emit({+ event: "progress",+ step: "repository",+ percent: 90,+ detail: `Copied ${stats.files} files (${(stats.bytes / 1024 / 1024).toFixed(1)} MB).`,+ });+ return stats;+}++export async function runRepository(+ state: InstallState,+ emit: EngineEventHandler+): Promise<void> {+ await emit({ event: "step_start", step: "repository" });+ await emitSectionHeader(+ emit,+ "INSTALLING-THE-PAI-TREE",+ "INSTALLING THE PAI TREE",+ "Laying down a fresh ~/.claude tree and restoring any consented content",+ 5+ );+ const paiDir = state.detection?.paiDir || join(homedir(), ".claude");++ await moveExistingClaudeToBackup(state, emit);++ if (!existsSync(paiDir)) {+ mkdirSync(paiDir, { recursive: true });+ }++ // The backup we just created IS a complete v5 bundle (it's a copy of the+ // staging tree this installer shipped with). Use it as the install source+ // — never reach out to GitHub when we already have the tree on disk.+ // Falls through to PAI_BUNDLE_DIR / git-clone only if the backup path is+ // missing markers (e.g. user explicitly skipped backup, or partial copy).+ if (state.backupPath && existsSync(state.backupPath)) {+ const backupHasMarkers = BUNDLE_MARKERS.every((m) =>+ existsSync(join(state.backupPath!, m))+ );+ if (backupHasMarkers) {+ process.env.PAI_BUNDLE_DIR = state.backupPath;+ await emit({+ event: "message",+ content: `Using your backup as the install source — no GitHub clone needed.`,+ });+ }+ }++ const localBundle = detectLocalBundle();+ let bundleInstalled = false;++ if (localBundle) {+ await emit({+ event: "message",+ content: `Local v5 bundle detected at ${localBundle}. Installing from bundle (skipping git clone).`,+ });+ try {+ const stats = await installFromLocalBundle(localBundle, paiDir, emit);+ await emit({+ event: "message",+ content: `Installed ${stats.files} files from local bundle (${(stats.bytes / 1024 / 1024).toFixed(1)} MB).`,+ });+ bundleInstalled = true;+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ await emit({+ event: "message",+ content: `Local bundle install failed: ${msg}. Falling back to git clone.`,+ });+ }+ } else if (process.env.PAI_BUNDLE_DIR) {+ await emit({+ event: "message",+ content: `PAI_BUNDLE_DIR set but bundle is incomplete (missing marker files). Falling back to git clone.`,+ });+ }++ if (!bundleInstalled) {+ await emit({ event: "progress", step: "repository", percent: 20, detail: "Cloning PAI repository..." });++ const cloneResult = tryExec(+ `git clone https://github.com/danielmiessler/PAI.git "${paiDir}" 2>&1`,+ 120000+ );++ if (cloneResult !== null) {+ await emit({ event: "message", content: "PAI repository cloned successfully." });+ } else {+ await emit({ event: "progress", step: "repository", percent: 50, detail: "Directory exists, trying alternative approach..." });++ const initResult = tryExec(`cd "${paiDir}" && git init && git remote add origin https://github.com/danielmiessler/PAI.git && git fetch origin && git checkout -b main origin/main 2>&1`, 120000);+ if (initResult !== null) {+ await emit({ event: "message", content: "PAI repository initialized and synced." });+ } else {+ await emit({+ event: "message",+ content: "Could not clone PAI repo automatically. You can clone it manually later: git clone https://github.com/danielmiessler/PAI.git ~/.claude",+ });+ }+ }+ }++ // Create required directories regardless of clone result+ const requiredDirs = [+ "MEMORY",+ "MEMORY/STATE",+ "MEMORY/LEARNING",+ "MEMORY/WORK",+ "MEMORY/RELATIONSHIP",+ "MEMORY/VOICE",+ "Plans",+ "hooks",+ "skills",+ "tasks",+ ];++ for (const dir of requiredDirs) {+ const fullPath = join(paiDir, dir);+ if (!existsSync(fullPath)) {+ mkdirSync(fullPath, { recursive: true });+ }+ }++ if (state.collected.scanConsent !== "no" && state.backupPath) {+ await emitSectionHeader(+ emit,+ "MIGRATING-YOUR-USER-CONTENT",+ "MIGRATING YOUR USER CONTENT",+ "Restoring your TELOS, identity, and personal docs from the backup"+ );+ await migrateUserContentFromBackup(state, emit);+ }++ await migrateUserContext(paiDir, emit);++ await emit({ event: "progress", step: "repository", percent: 100, detail: "Repository ready" });+ await emit({ event: "step_complete", step: "repository" });+}++// ─── Step 6: Configuration ───────────────────────────────────────++export async function runConfiguration(+ state: InstallState,+ emit: EngineEventHandler+): Promise<void> {+ await emit({ event: "step_start", step: "configuration" });+ await emitSectionHeader(+ emit,+ "GENERATING-CONFIGURATION",+ "GENERATING CONFIGURATION",+ "Writing settings, env files, aliases, and identity templates",+ 6+ );+ const paiDir = state.detection?.paiDir || join(homedir(), ".claude");+ const configDir = state.detection?.configDir || join(homedir(), ".config", "PAI");++ // Generate settings.json+ await emit({ event: "progress", step: "configuration", percent: 20, detail: "Generating settings.json..." });++ const config = generateSettingsJson({+ principalName: state.collected.principalName || "User",+ timezone: state.collected.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,+ aiName: state.collected.aiName || "PAI",+ catchphrase: state.collected.catchphrase || "Ready to go",+ projectsDir: state.collected.projectsDir,+ temperatureUnit: state.collected.temperatureUnit,+ voiceType: state.collected.voiceType,+ voiceId: state.collected.customVoiceId,+ paiDir,+ configDir,+ });++ const settingsPath = join(paiDir, "settings.json");++ // The release ships a complete settings.json with hooks, statusLine, spinnerVerbs, etc.+ // We only update user-specific fields — never overwrite the whole file.+ if (existsSync(settingsPath)) {+ try {+ const existing = JSON.parse(readFileSync(settingsPath, "utf-8"));+ // Merge only installer-managed fields; preserve everything else+ existing.env = { ...existing.env, ...config.env };+ existing.principal = { ...existing.principal, ...config.principal };+ existing.daidentity = { ...existing.daidentity, ...config.daidentity };+ existing.pai = { ...existing.pai, ...config.pai };+ // Force-overwrite version fields — these must ALWAYS match the release,+ // never be preserved from the user's existing config (fix for #800)+ existing.pai.version = PAI_VERSION;+ existing.pai.algorithmVersion = ALGORITHM_VERSION;+ existing.preferences = { ...existing.preferences, ...config.preferences };+ // Only set permissions/contextFiles/plansDirectory if not already present+ if (!existing.permissions) existing.permissions = config.permissions;+ if (!existing.contextFiles) existing.contextFiles = config.contextFiles;+ if (!existing.plansDirectory) existing.plansDirectory = config.plansDirectory;+ // Never touch: hooks, statusLine, spinnerVerbs, contextFiles (if present)+ writeFileSync(settingsPath, JSON.stringify(existing, null, 2));+ } catch {+ // Existing file is corrupt — write fresh as fallback+ writeFileSync(settingsPath, JSON.stringify(config, null, 2));+ }+ } else {+ writeFileSync(settingsPath, JSON.stringify(config, null, 2));+ }+ await emit({ event: "message", content: "settings.json generated." });++ // Algorithm LATEST is the single source of truth (v6.2.0+ doctrine).+ // Path is canonical uppercase ALGORITHM (case-sensitive on Linux).+ // Prefer the staged tree's LATEST if it shipped one; otherwise write the+ // ALGORITHM_VERSION fallback. The previous version skipped writing when+ // `latestDir` was missing — that left fresh installs (where the bundle+ // lacked PAI/ALGORITHM/) with no LATEST file at all, and the statusline+ // displayed `ALG: —` forever. Always ensure both directory and a non-empty+ // LATEST exist by the time configuration completes.+ const latestDir = join(paiDir, "PAI", "ALGORITHM");+ const latestPath = join(latestDir, "LATEST");+ let latestExisting = "";+ try { latestExisting = readFileSync(latestPath, "utf-8").trim(); } catch {}+ if (!latestExisting) {+ try {+ mkdirSync(latestDir, { recursive: true });+ writeFileSync(latestPath, `${ALGORITHM_VERSION}\n`);+ await emit({ event: "message", content: `Algorithm LATEST written from constant fallback (${ALGORITHM_VERSION}) — bundle did not ship one.` });+ } catch (err) {+ await emit({ event: "message", content: `WARNING: failed to write Algorithm LATEST: ${err instanceof Error ? err.message : String(err)}` });+ }+ }++ // Calculate and write initial counts so banner shows real numbers on first launch+ await emit({ event: "progress", step: "configuration", percent: 35, detail: "Calculating system counts..." });+ try {+ const countFiles = (dir: string, ext?: string): number => {+ if (!existsSync(dir)) return 0;+ let count = 0;+ const walk = (d: string) => {+ try {+ for (const entry of readdirSync(d, { withFileTypes: true })) {+ if (entry.isDirectory()) walk(join(d, entry.name));+ else if (!ext || entry.name.endsWith(ext)) count++;+ }+ } catch {}+ };+ walk(dir);+ return count;+ };++ const countDirs = (dir: string, filter?: (name: string) => boolean): number => {+ if (!existsSync(dir)) return 0;+ try {+ return readdirSync(dir, { withFileTypes: true })+ .filter(e => e.isDirectory() && (!filter || filter(e.name))).length;+ } catch { return 0; }+ };++ const skillCount = countDirs(join(paiDir, "skills"), (name) =>+ existsSync(join(paiDir, "skills", name, "SKILL.md")));+ const hookCount = countFiles(join(paiDir, "hooks"), ".ts");+ const signalCount = countFiles(join(paiDir, "MEMORY", "LEARNING"), ".md");+ const fileCount = countFiles(join(paiDir, "skills", "PAI", "USER"));+ // Count workflows by scanning skill Tools directories for .ts files+ let workflowCount = 0;+ const skillsDir = join(paiDir, "skills");+ if (existsSync(skillsDir)) {+ try {+ for (const s of readdirSync(skillsDir, { withFileTypes: true })) {+ if (s.isDirectory()) {+ const toolsDir = join(skillsDir, s.name, "Tools");+ if (existsSync(toolsDir)) {+ workflowCount += countFiles(toolsDir, ".ts");+ }+ }+ }+ } catch {}+ }++ // Write counts to settings.json+ const currentSettings = JSON.parse(readFileSync(settingsPath, "utf-8"));+ currentSettings.counts = {+ skills: skillCount,+ workflows: workflowCount,+ hooks: hookCount,+ signals: signalCount,+ files: fileCount,+ updatedAt: new Date().toISOString(),+ };+ writeFileSync(settingsPath, JSON.stringify(currentSettings, null, 2));+ } catch {+ // Non-fatal — banner will just show 0 until first session ends+ }++ // Render identity into the user-facing markdown.+ // CLAUDE.md ships with `{DA_IDENTITY.NAME}` / `{PRINCIPAL.NAME}` tokens+ // (because the public release can't know either yet) and DA_IDENTITY.md+ // / PRINCIPAL_IDENTITY.md ship as bootstrap defaults. Without this step,+ // the model literalises the curly-brace tokens at runtime and shows+ // `{{DA_NAME}}` in chat instead of the user's actual DA name.+ await emit({ event: "progress", step: "configuration", percent: 42, detail: "Personalising identity files..." });+ const aiName = state.collected.aiName || "PAI";+ const principalName = state.collected.principalName || "User";++ const claudeMdPath = join(paiDir, "CLAUDE.md");+ if (existsSync(claudeMdPath)) {+ try {+ const content = readFileSync(claudeMdPath, "utf-8")+ .replace(/\{DA_IDENTITY\.NAME\}/g, aiName)+ .replace(/\{PRINCIPAL\.NAME\}/g, principalName);+ writeFileSync(claudeMdPath, content);+ } catch {}+ }++ const daIdentityPath = join(paiDir, "PAI", "USER", "DA_IDENTITY.md");+ if (existsSync(daIdentityPath)) {+ try {+ const content = readFileSync(daIdentityPath, "utf-8")+ // Title — lenient match for any DA Identity heading+ .replace(/^# DA Identity — .+$/m, `# DA Identity — ${aiName}`)+ // Body Name/Full Name/Display line — structural match (any current values),+ // not literal "PAI Assistant", so the replace works regardless of which+ // template variant is on disk (fixes the "PAI | PAI | PAI" + "Kergan title"+ // drift case where title got updated but body did not).+ .replace(+ /^- \*\*Name:\*\* [^|\n]+\| \*\*Full Name:\*\* [^|\n]+\| \*\*Display:\*\* [^\n]+$/m,+ `- **Name:** ${aiName} | **Full Name:** ${aiName} | **Display:** ${aiName}`+ )+ // Self-introduction line — match either template variant+ .replace(/I am PAI, (the user's|User's) AI assistant/g, `I am ${aiName}, ${principalName}'s AI assistant`);+ writeFileSync(daIdentityPath, content);+ } catch {}+ }++ const principalIdPath = join(paiDir, "PAI", "USER", "PRINCIPAL_IDENTITY.md");+ if (existsSync(principalIdPath)) {+ try {+ const content = readFileSync(principalIdPath, "utf-8")+ .replace(/^# Principal Identity — .+$/m, `# Principal Identity — ${principalName}`);+ writeFileSync(principalIdPath, content);+ } catch {}+ }++ // Create .env file for API keys+ await emit({ event: "progress", step: "configuration", percent: 50, detail: "Setting up API keys..." });++ if (!existsSync(configDir)) {+ mkdirSync(configDir, { recursive: true });+ }++ const envPath = join(configDir, ".env");+ let envContent = "";++ if (state.collected.elevenLabsKey) {+ envContent += `ELEVENLABS_API_KEY=${state.collected.elevenLabsKey}\n`;+ }++ if (envContent) {+ writeFileSync(envPath, envContent, { mode: 0o600 });+ await emit({ event: "message", content: "API keys saved securely." });+ }++ // Create symlinks so all consumers can find the .env+ // Voice server reads ~/.env, hooks read ~/.claude/.env+ if (existsSync(envPath)) {+ const symlinkPaths = [+ join(paiDir, ".env"), // ~/.claude/.env+ join(homedir(), ".env"), // ~/.env (voice server reads this)+ ];+ for (const symlinkPath of symlinkPaths) {+ try {+ // Remove stale symlink or file before creating+ if (existsSync(symlinkPath)) {+ const stat = lstatSync(symlinkPath);+ if (stat.isSymbolicLink()) {+ unlinkSync(symlinkPath);+ } else {+ continue; // Don't overwrite a real file+ }+ }+ symlinkSync(envPath, symlinkPath);+ } catch {+ // Permission error or path conflict+ }+ }+ }++ // Set up shell alias (detect bash/zsh/fish)+ await emit({ event: "progress", step: "configuration", percent: 80, detail: "Setting up shell alias..." });++ const userShell = process.env.SHELL || "/bin/zsh";+ const rcFile = userShell.includes("bash") ? ".bashrc" : userShell.includes("fish") ? ".config/fish/config.fish" : ".zshrc";+ const rcPath = join(homedir(), rcFile);+ const aliasLine = `alias pai='bun ${join(paiDir, "PAI", "Tools", "pai.ts")}'`;+ const marker = "# PAI alias";++ if (existsSync(rcPath)) {+ let content = readFileSync(rcPath, "utf-8");+ // Remove any existing pai alias (old CORE or PAI paths, any marker variant)+ content = content.replace(/^#\s*(?:PAI|CORE)\s*alias.*\n.*alias pai=.*\n?/gm, "");+ content = content.replace(/^alias pai=.*\n?/gm, "");+ // Add fresh alias+ content = content.trimEnd() + `\n\n${marker}\n${aliasLine}\n`;+ writeFileSync(rcPath, content);+ } else {+ writeFileSync(rcPath, `${marker}\n${aliasLine}\n`);+ }++ // Fix permissions+ await emit({ event: "progress", step: "configuration", percent: 90, detail: "Setting permissions..." });+ try {+ tryExec(`chmod -R 755 "${paiDir}"`, 10000);+ } catch {+ // Non-fatal+ }++ await emit({ event: "progress", step: "configuration", percent: 100, detail: "Configuration complete" });+ await emit({ event: "step_complete", step: "configuration" });+}++// ─── Voice Server Management ────────────────────────────────────++// PAI 5.0 absorbed the standalone voice server into Pulse on port 31337.+// `PAI/PULSE/VoiceServer/voice.ts` is now an embeddable module that pulse.ts+// loads on startup; there is no separate voice-server process. Health-check+// the voice surface by probing Pulse on /notify.+async function isPulseRunning(): Promise<boolean> {+ try {+ const res = await fetch("http://localhost:31337/notify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ message: "", voice_enabled: false }),+ signal: AbortSignal.timeout(2000),+ });+ // Any non-network response (200/204/4xx) means Pulse is up and routing /notify.+ return res.status >= 200 && res.status < 500;+ } catch {+ return false;+ }+}++// Install Pulse as a launchd agent via the canonical `PULSE/manage.sh install`.+// Manage.sh substitutes __HOME__ in the public plist template, copies it to+// ~/Library/LaunchAgents/com.pai.pulse.plist, and `launchctl load`s it.+async function installPulse(paiDir: string, emit: EngineEventHandler): Promise<boolean> {+ const pulseDir = join(paiDir, "PAI", "PULSE");+ const manageScript = join(pulseDir, "manage.sh");++ if (!existsSync(manageScript)) {+ await emit({ event: "message", content: "Pulse not found in installation. Voice notifications will be unavailable." });+ return false;+ }++ await emit({ event: "progress", step: "voice", percent: 20, detail: "Installing Pulse (voice + dashboard + observability)..." });++ try {+ const installOk = await new Promise<boolean>((resolve) => {+ const child = spawn("bash", [manageScript, "install"], {+ cwd: pulseDir,+ stdio: ["ignore", "pipe", "pipe"],+ });+ const timer = setTimeout(() => { child.kill(); resolve(false); }, 30000);+ child.on("close", (code) => { clearTimeout(timer); resolve(code === 0); });+ child.on("error", () => { clearTimeout(timer); resolve(false); });+ });++ if (!installOk) {+ await emit({ event: "message", content: "Pulse install command failed. Voice notifications will not be available." });+ return false;+ }++ for (let i = 0; i < 20; i++) {+ await new Promise(r => setTimeout(r, 500));+ if (await isPulseRunning()) {+ await emit({ event: "message", content: "Pulse installed and running on port 31337 (voice + dashboard + observability)." });+ return true;+ }+ }+ // Pulse plist installed but never bound :31337. Surface this as an install+ // failure rather than silently reporting success — the user will hit+ // mysterious 'voice not working' / 'pulse not starting' otherwise.+ await emit({ event: "message", content: "Pulse plist installed but port 31337 did not bind within 10s. Check ~/.claude/PAI/PULSE/logs/pulse-stderr.log. Voice and dashboard will not work until this is resolved." });+ return false;+ } catch {+ await emit({ event: "message", content: "Could not install Pulse. Voice notifications will not be available." });+ return false;+ }+}++// Reload Pulse so it re-reads settings.json after a config change. Called at+// the end of voice setup so the user's DA voice pick (written to settings.json+// AFTER Pulse was installed and started) is actually honored at runtime.+//+// Without this, Pulse's `defaultVoiceId` cache is stale: Pulse boots from the+// template settings during initial install, then the wizard rewrites the voice+// section, but Pulse never reloads — so every skill curl that omits voice_id+// hits Pulse's stale cached default instead of the user's chosen DA voice.+// `manage.sh restart` is idempotent: unloads the launchd plist, kills any+// stale `bun pulse.ts`, reloads, waits up to 10s for :31337 to bind.+async function reloadPulse(paiDir: string, emit: EngineEventHandler): Promise<void> {+ const manageScript = join(paiDir, "PAI", "PULSE", "manage.sh");+ if (!existsSync(manageScript)) return;+ const homeLaunchAgent = join(homedir(), "Library", "LaunchAgents", "com.pai.pulse.plist");+ if (!existsSync(homeLaunchAgent)) return;+ await emit({ event: "message", content: "Reloading Pulse to pick up new voice configuration..." });+ await new Promise<void>((resolve) => {+ const child = spawn("bash", [manageScript, "restart"], {+ cwd: dirname(manageScript),+ stdio: ["ignore", "pipe", "pipe"],+ });+ const timer = setTimeout(() => { child.kill(); resolve(); }, 30000);+ child.on("close", () => { clearTimeout(timer); resolve(); });+ child.on("error", () => { clearTimeout(timer); resolve(); });+ });+}++// Optional menu bar app — separate launchd plist + macOS .app bundle.+async function installPulseMenuBar(paiDir: string, emit: EngineEventHandler): Promise<boolean> {+ const menuBarInstall = join(paiDir, "PAI", "PULSE", "MenuBar", "install.sh");+ if (!existsSync(menuBarInstall)) {+ await emit({ event: "message", content: "Menu bar installer not found — skipping." });+ return false;+ }++ await emit({ event: "progress", step: "voice", percent: 35, detail: "Installing Pulse menu bar app..." });++ try {+ const ok = await new Promise<boolean>((resolve) => {+ const child = spawn("bash", [menuBarInstall], {+ cwd: dirname(menuBarInstall),+ stdio: ["ignore", "pipe", "pipe"],+ });+ const timer = setTimeout(() => { child.kill(); resolve(false); }, 120000);+ child.on("close", (code) => { clearTimeout(timer); resolve(code === 0); });+ child.on("error", () => { clearTimeout(timer); resolve(false); });+ });++ if (ok) {+ await emit({ event: "message", content: "Menu bar app installed — look for the Pulse icon in your menu bar." });+ return true;+ }+ await emit({ event: "message", content: "Menu bar install did not complete. You can run it later: bash ~/.claude/PAI/PULSE/MenuBar/install.sh" });+ return false;+ } catch {+ return false;+ }+}++// ─── Step 7: Voice Setup ─────────────────────────────────────────++export async function runVoiceSetup(+ state: InstallState,+ emit: EngineEventHandler,+ getChoice: ChoicePrompt,+ getInput: InputPrompt,+ getChoiceWithPreview?: ChoicePreviewPrompt+): Promise<void> {+ await emit({ event: "step_start", step: "voice" });+ await emitSectionHeader(+ emit,+ "DA-VOICE-SETUP",+ "DA VOICE SETUP",+ "Configuring speech, Pulse, and the DA's default voice",+ 7+ );+ const daName = state.collected.aiName;++ // ── Upfront scan permission gate (UNCONDITIONAL) ──+ //+ // The very first prompt of the voice step. Fires regardless of whether+ // anything is found — the user authorizes the scan BEFORE any read+ // happens. This is the point: don't silently touch `~/.config/PAI/.env`,+ // `~/.claude*` backup dirs, or stale settings.json voice configs without+ // the user's explicit OK, even when the read would return nothing.+ //+ // If the user says yes → run `inventoryExistingConfig()` and present+ // findings (per-item confirmation handled below in key + voice picker).+ // If the user says no → never read those locations; go straight to+ // "provide your own key OR skip voice".+ const allowScanChoice = await getChoice(+ "scan-prior-config",+ "Look in backup directories and your prior PAI config for existing ElevenLabs voice IDs and API keys?",+ [+ { label: "Yes — scan and let me confirm anything found", value: "yes", description: "Reads ~/.config/PAI/.env and any ~/.claude.bak / ~/.claude-bak / ~/.claude.backup.* / ~/.claude.previous etc. Per-item confirmation before anything is imported." },+ { label: "No — start completely fresh", value: "no", description: "Skip the scan. I'll either enter a new ElevenLabs key or skip voice entirely." },+ ],+ daName+ );+ const allowImportPriorConfig = allowScanChoice === "yes";++ // Surface the inventory ONLY if the user authorized it.+ if (allowImportPriorConfig) {+ const inventory = inventoryExistingConfig();+ if (inventory.signals.length > 0) {+ await emit({+ event: "message",+ content:+ "Scanning prior config — found:\n • " ++ inventory.signals.join("\n • ") ++ "\n\nEach will be presented for individual confirmation below.",+ });+ } else {+ await emit({+ event: "message",+ content: "Scanned prior config — nothing found. Continuing to fresh-key prompt.",+ });+ }+ }++ // ── Collect ElevenLabs key — only reads existing locations if user opted in ──+ if (!state.collected.elevenLabsKey) {+ let elevenLabsKey = "";++ if (allowImportPriorConfig) {+ // Step 1: Check active locations (~/.claude/.env, ~/.config/PAI/.env).+ await emit({ event: "progress", step: "voice", percent: 5, detail: "Checking existing ElevenLabs key locations..." });+ const candidate = findExistingEnvKey("ELEVENLABS_API_KEY");+ if (candidate) {+ const useIt = await getChoice("confirm-active-key", `Found ElevenLabs API key in ~/.claude/.env or ~/.config/PAI/.env. Use it?`, [+ { label: "Yes — validate and use", value: "yes" },+ { label: "No — skip this one", value: "no" },+ ], daName);+ if (useIt === "yes") {+ await emit({ event: "message", content: "Validating key against ElevenLabs API..." });+ const result = await validateElevenLabsKey(candidate);+ if (result.valid) {+ state.collected.elevenLabsKey = candidate;+ elevenLabsKey = candidate;+ await emit({ event: "message", content: "Existing ElevenLabs API key is valid." });+ } else {+ await emit({ event: "message", content: `Key invalid: ${result.error}. Continuing search.` });+ }+ }+ }++ // Step 2: Check backup .claude* directories with per-finding confirmation.+ if (!elevenLabsKey) {+ const backupHits = findKeyInBackupDirs("ELEVENLABS_API_KEY");+ for (const hit of backupHits) {+ const useThis = await getChoice(`confirm-backup-${hit.path}`, `Found ElevenLabs key in ${hit.path.replace(homedir(), "~")}. Use it?`, [+ { label: "Yes — validate and use", value: "yes" },+ { label: "No — skip this one", value: "no" },+ ], daName);+ if (useThis !== "yes") continue;+ await emit({ event: "progress", step: "voice", percent: 10, detail: `Validating key from ${hit.path.replace(homedir(), "~")}...` });+ const result = await validateElevenLabsKey(hit.value);+ if (result.valid) {+ state.collected.elevenLabsKey = hit.value;+ elevenLabsKey = hit.value;+ await emit({ event: "message", content: `Using ElevenLabs key from ${hit.path.replace(homedir(), "~")}.` });+ break;+ } else {+ await emit({ event: "message", content: `Key from ${hit.path.replace(homedir(), "~")} invalid: ${result.error}.` });+ }+ }+ }+ }++ // Step 3: If no key was imported (either declined upfront, or no valid key found,+ // or scanning was permitted but every candidate was skipped/invalid), prompt the user.+ if (!elevenLabsKey) {+ const wantsVoice = await getChoice("voice-enable", "Voice requires an ElevenLabs API key. Get one free at elevenlabs.io — without a key, voice notifications are disabled.", [+ { label: "I have a key — let me enter it", value: "yes" },+ { label: "Skip voice for now", value: "skip", description: "You can add a key later: edit ~/.config/PAI/.env" },+ ], daName);++ if (wantsVoice === "yes") {+ const key = await getInput(+ "elevenlabs-key",+ "Enter your ElevenLabs API key:",+ "key",+ "sk_...",+ daName+ );++ if (key.trim()) {+ await emit({ event: "progress", step: "voice", percent: 15, detail: "Validating ElevenLabs key..." });+ const result = await validateElevenLabsKey(key.trim());+ if (result.valid) {+ state.collected.elevenLabsKey = key.trim();+ await emit({ event: "message", content: "ElevenLabs API key verified." });+ } else {+ await emit({ event: "message", content: `Key validation failed: ${result.error}. Skipping voice setup.` });+ }+ }+ }+ }+ }++ const hasElevenLabsKey = !!state.collected.elevenLabsKey;+ if (!hasElevenLabsKey) {+ await emit({ event: "message", content: "No ElevenLabs key — voice will fall back to macOS text-to-speech. You can add a key later in ~/.claude/.env" });+ }++ const paiDir = state.detection?.paiDir || join(homedir(), ".claude");++ // ── Write ELEVENLABS_API_KEY to ~/.claude/.env BEFORE Pulse starts ──+ // Pulse loads .env at boot. If we install Pulse before writing the key,+ // the daemon comes up without ELEVENLABS_API_KEY in process.env and voice+ // silently falls back to macOS `say` — even after the configuration step+ // writes .env later. The fix: write the key now, then start Pulse.+ if (hasElevenLabsKey) {+ try {+ const envPath = join(paiDir, ".env");+ let envContent = existsSync(envPath) ? readFileSync(envPath, "utf-8") : "";+ if (envContent.includes("ELEVENLABS_API_KEY=")) {+ envContent = envContent.replace(/ELEVENLABS_API_KEY=.*/, `ELEVENLABS_API_KEY=${state.collected.elevenLabsKey}`);+ } else {+ envContent = (envContent.trimEnd() + `\nELEVENLABS_API_KEY=${state.collected.elevenLabsKey}\n`).trimStart();+ }+ writeFileSync(envPath, envContent, { mode: 0o600 });+ await emit({ event: "message", content: "ElevenLabs key written to ~/.claude/.env (Pulse will read it on boot)." });+ } catch (err: any) {+ await emit({ event: "message", content: `Could not write .env: ${err?.message || err}. Voice may fall back to macOS say.` });+ }+ }++ // ── Install Pulse (Y/n) — embeds voice + dashboard + observability ──++ await emit({+ event: "message",+ content:+ "Pulse is the unified PAI runtime: it serves the Life Dashboard at http://localhost:31337, " ++ "handles voice notifications (TTS via ElevenLabs), and runs observability + scheduled jobs. " ++ "Installing it as a launchd agent makes it auto-start on login and stay running across reboots.",+ });++ const installPulseChoice = await getChoice("install-pulse", "Install Pulse as a system launchd service?", [+ { label: "Yes — install Pulse (recommended)", value: "yes", description: "Auto-starts on login. Voice + Dashboard + Observability." },+ { label: "Skip — don't install Pulse now", value: "skip", description: "Voice notifications will not work until you run: bash ~/.claude/PAI/PULSE/manage.sh install" },+ ], daName);++ let voiceServerReady = false;+ if (installPulseChoice === "yes") {+ voiceServerReady = await installPulse(paiDir, emit);+ } else {+ await emit({ event: "message", content: "Pulse skipped. Voice not enabled — install later via: bash ~/.claude/PAI/PULSE/manage.sh install" });+ }++ // ── Optional menu bar app (Y/n) — separate launchd plist + .app bundle ──+ if (voiceServerReady) {+ await emit({+ event: "message",+ content:+ "The Pulse menu bar app shows live status in your macOS menu bar (running indicator, " ++ "quick access to the Life Dashboard, mute/unmute voice). It builds a small .app bundle " ++ "and installs a second launchd plist that auto-starts on login.",+ });+ const installMenuBarChoice = await getChoice("install-menubar", "Install the Pulse menu bar app?", [+ { label: "Yes — install menu bar app", value: "yes", description: "Adds an icon to your menu bar. Auto-starts on login." },+ { label: "Skip — Pulse runs without menu bar", value: "skip", description: "Pulse keeps running. You can install the menu bar later: bash ~/.claude/PAI/PULSE/MenuBar/install.sh" },+ ], daName);++ if (installMenuBarChoice === "yes") {+ await installPulseMenuBar(paiDir, emit);+ } else {+ await emit({ event: "message", content: "Menu bar skipped. Install later: bash ~/.claude/PAI/PULSE/MenuBar/install.sh" });+ }+ }++ // ── Digital Assistant Voice selection ──+ await emit({ event: "progress", step: "voice", percent: 40, detail: "Choosing Digital Assistant voice..." });++ let selectedVoiceId = "";++ // Check for existing voice config from previous installations — gated on+ // the upfront import permission. Without that consent we never read prior+ // settings.json files.+ if (allowImportPriorConfig) {+ const existingVoice = findExistingVoiceConfig();+ if (existingVoice) {+ const sourceLabel = existingVoice.aiName+ ? `${existingVoice.aiName}'s voice (${existingVoice.voiceId.substring(0, 8)}...)`+ : `Voice ID ${existingVoice.voiceId.substring(0, 8)}...`;+ await emit({ event: "message", content: `Found existing voice configuration in ${existingVoice.source}` });++ const useExisting = await getChoice("voice-existing", `Use ${sourceLabel}?`, [+ { label: "Yes, import this voice ID", value: "keep", description: `Voice ID: ${existingVoice.voiceId}` },+ { label: "No, pick a new voice", value: "new", description: "Choose from the 6 built-in voices, enter a custom ID, or skip" },+ ], daName);++ if (useExisting === "keep") {+ selectedVoiceId = existingVoice.voiceId;+ state.collected.voiceType = "custom";+ state.collected.customVoiceId = selectedVoiceId;+ }+ }+ }++ // Voice picker — 6 built-in voices (2 female, 2 male, 2 neutral), plus+ // Custom Voice ID and Skip Voice. Source of truth for IDs is types.ts+ // (DEFAULT_VOICES). If the user has no ElevenLabs key, "Skip" is the+ // honest path — picking a voice without a key just disables voice anyway.+ if (!selectedVoiceId) {+ await emit({ event: "progress", step: "voice", percent: 45, detail: "Pick a voice for your DA..." });++ const hasKey = !!state.collected.elevenLabsKey;+ const previewText = `Hi, I'll be ${state.collected.aiName || "your assistant"}. This is what I sound like.`;+ const pickerChoices = [+ ...DEFAULT_VOICES.map((v) => ({ label: v.label, value: v.id, description: v.description, voiceId: v.voiceId })),+ { label: "Custom Voice ID", value: "custom", description: "Paste your own ElevenLabs voice ID" },+ { label: "Skip — no voice", value: "skip", description: hasKey ? "Voice disabled (key still saved for later use)" : "Voice disabled (no key was provided)" },+ ];+ const voiceType = voiceServerReady && getChoiceWithPreview+ ? await getChoiceWithPreview("voice-type", "Digital Assistant Voice — Pick the voice your DA speaks with:", pickerChoices, previewText, daName)+ : await getChoice("voice-type", "Digital Assistant Voice — Pick the voice your DA speaks with:", pickerChoices, daName);++ if (voiceType === "skip") {+ selectedVoiceId = "";+ state.collected.voiceType = "skip" as any;+ } else if (voiceType === "custom") {+ const customId = await getInput(+ "custom-voice-id",+ "Enter your ElevenLabs Voice ID:\nFind it at: elevenlabs.io/app/voice-library → Your voice → Voice ID",+ "text",+ "e.g., AyCt0WmAXUcPJR11zeeP",+ daName+ );+ selectedVoiceId = customId.trim();+ if (selectedVoiceId) {+ state.collected.voiceType = "custom";+ state.collected.customVoiceId = selectedVoiceId;+ } else {+ await emit({ event: "message", content: "No custom voice ID entered. Voice will be skipped." });+ state.collected.voiceType = "skip" as any;+ }+ } else {+ const found = DEFAULT_VOICES.find((v) => v.id === voiceType);+ if (found) {+ selectedVoiceId = found.voiceId;+ state.collected.voiceType = voiceType as any;+ } else {+ // Defensive fallback — shouldn't happen unless picker IDs drift+ selectedVoiceId = DEFAULT_VOICES[0].voiceId;+ state.collected.voiceType = DEFAULT_VOICES[0].id as any;+ }+ }+ }++ // If we got here without a key AND without skipping voice, we've still+ // selected a voice ID but TTS will fail at runtime. That's acceptable —+ // the user can add a key later and the voice ID is already saved.+ if (!state.collected.elevenLabsKey && selectedVoiceId) {+ await emit({+ event: "message",+ content:+ "Voice ID saved, but voice is disabled until you add an ElevenLabs API key. " ++ "Edit ~/.config/PAI/.env and set ELEVENLABS_API_KEY=sk_...",+ });+ }++ // ── Update settings.json with voice ID ──+ await emit({ event: "progress", step: "voice", percent: 60, detail: "Saving voice configuration..." });+ const settingsPath = join(paiDir, "settings.json");++ if (existsSync(settingsPath)) {+ try {+ const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));+ if (settings.daidentity) {+ settings.daidentity.voiceId = selectedVoiceId;+ settings.daidentity.voices = settings.daidentity.voices || {};+ settings.daidentity.voices.main = {+ voiceId: selectedVoiceId,+ stability: 0.35,+ similarityBoost: 0.80,+ style: 0.90,+ speed: 1.1,+ };+ settings.daidentity.voices.algorithm = {+ voiceId: selectedVoiceId,+ stability: 0.35,+ similarityBoost: 0.80,+ style: 0.90,+ speed: 1.1,+ };+ }+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2));+ await emit({ event: "message", content: "Voice settings saved to settings.json." });+ } catch {+ // Non-fatal+ }+ }++ // ── Save ElevenLabs key to .env (if provided) ──+ if (hasElevenLabsKey) {+ const configDir = state.detection?.configDir || join(homedir(), ".config", "PAI");+ const envPath = join(configDir, ".env");+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });++ let envContent = existsSync(envPath) ? readFileSync(envPath, "utf-8") : "";+ if (envContent.includes("ELEVENLABS_API_KEY=")) {+ envContent = envContent.replace(/ELEVENLABS_API_KEY=.*/, `ELEVENLABS_API_KEY=${state.collected.elevenLabsKey}`);+ } else {+ envContent = envContent.trim() + `\nELEVENLABS_API_KEY=${state.collected.elevenLabsKey}\n`;+ }+ writeFileSync(envPath, envContent.trim() + "\n", { mode: 0o600 });++ // Ensure symlinks exist at both ~/.claude/.env and ~/.env+ const symlinkTargets = [+ join(paiDir, ".env"),+ join(homedir(), ".env"),+ ];+ for (const sp of symlinkTargets) {+ try {+ if (existsSync(sp)) {+ if (lstatSync(sp).isSymbolicLink()) unlinkSync(sp);+ else continue;+ }+ symlinkSync(envPath, sp);+ } catch { /* non-fatal */ }+ }+ }++ // ── Test TTS and confirm with user ──+ if (voiceServerReady) {+ let voiceConfirmed = false;+ while (!voiceConfirmed) {+ await emit({ event: "progress", step: "voice", percent: 80, detail: "Testing voice output..." });+ try {+ const aiName = state.collected.aiName || "PAI";+ const userName = state.collected.principalName || "there";+ const testRes = await fetch("http://localhost:31337/notify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ message: `Hello ${userName}, this is ${aiName}. My voice system is online and ready to assist you.`,+ voice_id: selectedVoiceId,+ voice_settings: { stability: 0.35, similarity_boost: 0.80, style: 0.90, speed: 1.1, use_speaker_boost: true },+ }),+ signal: AbortSignal.timeout(10000),+ });+ if (testRes.ok) {+ await emit({ event: "message", content: `Voice test sent — listen for ${aiName} speaking...`, speak: false });++ // Ask user to confirm they heard it and like it+ const confirm = await getChoice("voice-confirm", "Did you hear the voice? Does it sound good?", [+ { label: "Sounds great!", value: "yes" },+ { label: "Pick a different voice", value: "change" },+ { label: "Skip voice for now", value: "skip" },+ ], daName);++ if (confirm === "yes") {+ voiceConfirmed = true;+ } else if (confirm === "skip") {+ voiceConfirmed = true;+ } else {+ // Let them pick again+ const retryChoices = [+ ...DEFAULT_VOICES.map((v) => ({ label: v.label, value: v.id, description: v.description, voiceId: v.voiceId })),+ { label: "Custom Voice ID", value: "custom", description: "Enter your own ElevenLabs voice ID" },+ ];+ const retryPreviewText = `Hi, I'll be ${state.collected.aiName || "your assistant"}. This is what I sound like.`;+ const newVoice = getChoiceWithPreview+ ? await getChoiceWithPreview("voice-type-retry", "Choose a different voice:", retryChoices, retryPreviewText, daName)+ : await getChoice("voice-type-retry", "Choose a different voice:", retryChoices, daName);+ if (newVoice === "custom") {+ const newId = await getInput("custom-voice-id-retry", "Enter your ElevenLabs Voice ID:", "text", "e.g., AyCt0WmAXUcPJR11zeeP", daName);+ selectedVoiceId = newId.trim() || selectedVoiceId;+ state.collected.voiceType = "custom";+ state.collected.customVoiceId = selectedVoiceId;+ } else {+ const found = DEFAULT_VOICES.find((v) => v.id === newVoice);+ selectedVoiceId = found?.voiceId || DEFAULT_VOICES[0].voiceId;+ state.collected.voiceType = newVoice as any;+ }+ // Update settings.json with new choice before re-testing+ try {+ const s = JSON.parse(readFileSync(settingsPath, "utf-8"));+ if (s.daidentity?.voices?.main) s.daidentity.voices.main.voiceId = selectedVoiceId;+ if (s.daidentity?.voices?.algorithm) s.daidentity.voices.algorithm.voiceId = selectedVoiceId;+ writeFileSync(settingsPath, JSON.stringify(s, null, 2));+ } catch { /* non-fatal */ }+ }+ } else {+ await emit({ event: "message", content: "Voice test returned an error. Voice may need manual configuration." });+ voiceConfirmed = true;+ }+ } catch {+ await emit({ event: "message", content: "Voice test timed out. Server may still be initializing." });+ voiceConfirmed = true;+ }+ }+ }++ const voiceLabel = state.collected.voiceType === "custom"+ ? `Custom voice (${selectedVoiceId.substring(0, 8)}...)`+ : state.collected.voiceType || "default";+ await emit({ event: "message", content: `Digital Assistant voice configured: ${voiceLabel}` });++ // Reload Pulse so the voice pick we just wrote to settings.json is actually+ // honored at runtime (Pulse caches defaultVoiceId at init — without this+ // restart, every skill curl that omits voice_id stays on the stale template+ // default until the next manual restart).+ await reloadPulse(paiDir, emit);++ await emit({ event: "step_complete", step: "voice" });+}++// ─── Telegram Setup ───────────────────────────────────────────────+//+// Optional step. If the user wants Pulse's Telegram bot to work, we collect+// the bot token + allowed user/chat ID, validate via Telegram getMe, write+// to ~/.claude/.env, then ask Pulse to restart so it picks up the env vars.+//+// Same key-discovery pattern as the voice step: check primary .env first,+// ask permission before scanning .claude* backup directories, fall back to+// manual entry.++interface TelegramValidation { valid: boolean; username?: string; error?: string }++async function validateTelegramBotToken(token: string): Promise<TelegramValidation> {+ try {+ const res = await fetch(`https://api.telegram.org/bot${token}/getMe`, {+ method: "GET",+ signal: AbortSignal.timeout(8000),+ });+ if (!res.ok) {+ const body = await res.text().catch(() => "");+ return { valid: false, error: `Telegram API ${res.status}: ${body.slice(0, 120)}` };+ }+ const data = await res.json() as { ok?: boolean; result?: { username?: string }; description?: string };+ if (!data.ok || !data.result) return { valid: false, error: data.description || "Telegram API rejected token" };+ return { valid: true, username: data.result.username };+ } catch (err: any) {+ return { valid: false, error: err?.message || "Network error contacting Telegram" };+ }+}++async function restartPulse(paiDir: string): Promise<boolean> {+ const manage = join(paiDir, "PAI", "PULSE", "manage.sh");+ if (!existsSync(manage)) return false;+ return new Promise<boolean>((resolve) => {+ const child = spawn("bash", [manage, "restart"], { cwd: dirname(manage), stdio: ["ignore", "pipe", "pipe"] });+ const timer = setTimeout(() => { child.kill(); resolve(false); }, 15000);+ child.on("close", (code) => { clearTimeout(timer); resolve(code === 0); });+ child.on("error", () => { clearTimeout(timer); resolve(false); });+ });+}++function writeEnvKey(envPath: string, key: string, value: string): void {+ let content = existsSync(envPath) ? readFileSync(envPath, "utf-8") : "";+ const re = new RegExp(`^${key}=.*$`, "m");+ if (re.test(content)) {+ content = content.replace(re, `${key}=${value}`);+ } else {+ content = (content.trimEnd() + `\n${key}=${value}\n`).trimStart();+ }+ writeFileSync(envPath, content, { mode: 0o600 });+}++export async function runTelegramSetup(+ state: InstallState,+ emit: EngineEventHandler,+ getChoice: (id: string, prompt: string, choices: { label: string; value: string; description?: string }[]) => Promise<string>,+ getInput: (id: string, prompt: string, type: "text" | "password" | "key", placeholder?: string) => Promise<string>+): Promise<void> {+ await emit({ event: "step_start", step: "telegram" });+ await emitSectionHeader(+ emit,+ "TELEGRAM-OPTIONAL",+ "TELEGRAM (OPTIONAL)",+ "Connecting Pulse to a Telegram bot for chat and notifications",+ 8+ );++ await emit({+ event: "message",+ content:+ "Optional: Telegram bot integration. Pulse can run a Telegram bot that lets you " ++ "chat with your DA from your phone and pushes long-task notifications. " ++ "Requires a bot token from @BotFather and your Telegram user/chat ID.",+ });++ const wantsTelegram = await getChoice("telegram-enable", "Set up Telegram now?", [+ { label: "Yes — I have a bot token from BotFather", value: "yes" },+ { label: "Skip — I'll set this up later (or never)", value: "skip", description: "Pulse runs fine without Telegram. Add later via ~/.claude/.env" },+ ]);++ if (wantsTelegram !== "yes") {+ await emit({ event: "message", content: "Skipped Telegram setup. Add later: TELEGRAM_BOT_TOKEN and TELEGRAM_ALLOWED_USERS in ~/.claude/.env, then bash ~/.claude/PAI/PULSE/manage.sh restart" });+ skipStep(state, "telegram", "user-skipped");+ return;+ }++ const paiDir = state.detection?.paiDir || join(homedir(), ".claude");++ // ── Step 1: Check primary .env locations (no permission needed) ──+ let token = findExistingEnvKey("TELEGRAM_BOT_TOKEN");+ let validation: TelegramValidation = { valid: false };++ if (token) {+ await emit({ event: "message", content: "Found existing TELEGRAM_BOT_TOKEN. Validating..." });+ validation = await validateTelegramBotToken(token);+ if (!validation.valid) {+ await emit({ event: "message", content: `Existing token invalid: ${validation.error}.` });+ token = "";+ }+ }++ // ── Step 2: Offer to scan backup .claude* dirs (with permission) ──+ if (!token) {+ const backupHits = findKeyInBackupDirs("TELEGRAM_BOT_TOKEN");+ if (backupHits.length > 0) {+ const sources = backupHits.map(h => h.path.replace(homedir(), "~")).join(", ");+ const allow = await getChoice("telegram-scan-backup", `Found Telegram bot tokens in backup directories: ${sources}. Use one of them?`, [+ { label: "Yes — try the backup token(s)", value: "yes", description: "We'll validate each via Telegram getMe and use the first that works." },+ { label: "No — I'll enter a fresh token", value: "no" },+ ]);+ if (allow === "yes") {+ for (const hit of backupHits) {+ await emit({ event: "progress", step: "telegram", percent: 15, detail: `Validating token from ${hit.path.replace(homedir(), "~")}...` });+ const result = await validateTelegramBotToken(hit.value);+ if (result.valid) {+ token = hit.value;+ validation = result;+ await emit({ event: "message", content: `Using Telegram bot token from ${hit.path.replace(homedir(), "~")} (bot @${result.username}).` });+ break;+ } else {+ await emit({ event: "message", content: `Token from ${hit.path.replace(homedir(), "~")} invalid: ${result.error}.` });+ }+ }+ }+ }+ }++ // ── Step 3: Manual entry ──+ if (!token) {+ const entered = await getInput(+ "telegram-bot-token",+ "Paste your Telegram bot token (from @BotFather):",+ "key",+ "1234567890:ABCdefGHI..."+ );+ const trimmed = entered.trim();+ if (!trimmed) {+ await emit({ event: "message", content: "No token entered. Skipping Telegram setup." });+ skipStep(state, "telegram", "no-token-entered");+ return;+ }+ await emit({ event: "progress", step: "telegram", percent: 30, detail: "Validating token via Telegram getMe..." });+ const result = await validateTelegramBotToken(trimmed);+ if (!result.valid) {+ await emit({ event: "message", content: `Token validation failed: ${result.error}. Skipping Telegram setup.` });+ skipStep(state, "telegram", "invalid-token");+ return;+ }+ token = trimmed;+ validation = result;+ await emit({ event: "message", content: `Bot validated: @${result.username}` });+ }++ // ── Step 4: Allowed users / chat ID ──+ // Reuse from primary .env first, fall back to prompt.+ let allowedUsers = findExistingEnvKey("TELEGRAM_ALLOWED_USERS") || findExistingEnvKey("TELEGRAM_PRINCIPAL_CHAT_ID");+ if (!allowedUsers) {+ const entered = await getInput(+ "telegram-allowed-users",+ "Enter your Telegram user ID or chat ID (find it via @userinfobot):",+ "text",+ "123456789"+ );+ allowedUsers = entered.trim();+ }+ if (!allowedUsers) {+ await emit({ event: "message", content: "No allowed user/chat ID provided. Bot will not respond to anyone (unsafe). Skipping." });+ skipStep(state, "telegram", "no-allowed-users");+ return;+ }++ // ── Step 5: Persist to ~/.claude/.env and restart Pulse ──+ state.collected.telegramBotToken = token;+ state.collected.telegramAllowedUsers = allowedUsers;+ state.collected.telegramBotUsername = validation.username;++ try {+ const envPath = join(paiDir, ".env");+ writeEnvKey(envPath, "TELEGRAM_BOT_TOKEN", token);+ writeEnvKey(envPath, "TELEGRAM_ALLOWED_USERS", allowedUsers);+ await emit({ event: "message", content: "Telegram credentials written to ~/.claude/.env." });+ } catch (err: any) {+ await emit({ event: "message", content: `Could not write .env: ${err?.message || err}. Telegram bot will not start.` });+ skipStep(state, "telegram", "env-write-failed");+ return;+ }++ // Pulse may already be running from the voice step; restart so it picks up env.+ await emit({ event: "progress", step: "telegram", percent: 80, detail: "Restarting Pulse to pick up Telegram credentials..." });+ const restarted = await restartPulse(paiDir);+ await emit({+ event: "message",+ content: restarted+ ? `Pulse restarted. Telegram bot @${validation.username} is now polling.`+ : `Pulse not restarted automatically — run: bash ~/.claude/PAI/PULSE/manage.sh restart`,+ });++ await emit({ event: "step_complete", step: "telegram" });+}++// Helper used by runTelegramSetup. Local re-export shim to avoid touching the+// generic skip flow up top — the runners already handle skippedSteps.+function skipStep(state: InstallState, step: StepId, _reason: string): void {+ if (!state.skippedSteps.includes(step)) state.skippedSteps.push(step);+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/config-gen.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/config-gen.tsnew file mode 100644index 00000000..7692863e--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/config-gen.ts@@ -0,0 +1,71 @@+/**+ * PAI Installer v5.0 — Configuration Generator+ * Generates a FALLBACK settings.json from collected user data.+ * Only used when no existing settings.json exists.+ * Produces minimal output — just fields the installer collects.+ * Hooks, permissions, and other config come from the release template.+ */++import type { PAIConfig } from "./types";+import { DEFAULT_VOICES, PAI_VERSION, ALGORITHM_VERSION } from "./types";++/**+ * Generate a minimal fallback settings.json from installer-collected data.+ * This is merged into (not replacing) the release template.+ */+export function generateSettingsJson(config: PAIConfig): Record<string, any> {+ const voiceId = config.voiceId || DEFAULT_VOICES[config.voiceType as keyof typeof DEFAULT_VOICES] || DEFAULT_VOICES.female;++ return {+ env: {+ // PAI_DIR is the PAI subsystem directory (~/.claude/PAI) — where Memory,+ // Algorithm, USER, TOOLS, PULSE live. NOT the install root (~/.claude).+ // statusline-command.sh, hooks, and tools read PAI_DIR expecting the /PAI+ // suffix; if we write just `~/.claude` here the statusline can't find+ // ALGORITHM/LATEST and falls back to "—". The variable name `config.paiDir`+ // is misleading — it's actually the INSTALL ROOT.+ PAI_DIR: `${config.paiDir}/PAI`,+ ...(config.projectsDir ? { PROJECTS_DIR: config.projectsDir } : {}),+ PAI_CONFIG_DIR: config.configDir,+ },++ contextFiles: [+ "skills/PAI/SKILL.md",+ "skills/PAI/AISTEERINGRULES.md",+ "skills/PAI/USER/AISTEERINGRULES.md",+ "skills/PAI/USER/DAIDENTITY.md",+ ],++ daidentity: {+ name: config.aiName,+ fullName: `${config.aiName} — Personal AI`,+ displayName: config.aiName.toUpperCase(),+ color: "#3B82F6",+ voices: {+ main: {+ voiceId,+ stability: 0.35,+ similarityBoost: 0.80,+ style: 0.90,+ speed: 1.1,+ },+ },+ startupCatchphrase: config.catchphrase,+ },++ principal: {+ name: config.principalName,+ timezone: config.timezone,+ },++ preferences: {+ temperatureUnit: config.temperatureUnit || "fahrenheit",+ },++ pai: {+ repoUrl: "https://github.com/danielmiessler/PAI",+ version: PAI_VERSION,+ algorithmVersion: ALGORITHM_VERSION,+ },+ };+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/detect.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/detect.tsnew file mode 100644index 00000000..9cc97598--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/detect.ts@@ -0,0 +1,397 @@+/**+ * PAI Installer v5.0 — System Detection+ * Detects OS, tools, existing PAI installation, and environment.+ * All detection is read-only and non-destructive.+ */++import { execSync } from "child_process";+import { existsSync, readFileSync } from "fs";+import { homedir } from "os";+import { join } from "path";+import type { DetectionResult, ExistingUserContentDetection } from "./types";++function tryExec(cmd: string): string | null {+ try {+ return execSync(cmd, { timeout: 5000, stdio: ["pipe", "pipe", "pipe"] })+ .toString()+ .trim();+ } catch {+ return null;+ }+}++function detectOS(): DetectionResult["os"] {+ const platform = process.platform === "darwin" ? "darwin" : "linux";+ const arch = process.arch;++ let version = "";+ let name = "";++ if (platform === "darwin") {+ const swVers = tryExec("sw_vers -productVersion");+ version = swVers || "";+ name = `macOS ${version}`;+ } else {+ const release = tryExec("cat /etc/os-release 2>/dev/null | grep PRETTY_NAME | cut -d= -f2 | tr -d '\"'");+ name = release || "Linux";+ version = tryExec("uname -r") || "";+ }++ return { platform, arch, version, name };+}++function detectShell(): DetectionResult["shell"] {+ const shellPath = process.env.SHELL || "/bin/sh";+ const shellName = shellPath.split("/").pop() || "sh";+ const version = tryExec(`${shellPath} --version 2>&1 | head -1`) || "";++ return { name: shellName, version, path: shellPath };+}++function detectTool(+ name: string,+ versionCmd: string+): { installed: boolean; version?: string; path?: string } {+ const path = tryExec(`which ${name}`);+ if (!path) return { installed: false };++ const versionOutput = tryExec(versionCmd);+ // Extract version number from output+ const versionMatch = versionOutput?.match(/(\d+\.\d+[\.\d]*)/);+ const version = versionMatch?.[1] || versionOutput || undefined;++ return { installed: true, version, path };+}++function detectExisting(+ home: string,+ paiDir: string,+ _configDir: string+): DetectionResult["existing"] {+ const result: DetectionResult["existing"] = {+ paiInstalled: false,+ hasApiKeys: false,+ elevenLabsKeyFound: false,+ backupPaths: [],+ apiKeys: {},+ };++ // Check for existing PAI installation+ const settingsPath = join(paiDir, "settings.json");+ if (existsSync(settingsPath)) {+ result.paiInstalled = true;+ result.settingsPath = settingsPath;+ }++ // Check for existing PAI skill+ if (existsSync(join(paiDir, "skills", "PAI", "SKILL.md"))) {+ result.paiInstalled = true;+ }++ // Check for backup directories+ const backupPatterns = [+ join(home, ".claude-backup"),+ join(home, ".claude-old"),+ join(home, ".claude-BACKUP"),+ join(home, ".claude.bak"),+ ];+ for (const bp of backupPatterns) {+ if (existsSync(bp)) {+ result.backupPaths.push(bp);+ }+ }+ return result;+}++/**+ * Scan shell rc files and config dirs for API-key VALUES. Returns a map of+ * provider → key. Only well-formed assignments are accepted (no `$VAR`+ * indirection, no obvious placeholders).+ */+export function scanApiKeys(+ home: string,+ configDir: string+): NonNullable<DetectionResult["existing"]["apiKeys"]> {+ const candidates = [+ join(home, ".zshenv"),+ join(home, ".zshrc"),+ join(home, ".zprofile"),+ join(home, ".bashrc"),+ join(home, ".bash_profile"),+ join(home, ".profile"),+ join(configDir, ".env"),+ join(configDir, "credentials.env"),+ join(home, ".config", "PAI", ".env"),+ join(home, ".config", "PAI", "credentials.env"),+ ];++ const patterns: Array<[keyof NonNullable<DetectionResult["existing"]["apiKeys"]>, RegExp]> = [+ ["elevenLabs", /(?:^|\n)\s*(?:export\s+)?ELEVENLABS_API_KEY\s*=\s*["']?([^"'\s#]+)/],+ ["anthropic", /(?:^|\n)\s*(?:export\s+)?ANTHROPIC_API_KEY\s*=\s*["']?([^"'\s#]+)/],+ ["openai", /(?:^|\n)\s*(?:export\s+)?OPENAI_API_KEY\s*=\s*["']?([^"'\s#]+)/],+ ["google", /(?:^|\n)\s*(?:export\s+)?(?:GEMINI_API_KEY|GOOGLE_API_KEY|GOOGLE_GENAI_API_KEY)\s*=\s*["']?([^"'\s#]+)/],+ ["xai", /(?:^|\n)\s*(?:export\s+)?(?:XAI_API_KEY|GROK_API_KEY)\s*=\s*["']?([^"'\s#]+)/],+ ["perplexity", /(?:^|\n)\s*(?:export\s+)?PERPLEXITY_API_KEY\s*=\s*["']?([^"'\s#]+)/],+ ];++ const placeholderHints = /^(your-key-here|sk-xxxxxxxx|xxxxx|REPLACE_ME|TODO)/i;+ const found: NonNullable<DetectionResult["existing"]["apiKeys"]> = {};++ for (const file of candidates) {+ if (!existsSync(file)) continue;+ let content: string;+ try {+ content = readFileSync(file, "utf-8");+ } catch {+ continue; // permission denied, etc.+ }+ for (const [provider, regex] of patterns) {+ if (found[provider]) continue;+ const m = content.match(regex);+ if (!m) continue;+ const value = m[1];+ if (value.startsWith("$")) continue; // `KEY=$OTHER_VAR` indirection+ if (placeholderHints.test(value)) continue;+ if (value.length < 12) continue; // empty / obviously stub+ found[provider] = value;+ }+ }++ return found;+}++/**+ * Try to recover the DA's name from a prior install or any backup tree. Reads+ * `PAI/USER/DA_IDENTITY.md` (or .yaml) and pulls the name from the title line+ * (`# DA Identity — Atlas`) or a `name:` frontmatter / yaml field.+ */+function detectDaName(paiDir: string, backupPaths: string[]): string | undefined {+ const roots = [paiDir, ...backupPaths];+ const relCandidates = [+ "PAI/USER/DA_IDENTITY.md",+ "PAI/USER/DA_IDENTITY.yaml",+ "PAI/USER/DA/IDENTITY.md",+ ];++ for (const root of roots) {+ for (const rel of relCandidates) {+ const p = join(root, rel);+ if (!existsSync(p)) continue;+ let content: string;+ try {+ content = readFileSync(p, "utf-8");+ } catch {+ continue;+ }+ // `# DA Identity — Atlas` or `# DA Identity - Atlas`+ const titleMatch = content.match(/^#\s*DA Identity\s*[—–-]\s*([A-Za-z][\w\s'-]+?)\s*$/m);+ if (titleMatch) return titleMatch[1].trim();+ // YAML/frontmatter `name: Atlas`+ const yamlMatch = content.match(/^\s*name:\s*["']?([A-Za-z][\w\s'-]+?)["']?\s*$/m);+ if (yamlMatch) return yamlMatch[1].trim();+ }+ }+ return undefined;+}++function fileExists(root: string, relPath: string): boolean {+ return existsSync(join(root, relPath));+}++function countGoals(goalsPath: string): number {+ if (!existsSync(goalsPath)) return 0;+ try {+ const content = readFileSync(goalsPath, "utf-8");+ const matches = content.match(/^\s*-\s*(?:\*\*G|G)/gm);+ return matches?.length || 0;+ } catch {+ return 0;+ }+}++function countContacts(contactsPath: string): number {+ if (!existsSync(contactsPath)) return 0;+ try {+ const content = readFileSync(contactsPath, "utf-8");+ return content+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => /^##\s+/.test(line) || /^[-*]\s+/.test(line)).length;+ } catch {+ return 0;+ }+}++function countProjectRows(projectsPath: string): number {+ if (!existsSync(projectsPath)) return 0;+ try {+ const lines = readFileSync(projectsPath, "utf-8").split("\n");+ const separatorIndex = lines.findIndex((line) => /^\s*\|?\s*[-:]+\s*\|/.test(line));+ if (separatorIndex === -1) return 0;+ return lines+ .slice(separatorIndex + 1)+ .map((line) => line.trim())+ .filter((line) => line.startsWith("|") && !/^\|\s*[-:]+\s*\|?$/.test(line))+ .length;+ } catch {+ return 0;+ }+}++export function detectExistingUserContent(paiUserDir: string): ExistingUserContentDetection {+ return {+ telos: {+ mission: fileExists(paiUserDir, "TELOS/MISSION.md"),+ goals: fileExists(paiUserDir, "TELOS/GOALS.md"),+ goalsCount: countGoals(join(paiUserDir, "TELOS", "GOALS.md")),+ activeProblems: fileExists(paiUserDir, "TELOS/ACTIVE_PROBLEMS.md"),+ strategy: fileExists(paiUserDir, "TELOS/STRATEGY.md"),+ principles: fileExists(paiUserDir, "TELOS/PRINCIPLES.md"),+ areas: fileExists(paiUserDir, "TELOS/AREAS.md"),+ now: fileExists(paiUserDir, "TELOS/NOW.md"),+ },+ identity: {+ principalIdentity: fileExists(paiUserDir, "PRINCIPAL_IDENTITY.md"),+ daIdentity: fileExists(paiUserDir, "DA_IDENTITY.md"),+ daIdentityYaml: fileExists(paiUserDir, "DA_IDENTITY.yaml"),+ workingStyle: fileExists(paiUserDir, "WORKINGSTYLE.md"),+ rhetoricalStyle: fileExists(paiUserDir, "RHETORICALSTYLE.md"),+ aiWritingPatterns: fileExists(paiUserDir, "AI_WRITING_PATTERNS.md"),+ feed: fileExists(paiUserDir, "FEED.md"),+ resume: fileExists(paiUserDir, "RESUME.md"),+ ourStory: fileExists(paiUserDir, "OUR_STORY.md"),+ definitions: fileExists(paiUserDir, "DEFINITIONS.md"),+ coreContent: fileExists(paiUserDir, "CORECONTENT.md"),+ beliefs: fileExists(paiUserDir, "BELIEFS.md"),+ },+ contacts: {+ contacts: fileExists(paiUserDir, "CONTACTS.md"),+ count: countContacts(join(paiUserDir, "CONTACTS.md")),+ },+ opinions: {+ opinions: fileExists(paiUserDir, "OPINIONS.md"),+ },+ projects: {+ projectsIndex: fileExists(paiUserDir, "PROJECTS.md"),+ projectsDirectory: fileExists(paiUserDir, "PROJECTS"),+ count: countProjectRows(join(paiUserDir, "PROJECTS.md")),+ },+ business: {+ present: fileExists(paiUserDir, "BUSINESS") || fileExists(paiUserDir, "BUSINESS.md"),+ },+ finances: {+ present: fileExists(paiUserDir, "FINANCES") || fileExists(paiUserDir, "FINANCES.md"),+ },+ health: {+ present: fileExists(paiUserDir, "HEALTH") || fileExists(paiUserDir, "HEALTH.md"),+ },+ };+}++/**+ * Detect the principal's likely name + email from the local machine.+ * Order of preference: git config (most explicit) → macOS RealName → $USER.+ */+function detectPrincipal(): DetectionResult["principal"] {+ const username = process.env.USER || process.env.LOGNAME || "user";++ const gitName = tryExec("git config --global user.name");+ const gitEmail = tryExec("git config --global user.email");++ let realName: string | null = null;+ if (process.platform === "darwin") {+ // dscl returns "RealName:\n First Last" — strip header + leading space+ const dscl = tryExec(`dscl . -read /Users/${username} RealName 2>/dev/null`);+ if (dscl) {+ const m = dscl.match(/RealName:\s*\n?\s*(.+)/);+ if (m) realName = m[1].trim();+ }+ if (!realName) realName = tryExec("id -F 2>/dev/null");+ }++ // Reject obvious placeholders that show up on fresh installs+ const looksReal = (s: string | null | undefined): s is string =>+ !!s && s !== username && s !== "Apple" && s.length > 1;++ const name = looksReal(gitName) ? gitName : looksReal(realName) ? realName : undefined;++ return {+ name,+ email: gitEmail || undefined,+ username,+ };+}++/**+ * macOS-only: read the system speech default voice. Skipped on Linux.+ */+function detectVoice(): DetectionResult["voice"] {+ if (process.platform !== "darwin") return undefined;+ const v = tryExec("defaults read com.apple.speech.synthesis.general.prefs SelectedVoiceName 2>/dev/null");+ if (!v) return undefined;+ return { systemDefault: v };+}++/**+ * Run full system detection. Safe, read-only, non-destructive.+ */+export function detectSystem(): DetectionResult {+ const home = homedir();+ const paiDir = join(home, ".claude");+ const configDir = process.env.PAI_CONFIG_DIR || join(home, ".config", "PAI");++ return {+ os: detectOS(),+ shell: detectShell(),+ tools: {+ bun: detectTool("bun", "bun --version"),+ git: detectTool("git", "git --version"),+ claude: detectTool("claude", "claude --version 2>&1"),+ node: detectTool("node", "node --version"),+ brew: {+ installed: tryExec("which brew") !== null,+ path: tryExec("which brew") || undefined,+ },+ },+ existing: detectExisting(home, paiDir, configDir),+ principal: detectPrincipal(),+ voice: detectVoice(),+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ homeDir: home,+ paiDir,+ configDir,+ };+}++/**+ * Validate an ElevenLabs API key.+ * Uses /v1/voices endpoint (requires only xi-api-key header, no specific scope)+ * instead of /v1/user (requires user_read permission, which many keys lack).+ * Also handles 401 with missing_permissions as "valid key, limited scope" —+ * TTS works fine with a known voice_id even without voices_read permission.+ */+export async function validateElevenLabsKey(key: string): Promise<{ valid: boolean; error?: string }> {+ try {+ const res = await fetch("https://api.elevenlabs.io/v1/voices", {+ headers: { "xi-api-key": key },+ signal: AbortSignal.timeout(10000),+ });++ if (res.ok) return { valid: true };++ // 401 with missing_permissions means the key IS valid but lacks a specific scope.+ // TTS still works (doesn't need voices_read to use a known voice_id).+ if (res.status === 401) {+ try {+ const body = await res.json();+ if (body?.detail?.status === "missing_permissions") {+ return { valid: true };+ }+ } catch { /* fall through to error */ }+ }++ return { valid: false, error: `HTTP ${res.status}` };+ } catch (e: any) {+ return { valid: false, error: e.message || "Network error" };+ }+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/index.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/index.tsnew file mode 100644index 00000000..170770b1--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/index.ts@@ -0,0 +1,12 @@+/**+ * PAI Installer v5.0 — Engine Entry Point+ * Re-exports all engine modules for convenient importing.+ */++export * from "./types";+export * from "./detect";+export * from "./steps";+export * from "./state";+export * from "./actions";+export * from "./config-gen";+export * from "./validate";diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/state.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/state.tsnew file mode 100644index 00000000..32f14984--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/state.ts@@ -0,0 +1,134 @@+/**+ * PAI Installer v5.0 — State Persistence+ * Manages install state to support resume from interruption.+ */++import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from "fs";+import { homedir } from "os";+import { join, dirname } from "path";+import type { InstallState, StepId } from "./types";+import { INSTALLER_VERSION } from "./types";++const STATE_FILE = join(+ process.env.PAI_CONFIG_DIR || join(homedir(), ".config", "PAI"),+ "PAI-Install",+ "install-state.json"+);++/**+ * Create a fresh install state.+ */+export function createFreshState(mode: "cli" | "web"): InstallState {+ return {+ version: INSTALLER_VERSION,+ startedAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ currentStep: "system-detect",+ completedSteps: [],+ skippedSteps: [],+ mode,+ detection: null,+ collected: {},+ installType: null,+ errors: [],+ };+}++/**+ * Check if a saved state exists.+ */+export function hasSavedState(): boolean {+ return existsSync(STATE_FILE);+}++/**+ * Load saved install state from disk.+ * Returns null if no state exists or it's corrupted.+ */+export function loadState(): InstallState | null {+ if (!existsSync(STATE_FILE)) return null;++ try {+ const raw = readFileSync(STATE_FILE, "utf-8");+ const state = JSON.parse(raw) as InstallState;++ // Validate basic structure+ if (!state.version || !state.startedAt || !state.currentStep) {+ return null;+ }++ return state;+ } catch {+ return null;+ }+}++/**+ * Save install state to disk.+ */+export function saveState(state: InstallState): void {+ state.updatedAt = new Date().toISOString();++ const dir = dirname(STATE_FILE);+ if (!existsSync(dir)) {+ mkdirSync(dir, { recursive: true });+ }++ writeFileSync(STATE_FILE, JSON.stringify(state, null, 2), { mode: 0o600 });+}++/**+ * Remove saved state (after successful install).+ */+export function clearState(): void {+ if (existsSync(STATE_FILE)) {+ unlinkSync(STATE_FILE);+ }+}++/**+ * Mark a step as completed and advance to the next.+ */+export function completeStep(state: InstallState, step: StepId): void {+ if (!state.completedSteps.includes(step)) {+ state.completedSteps.push(step);+ }+ saveState(state);+}++/**+ * Mark a step as skipped.+ */+export function skipStep(state: InstallState, step: StepId, reason?: string): void {+ if (!state.skippedSteps.includes(step)) {+ state.skippedSteps.push(step);+ }+ saveState(state);+}++/**+ * Record an error for a step.+ */+export function recordError(+ state: InstallState,+ step: StepId,+ message: string,+ recoverable: boolean = true+): void {+ state.errors.push({+ step,+ message,+ timestamp: new Date().toISOString(),+ recoverable,+ });+ saveState(state);+}++/**+ * Mask API keys for safe logging/display.+ * Shows first 8 chars and masks the rest.+ */+export function maskKey(key: string): string {+ if (!key || key.length <= 12) return "***";+ return key.substring(0, 8) + "..." + key.substring(key.length - 4);+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/steps.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/steps.tsnew file mode 100644index 00000000..d2991491--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/steps.ts@@ -0,0 +1,149 @@+/**+ * PAI Installer v5.0 — Step Definitions+ * Defines the 8 installation steps, their dependencies, and conditions.+ */++import type { StepDefinition, StepId, InstallState } from "./types";++export const STEPS: StepDefinition[] = [+ {+ id: "system-detect",+ name: "System Detection",+ description: "Detect operating system, installed tools, and existing PAI installation",+ number: 1,+ required: true,+ dependsOn: [],+ },+ {+ id: "prerequisites",+ name: "Prerequisites",+ description: "Install required tools: Git, Bun, Claude Code",+ number: 2,+ required: true,+ dependsOn: ["system-detect"],+ },+ {+ id: "api-keys",+ name: "API Keys",+ description: "Find or collect ElevenLabs API key for voice features",+ number: 3,+ required: true,+ dependsOn: ["prerequisites"],+ },+ {+ id: "identity",+ name: "Identity",+ description: "Configure your name, AI assistant name, timezone, and catchphrase",+ number: 4,+ required: true,+ dependsOn: ["api-keys"],+ },+ {+ id: "repository",+ name: "PAI Repository",+ description: "Clone or update the PAI repository into ~/.claude",+ number: 5,+ required: true,+ dependsOn: ["identity"],+ },+ {+ id: "configuration",+ name: "Configuration",+ description: "Generate settings.json, environment files, and directory structure",+ number: 6,+ required: true,+ dependsOn: ["repository"],+ },+ {+ id: "voice",+ name: "Digital Assistant Voice",+ description: "Configure ElevenLabs key, select voice, start voice server, and test",+ number: 7,+ required: true,+ dependsOn: ["configuration"],+ },+ {+ id: "telegram",+ name: "Telegram Bot (optional)",+ description: "Optional: connect a Telegram bot so Pulse can chat with you and send notifications",+ number: 8,+ required: false,+ dependsOn: ["voice"],+ },+ {+ id: "validation",+ name: "Validation",+ description: "Verify installation completeness and show summary",+ number: 9,+ required: true,+ dependsOn: ["telegram"],+ },+];++/**+ * Get a step definition by ID.+ */+export function getStep(id: StepId): StepDefinition {+ const step = STEPS.find((s) => s.id === id);+ if (!step) throw new Error(`Unknown step: ${id}`);+ return step;+}++/**+ * Get the next step to execute based on current state.+ */+export function getNextStep(state: InstallState): StepDefinition | null {+ for (const step of STEPS) {+ // Skip completed and skipped steps+ if (state.completedSteps.includes(step.id)) continue;+ if (state.skippedSteps.includes(step.id)) continue;++ // Check if condition allows this step+ if (step.condition && !step.condition(state)) {+ continue;+ }++ // Check dependencies are met+ const depsReady = step.dependsOn.every(+ (dep) => state.completedSteps.includes(dep) || state.skippedSteps.includes(dep)+ );+ if (!depsReady) continue;++ return step;+ }+ return null; // All steps done+}++/**+ * Get all steps with their current status.+ */+export function getStepStatuses(state: InstallState): Array<StepDefinition & { status: string }> {+ return STEPS.map((step) => {+ let status: string;+ if (state.completedSteps.includes(step.id)) {+ status = "completed";+ } else if (state.skippedSteps.includes(step.id)) {+ status = "skipped";+ } else if (state.currentStep === step.id) {+ status = "active";+ } else if (step.condition && !step.condition(state)) {+ status = "skipped";+ } else {+ status = "pending";+ }+ return { ...step, status };+ });+}++/**+ * Calculate overall progress percentage.+ */+export function getProgress(state: InstallState): number {+ const applicableSteps = STEPS.filter(+ (s) => !s.condition || s.condition(state)+ );+ const done = applicableSteps.filter(+ (s) => state.completedSteps.includes(s.id) || state.skippedSteps.includes(s.id)+ );+ return Math.round((done.length / applicableSteps.length) * 100);+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/types.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/types.tsnew file mode 100644index 00000000..288002da--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/types.ts@@ -0,0 +1,304 @@+/**+ * PAI Installer v5.0 — Type Definitions+ * Shared types for engine, CLI, and web frontends.+ */++// ─── System Detection ────────────────────────────────────────────++export interface DetectionResult {+ os: {+ platform: "darwin" | "linux";+ arch: string;+ version: string;+ name: string; // e.g., "macOS 15.2" or "Ubuntu 24.04"+ };+ shell: {+ name: string;+ version: string;+ path: string;+ };+ tools: {+ bun: { installed: boolean; version?: string; path?: string };+ git: { installed: boolean; version?: string; path?: string };+ claude: { installed: boolean; version?: string; path?: string };+ node: { installed: boolean; version?: string; path?: string };+ brew: { installed: boolean; path?: string }; // macOS only+ };+ existing: {+ paiInstalled: boolean;+ paiVersion?: string;+ settingsPath?: string;+ hasApiKeys: boolean;+ elevenLabsKeyFound: boolean;+ backupPaths: string[];+ /** DA name recovered from a prior install or backup (DA_IDENTITY.md / settings.json). */+ daName?: string;+ /** API key VALUES recovered from shell rc files / .env / prior install — not just presence flags. */+ apiKeys: {+ elevenLabs?: string;+ anthropic?: string;+ openai?: string;+ google?: string;+ xai?: string;+ perplexity?: string;+ };+ };+ existingUserContent?: ExistingUserContentDetection;+ /** Principal identity scanned from the local machine (git config, macOS dscl, $USER). */+ principal: {+ /** Full name: prefers `git config user.name`, falls back to macOS RealName, then $USER. */+ name?: string;+ /** Email from `git config user.email`. */+ email?: string;+ /** OS login name; always populated. */+ username: string;+ };+ /** Voice preferences detected from the OS. */+ voice?: {+ /** macOS default speech voice (`defaults read com.apple.speech.synthesis.general.prefs SelectedVoiceName`). */+ systemDefault?: string;+ };+ timezone: string;+ homeDir: string;+ paiDir: string; // resolved ~/.claude+ configDir: string; // resolved ~/.claude/PAI+}++export interface ExistingUserContentDetection {+ telos: {+ mission: boolean;+ goals: boolean;+ goalsCount: number;+ activeProblems: boolean;+ strategy: boolean;+ principles: boolean;+ areas: boolean;+ now: boolean;+ };+ identity: {+ principalIdentity: boolean;+ daIdentity: boolean;+ daIdentityYaml: boolean;+ workingStyle: boolean;+ rhetoricalStyle: boolean;+ aiWritingPatterns: boolean;+ feed: boolean;+ resume: boolean;+ ourStory: boolean;+ definitions: boolean;+ coreContent: boolean;+ beliefs: boolean;+ };+ contacts: {+ contacts: boolean;+ count: number;+ };+ opinions: {+ opinions: boolean;+ };+ projects: {+ projectsIndex: boolean;+ projectsDirectory: boolean;+ count: number;+ };+ business: {+ present: boolean;+ };+ finances: {+ present: boolean;+ };+ health: {+ present: boolean;+ };+}++// ─── Install Steps ───────────────────────────────────────────────++export type StepId =+ | "system-detect"+ | "prerequisites"+ | "api-keys"+ | "identity"+ | "repository"+ | "configuration"+ | "voice"+ | "telegram"+ | "validation";++export interface StepDefinition {+ id: StepId;+ name: string;+ description: string;+ number: number; // 1-8+ required: boolean;+ dependsOn: StepId[];+ condition?: (state: InstallState) => boolean; // skip if false+}++export type StepStatus = "pending" | "active" | "completed" | "skipped" | "failed";++// ─── Install State ───────────────────────────────────────────────++export interface InstallState {+ version: string;+ startedAt: string;+ updatedAt: string;+ currentStep: StepId;+ completedSteps: StepId[];+ skippedSteps: StepId[];+ mode: "cli" | "web";++ // Detection cache+ detection: DetectionResult | null;+ backupPath?: string;++ // Collected data+ collected: {+ elevenLabsKey?: string;+ scanConsent?: "yes-full" | "yes-id" | "no";+ principalName?: string;+ timezone?: string;+ aiName?: string;+ catchphrase?: string;+ projectsDir?: string;+ temperatureUnit?: "fahrenheit" | "celsius";+ voiceType?: "female" | "male" | "custom";+ customVoiceId?: string;+ telegramBotToken?: string;+ telegramAllowedUsers?: string;+ telegramBotUsername?: string;+ };++ // Results+ installType: "fresh" | "upgrade" | null;+ errors: StepError[];+}++export interface StepError {+ step: StepId;+ message: string;+ timestamp: string;+ recoverable: boolean;+}++// ─── Configuration ───────────────────────────────────────────────++export interface PAIConfig {+ principalName: string;+ timezone: string;+ aiName: string;+ catchphrase: string;+ projectsDir?: string;+ temperatureUnit?: "fahrenheit" | "celsius";+ voiceType?: string;+ voiceId?: string;+ paiDir: string;+ configDir: string;+}++// ─── WebSocket Protocol ──────────────────────────────────────────++// Server → Client messages+export type ServerMessage =+ | { type: "connected"; port: number }+ | { type: "section_header"; sectionId: string; title: string; subtitle?: string; stepNumber?: number }+ | { type: "step_update"; step: StepId; status: StepStatus; detail?: string }+ | { type: "detection_result"; data: DetectionResult }+ | { type: "message"; role: "assistant" | "system"; content: string; speak?: boolean }+ | { type: "input_request"; id: string; prompt: string; inputType: "text" | "password" | "key"; placeholder?: string }+ | { type: "choice_request"; id: string; prompt: string; choices: { label: string; value: string; description?: string }[] }+ | { type: "progress"; step: StepId; percent: number; detail: string }+ | { type: "voice_enabled"; enabled: boolean; mode: "elevenlabs" | "browser" | "none" }+ | { type: "install_complete"; success: boolean; summary: InstallSummary }+ | { type: "validation_result"; checks: ValidationCheck[] }+ | { type: "error"; message: string; step?: StepId };++// Client → Server messages+export type ClientMessage =+ | { type: "client_ready" }+ | { type: "user_input"; requestId: string; value: string }+ | { type: "user_choice"; requestId: string; value: string }+ | { type: "mode_select"; mode: "cli" | "web" }+ | { type: "start_install"; config?: Partial<InstallState["collected"]> }+ | { type: "go_to_step"; step: StepId }+ | { type: "voice_toggle"; enabled: boolean };++// ─── Validation ──────────────────────────────────────────────────++export interface ValidationCheck {+ name: string;+ passed: boolean;+ detail: string;+ critical: boolean;+}++export interface InstallSummary {+ paiVersion: string;+ principalName: string;+ aiName: string;+ timezone: string;+ voiceEnabled: boolean;+ voiceMode: string;+ catchphrase: string;+ installType: "fresh" | "upgrade";+ completedSteps: number;+ totalSteps: number;+}++// ─── Engine Events ───────────────────────────────────────────────++export type EngineEvent =+ | { event: "step_start"; step: StepId }+ | { event: "section_header"; sectionId: string; title: string; subtitle?: string; stepNumber?: number }+ | { event: "step_complete"; step: StepId }+ | { event: "step_error"; step: StepId; error: string }+ | { event: "step_skip"; step: StepId; reason: string }+ | { event: "progress"; step: StepId; percent: number; detail: string }+ | { event: "message"; content: string; speak?: boolean }+ | { event: "input_needed"; id: string; prompt: string; type: "text" | "password" | "key"; placeholder?: string }+ | { event: "choice_needed"; id: string; prompt: string; choices: { label: string; value: string; description?: string }[] }+ | { event: "complete"; summary: InstallSummary }+ | { event: "error"; message: string };++export type EngineEventHandler = (event: EngineEvent) => void | Promise<void>;++// ─── Voice ───────────────────────────────────────────────────────++// ─── Release Versions (single source of truth) ─────────────────+// Update these when cutting a new PAI release.+// The installer reads these constants — no other file should hardcode versions.++export const PAI_VERSION = "5.0.0";+// Fallback only — the live PAI/ALGORITHM/LATEST file is the single source+// of truth (v6.2.0+ doctrine). runConfiguration prefers LATEST and only+// uses this constant when the staged tree didn't ship a LATEST file.+export const ALGORITHM_VERSION = "6.2.0";+export const INSTALLER_VERSION = "5.0";++// ElevenLabs voice IDs for the install picker. Six built-in options across+// three gender presentations, two voices each, so a fresh user can pick+// without needing to know what an ElevenLabs voice ID is. Custom Voice ID+// and Skip Voice are surfaced alongside these in the picker UI.+//+// These IDs are public ElevenLabs voice identifiers — not API keys, not+// credentials. They identify which TTS voice to render with; the user's own+// ELEVENLABS_API_KEY is required separately to actually invoke synthesis.+export interface VoiceOption {+ /** Stable picker key, used in state.collected.voiceType. */+ id: string;+ /** Public ElevenLabs voice ID (no auth, just an identifier). */+ voiceId: string;+ /** Label shown in the picker. */+ label: string;+ /** Short description shown under the label. */+ description: string;+}++export const DEFAULT_VOICES: readonly VoiceOption[] = [+ { id: "female-1", voiceId: "AyCt0WmAXUcPJR11zeeP", label: "Female 1", description: "Voice ID AyCt0WmAXUcPJR11zeeP" },+ { id: "female-2", voiceId: "VD1if7jDVYtAKs4P0FIY", label: "Female 2", description: "Voice ID VD1if7jDVYtAKs4P0FIY" },+ { id: "male-1", voiceId: "gUU37agQvEpxeWrZUIMk", label: "Male 1", description: "Voice ID gUU37agQvEpxeWrZUIMk" },+ { id: "male-2", voiceId: "77aEIu0qStu8Jwv1EdhX", label: "Male 2", description: "Voice ID 77aEIu0qStu8Jwv1EdhX" },+ { id: "neutral-1", voiceId: "807MhexSYBuyUN7pI4wT", label: "Neutral 1", description: "Voice ID 807MhexSYBuyUN7pI4wT" },+ { id: "neutral-2", voiceId: "rk9BD4xwuG39syvDIBQy", label: "Neutral 2", description: "Voice ID rk9BD4xwuG39syvDIBQy" },+] as const;diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/validate.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/validate.tsnew file mode 100644index 00000000..ff6dc666--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/engine/validate.ts@@ -0,0 +1,297 @@+/**+ * PAI Installer v5.0 — Validation+ * Verifies installation completeness after all steps run.+ */++import { existsSync, readFileSync } from "fs";+import { join } from "path";+import { spawnSync } from "child_process";+import type { InstallState, ValidationCheck, InstallSummary, EngineEventHandler } from "./types";+import { PAI_VERSION } from "./types";+import { homedir } from "os";++/**+ * Check if Pulse is running. PAI 5.0 absorbed the standalone voice server+ * into Pulse on port 31337 — Pulse serves /notify for voice + the Life+ * Dashboard + observability. Probe /notify with an empty silent payload.+ * Any 2xx-4xx response means Pulse is up and the route is registered.+ */+async function checkPulseHealth(): Promise<boolean> {+ try {+ const res = await fetch("http://localhost:31337/notify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ message: "", voice_enabled: false }),+ signal: AbortSignal.timeout(2000),+ });+ return res.status >= 200 && res.status < 500;+ } catch {+ return false;+ }+}++/**+ * Run the SecurityPipeline.hook.ts as Claude Code would, with a benign Bash+ * payload. The hook MUST exit 0 (allow) and MUST NOT print "patterns file+ * missing — fail-closed". A failure here means PATTERNS.yaml is unreachable+ * to the hook at runtime even if the file appears to exist on disk — the+ * exact bug that left fresh installs unable to run any Bash command.+ *+ * Returns { passed, detail }. `passed=false` is CRITICAL: every Bash call+ * the user makes will be denied until this is fixed.+ */+function checkSecurityHookSmoke(paiDir: string): { passed: boolean; detail: string } {+ const hookPath = join(paiDir, "hooks", "SecurityPipeline.hook.ts");+ if (!existsSync(hookPath)) {+ return { passed: false, detail: "Hook not found at hooks/SecurityPipeline.hook.ts" };+ }+ const patternsPath = join(paiDir, "PAI", "USER", "SECURITY", "PATTERNS.yaml");+ if (!existsSync(patternsPath)) {+ return { passed: false, detail: `PATTERNS.yaml not found at ${patternsPath} — hook will fail-close on every Bash call` };+ }+ // Synthetic benign payload that should ALWAYS be allowed. Mirrors Claude Code's hook input shape.+ const payload = JSON.stringify({+ session_id: "smoke-test",+ hook_event_name: "PreToolUse",+ tool_name: "Bash",+ tool_input: { command: "echo pai-smoke-test" },+ });+ try {+ const res = spawnSync(process.execPath, [hookPath], {+ input: payload,+ encoding: "utf-8",+ timeout: 8000,+ // Match Claude Code: no inherited zshrc, minimal env. HOME and PATH only.+ env: { HOME: homedir(), PATH: process.env.PATH || "" },+ });+ const stderr = (res.stderr || "").toString();+ if (res.status !== 0) {+ return { passed: false, detail: `Hook exited ${res.status}: ${stderr.trim().slice(0, 160) || "no stderr"}` };+ }+ if (/patterns file missing|fail-closed/i.test(stderr)) {+ return { passed: false, detail: `Hook printed fail-closed message: ${stderr.trim().slice(0, 160)}` };+ }+ return { passed: true, detail: "echo allowed; PATTERNS.yaml loaded; no fail-closed message" };+ } catch (err: any) {+ return { passed: false, detail: `Hook execution threw: ${err?.message || String(err)}` };+ }+}++/**+ * Run all validation checks against the current state.+ */+export async function runValidation(state: InstallState, emit?: EngineEventHandler): Promise<ValidationCheck[]> {+ if (emit) {+ await emit({ event: "step_start", step: "validation" });+ await emit({+ event: "section_header",+ sectionId: "FINAL-VALIDATION",+ title: "FINAL VALIDATION",+ subtitle: "Verifying the install before handing control back to you",+ stepNumber: 9,+ });+ }++ const paiDir = state.detection?.paiDir || join(homedir(), ".claude");+ const configDir = state.detection?.configDir || join(homedir(), ".config", "PAI");+ const checks: ValidationCheck[] = [];++ // 1. settings.json exists and is valid JSON+ const settingsPath = join(paiDir, "settings.json");+ const settingsExists = existsSync(settingsPath);+ let settingsValid = false;+ let settings: any = null;++ if (settingsExists) {+ try {+ settings = JSON.parse(readFileSync(settingsPath, "utf-8"));+ settingsValid = true;+ } catch {+ settingsValid = false;+ }+ }++ checks.push({+ name: "settings.json",+ passed: settingsExists && settingsValid,+ detail: settingsValid+ ? "Valid configuration file"+ : settingsExists+ ? "File exists but invalid JSON"+ : "File not found",+ critical: true,+ });++ // 2. Required settings fields+ if (settings) {+ checks.push({+ name: "Principal name",+ passed: !!settings.principal?.name,+ detail: settings.principal?.name ? `Set to: ${settings.principal.name}` : "Not configured",+ critical: true,+ });++ checks.push({+ name: "AI identity",+ passed: !!settings.daidentity?.name,+ detail: settings.daidentity?.name ? `Set to: ${settings.daidentity.name}` : "Not configured",+ critical: true,+ });++ checks.push({+ name: "PAI version",+ passed: !!settings.pai?.version,+ detail: settings.pai?.version ? `v${settings.pai.version}` : "Not set",+ critical: false,+ });++ checks.push({+ name: "Timezone",+ passed: !!settings.principal?.timezone,+ detail: settings.principal?.timezone || "Not configured",+ critical: false,+ });+ }++ // 3. Directory structure+ const requiredDirs = [+ { path: "skills", name: "Skills directory" },+ { path: "MEMORY", name: "Memory directory" },+ { path: "MEMORY/STATE", name: "State directory" },+ { path: "MEMORY/WORK", name: "Work directory" },+ { path: "hooks", name: "Hooks directory" },+ { path: "Plans", name: "Plans directory" },+ ];++ for (const dir of requiredDirs) {+ const fullPath = join(paiDir, dir.path);+ checks.push({+ name: dir.name,+ passed: existsSync(fullPath),+ detail: existsSync(fullPath) ? "Present" : "Missing",+ critical: dir.path === "skills" || dir.path === "MEMORY",+ });+ }++ // 4. PAI skill present+ const skillPath = join(paiDir, "skills", "PAI", "SKILL.md");+ checks.push({+ name: "PAI core skill",+ passed: existsSync(skillPath),+ detail: existsSync(skillPath) ? "Present" : "Not found — clone PAI repo to enable",+ critical: false,+ });++ // 5. ElevenLabs key stored — check all three possible locations+ const envPaths = [+ join(configDir, ".env"),+ join(paiDir, ".env"),+ join(homedir(), ".env"),+ ];+ let elevenLabsKeyStored = false;+ let elevenLabsKeyLocation = "";+ for (const ep of envPaths) {+ if (existsSync(ep)) {+ try {+ const envContent = readFileSync(ep, "utf-8");+ if (envContent.includes("ELEVENLABS_API_KEY=") &&+ !envContent.includes("ELEVENLABS_API_KEY=\n")) {+ elevenLabsKeyStored = true;+ elevenLabsKeyLocation = ep;+ break;+ }+ } catch {}+ }+ }++ checks.push({+ name: "ElevenLabs API key",+ passed: elevenLabsKeyStored,+ detail: elevenLabsKeyStored ? `Stored in ${elevenLabsKeyLocation}` : state.collected.elevenLabsKey ? "Collected but not saved" : "Not configured",+ critical: false,+ });++ // 6. DA voice configured in settings (nested under voices.main.voiceId)+ const voiceId = settings?.daidentity?.voices?.main?.voiceId;+ const voiceIdConfigured = !!voiceId;++ checks.push({+ name: "DA voice ID",+ passed: voiceIdConfigured,+ detail: voiceIdConfigured ? `Voice ID: ${voiceId.substring(0, 8)}...` : "Not configured",+ critical: false,+ });++ // 7. Pulse running — embeds voice + dashboard + observability (PAI 5.0)+ const pulseHealthy = await checkPulseHealth();++ checks.push({+ name: "Pulse (voice + dashboard)",+ passed: pulseHealthy,+ detail: pulseHealthy+ ? "Running on localhost:31337"+ : "Not reachable — install via: bash ~/.claude/PAI/PULSE/manage.sh install",+ critical: false,+ });++ // 7b. Pulse launchd plist present (auto-start on login)+ const pulsePlist = join(homedir(), "Library", "LaunchAgents", "com.pai.pulse.plist");+ const pulsePlistInstalled = existsSync(pulsePlist);+ checks.push({+ name: "Pulse launchd agent",+ passed: pulsePlistInstalled,+ detail: pulsePlistInstalled+ ? "Installed at ~/Library/LaunchAgents/com.pai.pulse.plist"+ : "Not installed — Pulse will not auto-start on login",+ critical: false,+ });++ // 8. Zsh alias configured+ const zshrcPath = join(homedir(), ".zshrc");+ let aliasConfigured = false;+ if (existsSync(zshrcPath)) {+ try {+ const zshContent = readFileSync(zshrcPath, "utf-8");+ aliasConfigured = zshContent.includes("# PAI alias") && zshContent.includes("alias pai=");+ } catch {}+ }++ checks.push({+ name: "Shell alias (pai)",+ passed: aliasConfigured,+ detail: aliasConfigured ? "Configured in .zshrc" : "Not found — run: source ~/.zshrc",+ critical: true,+ });++ // 9. SecurityPipeline smoke test — runs the actual hook with a benign Bash+ // payload. Catches the v5.0 fail-closed regression where PATTERNS.yaml was+ // missing from the public template, leaving every fresh install unable to+ // execute Bash commands. CRITICAL — if this fails, the install is broken.+ const securitySmoke = checkSecurityHookSmoke(paiDir);+ checks.push({+ name: "SecurityPipeline hook (smoke test)",+ passed: securitySmoke.passed,+ detail: securitySmoke.detail,+ critical: true,+ });++ return checks;+}++/**+ * Generate install summary from state.+ */+export function generateSummary(state: InstallState): InstallSummary {+ return {+ paiVersion: PAI_VERSION,+ principalName: state.collected.principalName || "User",+ aiName: state.collected.aiName || "PAI",+ timezone: state.collected.timezone || "UTC",+ voiceEnabled: state.completedSteps.includes("voice"),+ voiceMode: state.collected.elevenLabsKey ? "elevenlabs" : state.completedSteps.includes("voice") ? "macos-say" : "none",+ catchphrase: state.collected.catchphrase || "",+ installType: state.installType || "fresh",+ completedSteps: state.completedSteps.length,+ totalSteps: 9,+ };+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/generate-welcome.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/generate-welcome.tsnew file mode 100644index 00000000..05463fc1--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/generate-welcome.ts@@ -0,0 +1,104 @@+#!/usr/bin/env bun+/**+ * PAI Installer v5.0 — Welcome MP3 Generator+ * Uses ElevenLabs API to generate the welcome audio with a voice clone.+ *+ * Usage: bun generate-welcome.ts+ *+ * Requires: ELEVENLABS_API_KEY environment variable+ * Uses voice clone ID from settings.json principal.voiceClone+ */++import { writeFileSync, readFileSync, existsSync } from "fs";+import { join, dirname } from "path";+import { homedir } from "os";++const OUTPUT_PATH = join(import.meta.dir, "public", "assets", "welcome.mp3");++// Voice ID — check env var, then settings.json voices, then default+function getVoiceId(): string {+ // Environment variable takes priority+ if (process.env.ELEVENLABS_VOICE_ID) return process.env.ELEVENLABS_VOICE_ID;++ const settingsPath = join(homedir(), ".claude", "settings.json");+ if (existsSync(settingsPath)) {+ try {+ const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));+ // Use principal's voice clone (the installer speaks in the user's voice)+ const clone = settings.principal?.voiceClone;+ if (typeof clone === "string") return clone;+ if (typeof clone?.voiceId === "string") return clone.voiceId;+ // Fallback to DA main voice+ const mainVoice = settings.daidentity?.voices?.main?.voiceId;+ if (typeof mainVoice === "string") return mainVoice;+ } catch {}+ }+ // Fallback to a default ElevenLabs voice+ return "pNInz6obpgDQGcFmaJgB"; // Adam+}++async function generateWelcome() {+ const apiKey = process.env.ELEVENLABS_API_KEY;+ if (!apiKey) {+ // Try to read from config+ const envPath = join(homedir(), ".config", "PAI", ".env");+ if (existsSync(envPath)) {+ const envContent = readFileSync(envPath, "utf-8");+ const match = envContent.match(/ELEVENLABS_API_KEY=(.+)/);+ if (match) {+ process.env.ELEVENLABS_API_KEY = match[1].trim();+ }+ }++ if (!process.env.ELEVENLABS_API_KEY) {+ console.error("Error: ELEVENLABS_API_KEY not found in environment or ~/.claude/PAI/.env");+ console.error("Set it with: export ELEVENLABS_API_KEY=your-key-here");+ process.exit(1);+ }+ }++ const voiceId = getVoiceId();+ const text = "Welcome to Personal AI Infrastructure. <break time=\"1.0s\" /> Magnifying human capabilities.";++ console.log(`Generating welcome audio...`);+ console.log(` Voice ID: ${voiceId}`);+ console.log(` Text: "${text}"`);+ console.log(` Output: ${OUTPUT_PATH}`);++ const response = await fetch(+ `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`,+ {+ method: "POST",+ headers: {+ "xi-api-key": process.env.ELEVENLABS_API_KEY!,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ text,+ model_id: "eleven_turbo_v2_5",+ voice_settings: {+ stability: 0.85,+ similarity_boost: 0.9,+ style: 0.1,+ use_speaker_boost: true,+ },+ }),+ }+ );++ if (!response.ok) {+ const error = await response.text();+ console.error(`ElevenLabs API error (${response.status}): ${error}`);+ process.exit(1);+ }++ const buffer = await response.arrayBuffer();+ writeFileSync(OUTPUT_PATH, Buffer.from(buffer));++ console.log(`\n✓ Welcome audio generated: ${OUTPUT_PATH} (${Math.round(buffer.byteLength / 1024)}KB)`);+}++generateWelcome().catch((err) => {+ console.error("Error:", err.message);+ process.exit(1);+});diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/main.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/main.tsnew file mode 100644index 00000000..3a46f0a6--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/main.ts@@ -0,0 +1,78 @@+#!/usr/bin/env bun+/**+ * PAI Installer v5.0 — Main Entry Point+ * Routes to CLI, Web server (for Electron), or GUI (Electron app).+ *+ * Modes:+ * --mode cli → Interactive terminal wizard+ * --mode web → Start HTTP/WebSocket server (used internally by Electron)+ * --mode gui → Launch Electron app (which spawns web mode internally)+ */++import { spawn, spawnSync, execSync } from "child_process";+import { join } from "path";+import { existsSync } from "fs";++const args = process.argv.slice(2);+const modeIdx = args.indexOf("--mode");+const mode = modeIdx >= 0 ? args[modeIdx + 1] : "gui";++const ROOT = import.meta.dir;++async function main() {+ if (mode === "cli") {+ // Run CLI wizard+ const { runCLI } = await import("./cli/index");+ await runCLI();+ } else if (mode === "web") {+ // Start the HTTP + WebSocket server (Electron loads this)+ await import("./web/server");+ } else {+ // Launch Electron GUI app+ const electronDir = join(ROOT, "electron");+ const electronPkg = join(electronDir, "node_modules", ".package-lock.json");++ // Install electron dependencies if needed.+ // bun is the bootstrap runtime install.sh guarantees; npm is NOT on a+ // bun-only host. Using bun install here keeps the GUI path reachable+ // for the typical PAI user.+ if (!existsSync(electronPkg)) {+ console.log("Installing GUI dependencies (first run only)...\n");+ const install = spawnSync("bun", ["install"], {+ cwd: electronDir,+ stdio: "inherit",+ });+ if (install.status !== 0) {+ console.error("Failed to install GUI dependencies. Falling back to CLI...\n");+ const { runCLI } = await import("./cli/index");+ await runCLI();+ return;+ }+ }++ // Clear macOS quarantine flags (prevents "app is damaged" error on copied installs)+ if (process.platform === "darwin") {+ try {+ execSync(`xattr -cr "${electronDir}"`, { stdio: "pipe", timeout: 30000 });+ console.log("Cleared macOS quarantine flags.\n");+ } catch {+ // Non-fatal+ }+ }++ console.log("Starting PAI Installer GUI...\n");+ const child = spawn("bun", ["run", "start"], {+ cwd: electronDir,+ stdio: "inherit",+ });++ child.on("exit", (code) => {+ process.exit(code || 0);+ });+ }+}++main().catch((err) => {+ console.error("Fatal error:", err.message);+ process.exit(1);+});diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/app.js b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/app.jsnew file mode 100644index 00000000..e0359050--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/app.js@@ -0,0 +1,503 @@+/**+ * PAI Installer v5.0 — Frontend Application+ * Vanilla JavaScript — no framework dependencies.+ * Handles WebSocket communication, UI rendering, and state management.+ */++// ─── State ───────────────────────────────────────────────────────++let ws = null;+let connected = false;+let voiceEnabled = true;+let currentAudio = null;+let steps = [+ { id: 'system-detect', name: 'System Detection', number: 1, status: 'pending' },+ { id: 'prerequisites', name: 'Prerequisites', number: 2, status: 'pending' },+ { id: 'api-keys', name: 'API Keys', number: 3, status: 'pending' },+ { id: 'identity', name: 'Identity', number: 4, status: 'pending' },+ { id: 'repository', name: 'PAI Repository', number: 5, status: 'pending' },+ { id: 'configuration', name: 'Configuration', number: 6, status: 'pending' },+ { id: 'voice', name: 'DA Voice', number: 7, status: 'pending' },+ { id: 'telegram', name: 'Telegram', number: 8, status: 'pending' },+ { id: 'validation', name: 'Validation', number: 9, status: 'pending' },+];++// ─── WebSocket Connection ────────────────────────────────────────++function connect() {+ const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';+ ws = new WebSocket(`${protocol}//${location.host}/ws`);++ ws.onopen = () => {+ connected = true;+ ws.send(JSON.stringify({ type: 'client_ready' }));+ };++ ws.onmessage = (event) => {+ const msg = JSON.parse(event.data);+ handleServerMessage(msg);+ };++ ws.onclose = () => {+ connected = false;+ addMessage('system', 'Connection lost. Reconnecting...', false);+ setTimeout(connect, 2000); // Auto-reconnect+ };++ ws.onerror = () => {+ connected = false;+ };+}++// ─── Message Handler ─────────────────────────────────────────────++function handleServerMessage(msg) {+ const isReplayed = msg.replayed === true;++ // Any server-driven update means our pending placeholder has served its+ // purpose — the user is now seeing real activity. Clear it so we don't+ // double-stack a generic "Working…" with a real progress row.+ clearPendingIndicator();++ switch (msg.type) {+ case 'connected':+ break;++ case 'step_update':+ updateStep(msg.step, msg.status);+ updateProgress();+ break;++ case 'detection_result':+ renderDetection(msg.data);+ break;++ case 'message':+ addMessage(msg.role || 'assistant', msg.content, isReplayed);+ if (msg.speak && !isReplayed && voiceEnabled) {+ // TTS would go here if we had the ElevenLabs key+ }+ break;++ case 'section_header':+ renderSectionHeader(msg, isReplayed);+ break;++ case 'input_request':+ renderInputForm(msg.id, msg.prompt, msg.inputType, msg.placeholder);+ break;++ case 'choice_request':+ renderChoiceForm(msg.id, msg.prompt, msg.choices);+ break;++ case 'progress':+ renderProgress(msg.step, msg.percent, msg.detail);+ break;++ case 'validation_result':+ renderValidation(msg.checks);+ break;++ case 'install_complete':+ renderSummary(msg.summary);+ break;++ case 'error':+ addMessage('error', `Error: ${msg.message}`, isReplayed);+ break;+ }++ scrollToBottom();+}++// ─── Step Management ─────────────────────────────────────────────++function updateStep(stepId, status) {+ const step = steps.find(s => s.id === stepId);+ if (step) step.status = status;+ renderSteps();+}++function updateProgress() {+ const done = steps.filter(s => s.status === 'completed' || s.status === 'skipped').length;+ const pct = Math.round((done / steps.length) * 100);++ const fill = document.getElementById('progress-fill');+ const text = document.getElementById('progress-text');+ const sidebarFill = document.getElementById('sidebar-progress-fill');+ const sidebarText = document.getElementById('sidebar-progress-text');++ if (fill) fill.style.width = pct + '%';+ if (text) text.textContent = `Step ${done}/${steps.length}`;+ if (sidebarFill) sidebarFill.style.width = pct + '%';+ if (sidebarText) sidebarText.textContent = `Progress: ${pct}%`;+}++function renderSteps() {+ const list = document.getElementById('step-list');+ if (!list) return;++ list.innerHTML = steps.map(s => {+ let icon = '○';+ let cls = s.status;+ if (s.status === 'completed') icon = '✓';+ else if (s.status === 'active') icon = '→';+ else if (s.status === 'skipped') icon = '–';+ else if (s.status === 'failed') icon = '✗';++ return `<li class="step-item ${cls}">+ <span class="step-icon ${cls}">${icon}</span>+ <span class="step-label">${s.number}. ${s.name}</span>+ </li>`;+ }).join('');+}++// ─── Chat Rendering ──────────────────────────────────────────────++function addMessage(role, content, replayed) {+ if (!content || !content.trim()) return;+ const chat = document.getElementById('chat-messages');+ if (!chat) return;++ const div = document.createElement('div');+ div.className = `msg ${role}`;+ div.textContent = content;+ if (replayed) div.style.animation = 'none';+ chat.appendChild(div);+}++function renderSectionHeader(msg, replayed) {+ const chat = document.getElementById('chat-messages');+ if (!chat) return;++ const wrapper = document.createElement('div');+ wrapper.className = 'section-header';+ if (replayed) wrapper.style.animation = 'none';++ const subtitleHtml = msg.subtitle+ ? `<div class="section-header-subtitle">${msg.subtitle}</div>`+ : '';+ const stepHtml = msg.stepNumber+ ? `<div class="section-header-step">Step ${msg.stepNumber} / 9</div>`+ : '';++ wrapper.innerHTML = `+ <div class="section-header-rule"></div>+ <div class="section-header-content">+ <div class="section-header-title">${msg.title}</div>+ ${subtitleHtml}+ ${stepHtml}+ </div>+ <div class="section-header-rule"></div>+ `;+ chat.appendChild(wrapper);+}++function renderDetection(data) {+ const chat = document.getElementById('chat-messages');+ if (!chat) return;++ const items = [+ { icon: 'check', label: 'OS', value: data.os?.name + ' (' + data.os?.arch + ')' },+ { icon: 'check', label: 'Shell', value: data.shell?.name },+ { icon: data.tools?.bun?.installed ? 'check' : 'cross', label: 'Bun', value: data.tools?.bun?.installed ? 'v' + data.tools.bun.version : 'Not found' },+ { icon: data.tools?.git?.installed ? 'check' : 'cross', label: 'Git', value: data.tools?.git?.installed ? 'v' + data.tools.git.version : 'Not found' },+ { icon: data.tools?.claude?.installed ? 'check' : 'info', label: 'Claude Code', value: data.tools?.claude?.installed ? 'v' + data.tools.claude.version : 'Will install' },+ { icon: 'info', label: 'Timezone', value: data.timezone },+ { icon: data.existing?.paiInstalled ? 'info' : 'check', label: 'Existing PAI', value: data.existing?.paiInstalled ? 'v' + (data.existing.paiVersion || '?') : 'Fresh install' },+ { icon: data.existing?.hasApiKeys ? 'check' : 'info', label: 'ElevenLabs Key', value: data.existing?.elevenLabsKeyFound ? 'Found' : 'Not found' },+ ];++ const grid = document.createElement('div');+ grid.className = 'detection-grid';+ grid.innerHTML = items.map(i =>+ `<div class="detection-item">+ <span class="${i.icon}">${i.icon === 'check' ? '✓' : i.icon === 'cross' ? '✗' : 'ℹ'}</span>+ <span>${i.label}: ${i.value}</span>+ </div>`+ ).join('');+ chat.appendChild(grid);+}++function renderInputForm(requestId, prompt, inputType, placeholder) {+ const chat = document.getElementById('chat-messages');+ if (!chat) return;++ // Show prompt as message+ addMessage('assistant', prompt);++ // The backend passes a single value used as BOTH the pre-filled default+ // (input.value, so Enter immediately accepts it) AND the placeholder hint+ // (visible if the user clears the field). For password/key fields we never+ // pre-fill — secrets stay out of the DOM unless the user types them.+ const isSecret = inputType === 'key' || inputType === 'password';+ const safeDefault = isSecret ? '' : (placeholder || '');+ const safeHint = placeholder || '';++ const form = document.createElement('div');+ form.className = 'inline-form';+ form.innerHTML = `+ <label>${inputType === 'key' ? 'API Key' : 'Input'}</label>+ <div class="form-row">+ <input class="inline-input" type="${isSecret ? 'password' : 'text'}"+ value="${escapeAttr(safeDefault)}"+ placeholder="${escapeAttr(safeHint)}"+ id="input-${requestId}" autocomplete="off">+ <button class="inline-btn" onclick="submitInput('${requestId}')">Submit</button>+ </div>+ `;+ chat.appendChild(form);++ // Focus input AND select-all so the pre-filled default highlights —+ // user can press Enter to accept, type to overwrite, or arrow to edit.+ setTimeout(() => {+ const input = document.getElementById('input-' + requestId);+ if (input) {+ input.focus();+ if (input.value) input.select();+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') submitInput(requestId);+ });+ }+ }, 100);++ scrollToBottom();+}++// Minimal HTML attribute escape — used for value= and placeholder= attrs.+function escapeAttr(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/"/g, '"')+ .replace(/'/g, ''')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}++function submitInput(requestId) {+ const input = document.getElementById('input-' + requestId);+ if (!input) return;++ const value = input.value.trim();+ if (!value && input.getAttribute('type') === 'password') {+ // Allow empty for optional fields+ }++ // Mask key display+ const display = value.startsWith('sk-') || value.startsWith('xi-')+ ? value.substring(0, 8) + '...'+ : value;+ addMessage('user', display || '(empty)');++ // Disable form+ input.disabled = true;+ input.closest('.inline-form').querySelector('.inline-btn').disabled = true;++ ws.send(JSON.stringify({ type: 'user_input', requestId, value }));+ showPendingIndicator('Working…');+ scrollToBottom();+}++function renderChoiceForm(requestId, prompt, choices) {+ const chat = document.getElementById('chat-messages');+ if (!chat) return;++ addMessage('assistant', prompt);++ // Voice preview audio map — show previews for both initial and retry voice selection+ const voicePreviews = { female: '/assets/voice-female.mp3', male: '/assets/voice-male.mp3' };+ const isVoiceTypeRequest = requestId === 'voice-type' || requestId === 'voice-type-retry';++ const group = document.createElement('div');+ group.className = 'choice-group';++ choices.forEach(c => {+ const btn = document.createElement('button');+ btn.className = 'choice-btn';+ btn.dataset.requestId = requestId;+ btn.dataset.value = c.value;++ const labelSpan = document.createElement('span');+ labelSpan.className = 'choice-label';+ labelSpan.textContent = c.label;+ btn.appendChild(labelSpan);++ if (c.description) {+ const descSpan = document.createElement('span');+ descSpan.className = 'choice-desc';+ descSpan.textContent = c.description;+ btn.appendChild(descSpan);+ }++ if (voicePreviews[c.value] && isVoiceTypeRequest) {+ const preview = document.createElement('span');+ preview.className = 'preview-btn';+ preview.innerHTML = '▶ Preview';+ preview.addEventListener('click', (e) => {+ e.stopPropagation();+ playPreview(voicePreviews[c.value], preview);+ });+ btn.appendChild(preview);+ }++ btn.addEventListener('click', () => submitChoice(requestId, c.value, btn));+ group.appendChild(btn);+ });++ chat.appendChild(group);+ scrollToBottom();+}++function playPreview(src, btn) {+ if (currentAudio) { currentAudio.pause(); currentAudio = null; }+ currentAudio = new Audio(src);+ currentAudio.volume = 0.8;+ currentAudio.play().catch(() => {});+ btn.textContent = '⏹ Playing';+ currentAudio.onended = () => { btn.textContent = '▶ Preview'; currentAudio = null; };+}++function submitChoice(requestId, value, btn) {+ // Highlight selected, disable all+ const group = btn.closest('.choice-group');+ group.querySelectorAll('.choice-btn').forEach(b => {+ b.disabled = true;+ b.style.opacity = b === btn ? '1' : '0.4';+ });+ btn.style.borderColor = 'var(--accent-primary)';++ // Extract only the label text, not description or preview button text+ const labelEl = btn.querySelector('.choice-label');+ const displayText = labelEl ? labelEl.textContent.trim() : btn.textContent.trim().split('\n')[0];+ addMessage('user', displayText);+ ws.send(JSON.stringify({ type: 'user_choice', requestId, value }));+ showPendingIndicator('Working…');+ scrollToBottom();+}++// ─── Pending-action placeholder ──────────────────────────────────+// Long-running steps (e.g. installPulse, installPulseMenuBar) can take+// several seconds before the engine emits its first "progress" event. The+// gap between a click and the first server update used to read as a dead+// UI ("did anything happen?"). This placeholder appears the instant the+// user submits a choice/input and is cleared as soon as the next server+// message arrives.++function showPendingIndicator(text) {+ clearPendingIndicator();+ const chat = document.getElementById('chat-messages');+ if (!chat) return;+ const div = document.createElement('div');+ div.id = 'pending-action';+ div.className = 'progress-msg';+ div.innerHTML = `<div class="spinner"></div><span class="prog-detail">${text}</span>`;+ chat.appendChild(div);+}++function clearPendingIndicator() {+ const existing = document.getElementById('pending-action');+ if (existing) existing.remove();+}++function renderProgress(step, percent, detail) {+ // Update or create progress indicator+ let existing = document.getElementById('progress-' + step);+ const chat = document.getElementById('chat-messages');++ if (existing) {+ existing.querySelector('.mini-fill').style.width = percent + '%';+ existing.querySelector('.prog-detail').textContent = detail;+ } else {+ const div = document.createElement('div');+ div.className = 'progress-msg';+ div.id = 'progress-' + step;+ div.innerHTML = `+ <div class="spinner"></div>+ <div class="mini-bar"><div class="mini-fill" style="width:${percent}%"></div></div>+ <span class="prog-detail">${detail}</span>+ `;+ chat.appendChild(div);+ }+ scrollToBottom();+}++function renderValidation(checks) {+ const chat = document.getElementById('chat-messages');+ if (!chat) return;++ addMessage('system', 'Running validation checks...');++ const list = document.createElement('div');+ list.className = 'validation-list';+ list.innerHTML = checks.map(c =>+ `<div class="validation-item">+ <span class="v-icon">${c.passed ? '✓' : c.critical ? '✗' : '⚠'}</span>+ <span class="v-name">${c.name}</span>+ <span class="v-detail">${c.detail}</span>+ </div>`+ ).join('');+ chat.appendChild(list);+ scrollToBottom();+}++function renderSummary(summary) {+ const chat = document.getElementById('chat-messages');+ if (!chat) return;++ const installTypeLabel = summary.installType === 'upgrade'+ ? 'Fresh install + backup migration'+ : 'Fresh install';++ const card = document.createElement('div');+ card.className = 'summary-card';+ card.innerHTML = `+ <h3>Installation Complete</h3>+ <div class="summary-row"><span class="s-label">PAI Version</span><span class="s-value">v${summary.paiVersion}</span></div>+ <div class="summary-row"><span class="s-label">Principal</span><span class="s-value">${summary.principalName}</span></div>+ <div class="summary-row"><span class="s-label">AI Name</span><span class="s-value">${summary.aiName}</span></div>+ <div class="summary-row"><span class="s-label">Timezone</span><span class="s-value">${summary.timezone}</span></div>+ <div class="summary-row"><span class="s-label">Voice</span><span class="s-value">${summary.voiceEnabled ? summary.voiceMode : 'Disabled'}</span></div>+ <div class="summary-row"><span class="s-label">Install Type</span><span class="s-value">${installTypeLabel}</span></div>+ <div class="summary-action">+ <p>To activate PAI, open a terminal and run:</p>+ <code>source ~/.zshrc && pai</code>+ <p class="summary-hint">This reloads your shell config and launches PAI for the first time.</p>+ </div>+ `;+ chat.appendChild(card);+ scrollToBottom();+}++// ─── Welcome Screen ──────────────────────────────────────────────++function startInstall() {+ const overlay = document.getElementById('welcome-overlay');+ if (overlay) overlay.classList.add('hidden');++ // Start installation+ ws.send(JSON.stringify({ type: 'start_install' }));+}++// ─── Utilities ───────────────────────────────────────────────────++function scrollToBottom() {+ const chat = document.getElementById('chat-messages');+ if (chat) {+ // Double-RAF ensures DOM has fully rendered before scrolling+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ chat.scrollTop = chat.scrollHeight;+ });+ });+ }+}++// ─── Initialize ──────────────────────────────────────────────────++document.addEventListener('DOMContentLoaded', () => {+ renderSteps();+ connect();++ // Welcome audio is played via <audio autoplay> in index.html+});diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/advocate_34_narr_reg.woff2 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/advocate_34_narr_reg.woff2new file mode 100755index 00000000..8478f661Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/advocate_34_narr_reg.woff2 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/advocate_54_wide_reg.woff2 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/advocate_54_wide_reg.woff2new file mode 100755index 00000000..bf4d8792Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/advocate_54_wide_reg.woff2 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_3_bold.woff2 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_3_bold.woff2new file mode 100755index 00000000..c804acb5Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_3_bold.woff2 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_3_regular.woff2 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_3_regular.woff2new file mode 100755index 00000000..ab5cfbb1Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_3_regular.woff2 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_4_regular.woff2 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_4_regular.woff2new file mode 100755index 00000000..efdb1d5bBinary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/concourse_4_regular.woff2 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/triplicate_t3_code_bold.ttf b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/triplicate_t3_code_bold.ttfnew file mode 100755index 00000000..ff7fd62eBinary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/triplicate_t3_code_bold.ttf differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/triplicate_t3_code_regular.ttf b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/triplicate_t3_code_regular.ttfnew file mode 100755index 00000000..4ce95ea4Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/triplicate_t3_code_regular.ttf differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/valkyrie_a_bold.woff2 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/valkyrie_a_bold.woff2new file mode 100755index 00000000..35d8ea2dBinary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/valkyrie_a_bold.woff2 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/valkyrie_a_regular.woff2 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/valkyrie_a_regular.woff2new file mode 100755index 00000000..4387da7eBinary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/fonts/valkyrie_a_regular.woff2 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/voice-female.mp3 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/voice-female.mp3new file mode 100644index 00000000..d326bf91Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/voice-female.mp3 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/voice-male.mp3 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/voice-male.mp3new file mode 100644index 00000000..ba6785a8Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/voice-male.mp3 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/welcome.mp3 b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/welcome.mp3new file mode 100644index 00000000..d4ad88ffBinary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/welcome.mp3 differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/welcome.wav b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/welcome.wavnew file mode 100644index 00000000..2591f9c8Binary files /dev/null and b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/assets/welcome.wav differdiff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/index.html b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/index.htmlnew file mode 100644index 00000000..f26856d5--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/index.html@@ -0,0 +1,62 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=1280, initial-scale=1">+ <title>PAI Installer v5.0</title>+ <link rel="stylesheet" href="/styles.css">+ <link rel="icon" href="/assets/pai-icon.png" type="image/png">+</head>+<body>++ <!-- Welcome Overlay -->+ <div id="welcome-overlay" class="welcome-overlay">+ <img src="/assets/pai-logo.png" alt="PAI" class="welcome-logo">+ <div class="welcome-title">PAI Installer</div>+ <div class="welcome-subtitle">Personal AI Infrastructure v5.0</div>+ <button class="welcome-start" onclick="startInstall()">Begin Installation</button>+ </div>++ <!-- App Shell -->+ <div id="app">++ <!-- Header -->+ <header class="header">+ <div class="header-brand">+ <img src="/assets/pai-icon.png" alt="PAI" class="header-logo">+ <span class="header-title">PAI Installer</span>+ <span class="header-version">v5.0</span>+ </div>+ <div class="header-progress">+ <span id="progress-text">Step 0/8</span>+ <div class="progress-bar-container">+ <div class="progress-bar-fill" id="progress-fill" style="width: 0%"></div>+ </div>+ </div>+ </header>++ <!-- Sidebar -->+ <nav class="sidebar">+ <div class="sidebar-label">Install Steps</div>+ <ul class="step-list" id="step-list"></ul>+ <div class="sidebar-footer">+ <div class="sidebar-progress-text" id="sidebar-progress-text">Progress: 0%</div>+ <div class="sidebar-progress-bar">+ <div class="sidebar-progress-fill" id="sidebar-progress-fill" style="width: 0%"></div>+ </div>+ </div>+ </nav>++ <!-- Main Content -->+ <main class="main">+ <!-- Chat Messages -->+ <div class="chat-container" id="chat-messages"></div>++ </main>++ </div>++ <audio id="welcome-audio" src="/assets/welcome.wav" autoplay preload="auto"></audio>+ <script src="/app.js"></script>+</body>+</html>diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/public/styles.css b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/styles.cssnew file mode 100644index 00000000..97bee6e6--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/public/styles.css@@ -0,0 +1,912 @@+/* ═══════════════════════════════════════════════════════════+ PAI Installer v5.0 — Thick Client Styles+ Dark theme, glassmorphic, PAI brand colors+ ═══════════════════════════════════════════════════════════ */++/* ─── Fonts ────────────────────────────────────────────── */+@font-face { font-family: 'Concourse'; src: url('/assets/fonts/concourse_3_regular.woff2') format('woff2'); font-weight: 400; }+@font-face { font-family: 'Concourse'; src: url('/assets/fonts/concourse_3_bold.woff2') format('woff2'); font-weight: 700; }+@font-face { font-family: 'Advocate'; src: url('/assets/fonts/advocate_54_wide_reg.woff2') format('woff2'); font-weight: 400; }+@font-face { font-family: 'Triplicate'; src: url('/assets/fonts/triplicate_t3_code_regular.ttf') format('truetype'); font-weight: 400; }+@font-face { font-family: 'Triplicate'; src: url('/assets/fonts/triplicate_t3_code_bold.ttf') format('truetype'); font-weight: 700; }++/* ─── CSS Variables ────────────────────────────────────── */+:root {+ --bg-deep: #0f0f14;+ --bg-surface: #1a1b26;+ --bg-elevated: #1e2030;+ --bg-input: #12131c;+ --bg-hover: #252738;++ --accent-primary: #3B82F6;+ --accent-secondary: #93C5FD;+ --accent-dim: rgba(59, 130, 246, 0.15);++ --text-primary: #e2e8f0;+ --text-secondary: #94a3b8;+ --text-dim: #64748b;++ --success: #22c55e;+ --warning: #eab308;+ --error: #ef4444;++ --border: rgba(59, 130, 246, 0.12);+ --border-strong: rgba(59, 130, 246, 0.25);+ --border-interactive: rgba(59, 130, 246, 0.45);++ --glow-blue: rgba(59, 130, 246, 0.12);+ --glow-blue-strong: rgba(59, 130, 246, 0.25);++ --radius: 8px;+ --radius-lg: 12px;++ --font-body: 'Concourse', system-ui, -apple-system, sans-serif;+ --font-display: 'Advocate', 'Concourse', system-ui, sans-serif;+ --font-mono: 'Triplicate', 'SF Mono', Menlo, monospace;++ --sidebar-width: 260px;+ --header-height: 64px;+}++/* ─── Reset ────────────────────────────────────────────── */+*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }++html, body {+ height: 100%;+ overflow: hidden;+ background: var(--bg-deep);+ color: var(--text-primary);+ font-family: var(--font-body);+ font-size: 15px;+ line-height: 1.5;+ -webkit-font-smoothing: antialiased;+}++/* ─── App Shell ────────────────────────────────────────── */+#app {+ display: grid;+ grid-template-rows: var(--header-height) 1fr;+ grid-template-columns: var(--sidebar-width) 1fr;+ height: 100vh;+}++/* ─── Header ───────────────────────────────────────────── */+.header {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 0 24px;+ background: var(--bg-surface);+ border-bottom: 1px solid var(--border);+ position: relative;+ overflow: hidden;+}++.header::after {+ content: '';+ position: absolute;+ bottom: 0;+ left: 0;+ right: 0;+ height: 2px;+ background: linear-gradient(90deg, transparent, var(--accent-primary), var(--accent-secondary), transparent);+ animation: shimmer 4s ease-in-out infinite;+}++@keyframes shimmer {+ 0%, 100% { opacity: 0.3; }+ 50% { opacity: 1; }+}++.header-brand {+ display: flex;+ align-items: center;+ gap: 14px;+}++.header-logo {+ width: 32px;+ height: 32px;+ object-fit: contain;+}++.header-title {+ font-family: var(--font-display);+ font-size: 18px;+ letter-spacing: 3px;+ text-transform: uppercase;+ color: var(--accent-secondary);+}++.header-version {+ font-family: var(--font-mono);+ font-size: 11px;+ color: var(--text-dim);+ margin-left: 8px;+}++.header-progress {+ display: flex;+ align-items: center;+ gap: 12px;+ font-family: var(--font-mono);+ font-size: 12px;+ color: var(--text-secondary);+}++.progress-bar-container {+ width: 160px;+ height: 6px;+ background: var(--bg-input);+ border-radius: 3px;+ overflow: hidden;+}++.progress-bar-fill {+ height: 100%;+ background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));+ border-radius: 3px;+ transition: width 0.5s ease;+}++/* ─── Sidebar ──────────────────────────────────────────── */+.sidebar {+ background: var(--bg-surface);+ border-right: 1px solid var(--border);+ padding: 20px 0;+ display: flex;+ flex-direction: column;+ overflow-y: auto;+}++.sidebar-label {+ font-family: var(--font-mono);+ font-size: 10px;+ letter-spacing: 2px;+ text-transform: uppercase;+ color: var(--text-dim);+ padding: 0 20px;+ margin-bottom: 12px;+}++.step-list {+ list-style: none;+ flex: 1;+}++.step-item {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 10px 20px;+ cursor: default;+ transition: background 0.2s;+ border-left: 3px solid transparent;+}++.step-item:hover { background: var(--bg-hover); }+.step-item.active { background: var(--accent-dim); border-left-color: var(--accent-primary); }+.step-item.completed .step-icon { color: var(--success); }+.step-item.skipped .step-icon { color: var(--text-dim); }+.step-item.failed .step-icon { color: var(--error); }+.step-item.failed .step-label { color: var(--error); }++.step-icon {+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 13px;+ color: var(--text-dim);+}++.step-icon.active { color: var(--accent-primary); }++.step-label {+ font-size: 13px;+ color: var(--text-secondary);+}++.step-item.active .step-label { color: var(--text-primary); font-weight: 700; }+.step-item.completed .step-label { color: var(--text-secondary); }++.sidebar-footer {+ padding: 16px 20px;+ border-top: 1px solid var(--border);+}++.sidebar-progress-text {+ font-family: var(--font-mono);+ font-size: 11px;+ color: var(--text-dim);+ margin-bottom: 8px;+}++.sidebar-progress-bar {+ width: 100%;+ height: 4px;+ background: var(--bg-input);+ border-radius: 2px;+ overflow: hidden;+}++.sidebar-progress-fill {+ height: 100%;+ background: var(--accent-primary);+ transition: width 0.5s ease;+}++/* ─── Main Content ─────────────────────────────────────── */+.main {+ display: flex;+ flex-direction: column;+ overflow: hidden;+ background: var(--bg-deep);+}++/* ─── Chat Area ────────────────────────────────────────── */+.chat-container {+ flex: 1;+ overflow-y: auto;+ padding: 24px 32px;+ display: flex;+ flex-direction: column;+ gap: 16px;+}++.chat-container::-webkit-scrollbar { width: 4px; }+.chat-container::-webkit-scrollbar-track { background: transparent; }+.chat-container::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 2px; }++/* Messages */+.section-header {+ width: 100%;+ max-width: 760px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ margin: 8px 0 4px;+ padding: 12px 0;+ animation: cardIn 0.35s cubic-bezier(0.16, 1, 0.3, 1);+}++.section-header-rule {+ width: 100%;+ height: 1px;+ background: linear-gradient(90deg, transparent, var(--accent-primary), transparent);+ box-shadow: 0 0 12px var(--glow-blue-strong);+}++.section-header-content {+ display: grid;+ grid-template-columns: 1fr auto;+ gap: 8px 20px;+ padding: 18px 20px;+ background: linear-gradient(135deg, var(--bg-elevated), var(--bg-surface));+ border: 1px solid var(--border-strong);+ border-radius: var(--radius-lg);+ box-shadow: 0 0 0 1px var(--border), 0 12px 32px var(--glow-blue);+}++.section-header-title {+ font-family: var(--font-display);+ font-size: 22px;+ letter-spacing: 4px;+ text-transform: uppercase;+ color: var(--accent-secondary);+}++.section-header-subtitle {+ grid-column: 1 / 2;+ font-size: 12px;+ line-height: 1.7;+ color: var(--text-secondary);+}++.section-header-step {+ grid-column: 2 / 3;+ grid-row: 1 / span 2;+ align-self: center;+ justify-self: end;+ font-family: var(--font-mono);+ font-size: 11px;+ color: var(--text-secondary);+ letter-spacing: 1px;+ text-transform: uppercase;+}++.msg {+ max-width: 680px;+ padding: 16px 20px;+ border-radius: var(--radius-lg);+ animation: msgIn 0.3s ease-out;+ line-height: 1.7;+}++@keyframes msgIn {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+}++.msg.assistant {+ background: var(--bg-elevated);+ border: 1px solid var(--border);+ color: var(--text-primary);+ align-self: flex-start;+ border-left: 2px solid var(--accent-dim);+}++.msg.system {+ background: var(--accent-dim);+ border: 1px solid var(--border-strong);+ color: var(--accent-secondary);+ align-self: center;+ font-family: var(--font-mono);+ font-size: 13px;+ text-align: center;+ max-width: 500px;+}++.msg.user {+ background: linear-gradient(135deg, var(--accent-primary), #2563eb);+ color: white;+ align-self: flex-end;+ box-shadow: 0 2px 12px rgba(59, 130, 246, 0.2);+}++.msg.error {+ background: rgba(239, 68, 68, 0.12);+ border: 1px solid rgba(239, 68, 68, 0.4);+ border-left: 3px solid var(--error);+ color: #fca5a5;+ align-self: stretch;+ font-family: var(--font-mono);+ font-size: 13px;+ max-width: 100%;+}++/* Inline forms in chat — "Question Card" treatment */+.inline-form {+ position: relative;+ background: linear-gradient(135deg, rgba(30, 32, 48, 0.95), rgba(26, 27, 38, 0.98));+ border: 1px solid var(--border-interactive);+ border-radius: var(--radius-lg);+ padding: 24px 24px 24px 28px;+ max-width: 680px;+ animation: cardIn 0.4s cubic-bezier(0.16, 1, 0.3, 1), questionPulse 3s ease-in-out 0.5s infinite;+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+}++/* Left accent bar — signals interactivity */+.inline-form::before {+ content: '';+ position: absolute;+ left: 0;+ top: 12px;+ bottom: 12px;+ width: 3px;+ border-radius: 0 2px 2px 0;+ background: linear-gradient(180deg, var(--accent-primary), var(--accent-secondary), var(--accent-primary));+ background-size: 100% 200%;+ animation: accentSlide 3s linear infinite;+}++/* Question badge */+.inline-form::after {+ content: '?';+ position: absolute;+ top: -10px;+ right: 16px;+ width: 22px;+ height: 22px;+ background: var(--accent-primary);+ color: white;+ font-family: var(--font-mono);+ font-size: 12px;+ font-weight: 700;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 50%;+ box-shadow: 0 2px 8px rgba(59, 130, 246, 0.4);+}++.inline-form label {+ display: block;+ font-family: var(--font-mono);+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 1.5px;+ color: var(--accent-secondary);+ margin-bottom: 12px;+}++.inline-form .form-row {+ display: flex;+ gap: 10px;+}++/* Remove pulse once form is answered */+.inline-form:has(.inline-input:disabled) {+ animation: none;+ border-color: var(--border);+ opacity: 0.6;+}+.inline-form:has(.inline-input:disabled)::before { animation: none; opacity: 0.3; }+.inline-form:has(.inline-input:disabled)::after { background: var(--text-dim); box-shadow: none; }++.inline-input {+ flex: 1;+ background: var(--bg-input);+ border: 1px solid var(--border-strong);+ border-radius: var(--radius);+ padding: 12px 16px;+ color: var(--text-primary);+ font-family: var(--font-mono);+ font-size: 14px;+ outline: none;+ transition: border-color 0.2s, box-shadow 0.2s;+ animation: inputReady 2.5s ease-in-out infinite;+}++.inline-input:focus {+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 3px var(--glow-blue), inset 0 0 0 1px var(--accent-primary);+ animation: none;+}+.inline-input::placeholder { color: var(--text-dim); }+.inline-input:disabled { animation: none; }++.inline-btn {+ background: linear-gradient(135deg, var(--accent-primary), #2563eb);+ color: white;+ border: none;+ border-radius: var(--radius);+ padding: 12px 24px;+ font-family: var(--font-mono);+ font-size: 13px;+ font-weight: 700;+ letter-spacing: 0.5px;+ text-transform: uppercase;+ cursor: pointer;+ transition: all 0.2s;+ box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);+}++.inline-btn:hover {+ background: linear-gradient(135deg, #2563eb, #1d4ed8);+ box-shadow: 0 4px 16px rgba(59, 130, 246, 0.4);+ transform: translateY(-1px);+}+.inline-btn:active { transform: translateY(0) scale(0.97); }+.inline-btn:disabled { opacity: 0.4; cursor: not-allowed; box-shadow: none; transform: none; }++/* Choice buttons — "Select an option" question card */+.choice-group {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 6px;+ max-width: 680px;+ background: linear-gradient(135deg, rgba(30, 32, 48, 0.95), rgba(26, 27, 38, 0.98));+ border: 1px solid var(--border-interactive);+ border-radius: var(--radius-lg);+ padding: 24px 24px 20px 28px;+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ animation: cardIn 0.4s cubic-bezier(0.16, 1, 0.3, 1), questionPulse 3s ease-in-out 0.5s infinite;+}++/* Left accent bar */+.choice-group::before {+ content: '';+ position: absolute;+ left: 0;+ top: 12px;+ bottom: 12px;+ width: 3px;+ border-radius: 0 2px 2px 0;+ background: linear-gradient(180deg, var(--accent-primary), var(--accent-secondary), var(--accent-primary));+ background-size: 100% 200%;+ animation: accentSlide 3s linear infinite;+}++/* Question badge */+.choice-group::after {+ content: '?';+ position: absolute;+ top: -10px;+ right: 16px;+ width: 22px;+ height: 22px;+ background: var(--accent-primary);+ color: white;+ font-family: var(--font-mono);+ font-size: 12px;+ font-weight: 700;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 50%;+ box-shadow: 0 2px 8px rgba(59, 130, 246, 0.4);+}++/* Dim the card once a choice has been made */+.choice-group:has(.choice-btn:disabled) {+ animation: none;+ border-color: var(--border);+ opacity: 0.7;+}+.choice-group:has(.choice-btn:disabled)::before { animation: none; opacity: 0.3; }+.choice-group:has(.choice-btn:disabled)::after { background: var(--text-dim); box-shadow: none; }++.choice-btn {+ position: relative;+ background: var(--bg-input);+ border: 1px solid var(--border-strong);+ border-radius: var(--radius);+ padding: 14px 18px 14px 40px;+ color: var(--text-primary);+ font-family: var(--font-body);+ font-size: 14px;+ text-align: left;+ cursor: pointer;+ transition: all 0.2s;+}++/* Radio-style dot indicator */+.choice-btn::before {+ content: '';+ position: absolute;+ left: 14px;+ top: 50%;+ transform: translateY(-50%);+ width: 14px;+ height: 14px;+ border-radius: 50%;+ border: 2px solid var(--text-dim);+ transition: all 0.2s;+}++.choice-btn:hover {+ background: var(--accent-dim);+ border-color: var(--accent-primary);+ transform: translateX(4px);+}++.choice-btn:hover::before {+ border-color: var(--accent-primary);+ background: rgba(59, 130, 246, 0.2);+}++/* Selected state (applied via JS inline style override) */+.choice-btn:disabled {+ cursor: default;+ transform: none;+}++.choice-btn .choice-label {+ display: block;+}++.choice-btn .choice-desc {+ display: block;+ font-size: 12px;+ color: var(--text-dim);+ margin-top: 4px;+ padding-left: 0;+}++.choice-btn .preview-btn {+ display: inline-block;+ margin-top: 6px;+ font-family: var(--font-mono);+ font-size: 11px;+ color: var(--accent-secondary);+ cursor: pointer;+ transition: color 0.2s;+}++.choice-btn .preview-btn:hover {+ color: var(--accent-primary);+}++/* Progress indicator in chat */+.progress-msg {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 10px 16px;+ background: var(--bg-surface);+ border-radius: var(--radius);+ font-family: var(--font-mono);+ font-size: 12px;+ color: var(--text-secondary);+ max-width: 500px;+ animation: msgIn 0.3s ease-out;+}++.progress-msg .mini-bar {+ width: 80px;+ height: 4px;+ background: var(--bg-input);+ border-radius: 2px;+ overflow: hidden;+}++.progress-msg .mini-fill {+ height: 100%;+ background: var(--accent-primary);+ transition: width 0.3s;+}++/* Detection results */+.detection-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 10px;+ max-width: 680px;+ padding: 20px;+ background: linear-gradient(135deg, rgba(30, 32, 48, 0.9), rgba(26, 27, 38, 0.95));+ border: 1px solid var(--border-strong);+ border-radius: var(--radius-lg);+ animation: cardIn 0.4s cubic-bezier(0.16, 1, 0.3, 1);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+}++.detection-item {+ display: flex;+ align-items: center;+ gap: 8px;+ font-family: var(--font-mono);+ font-size: 12px;+}++.detection-item .check { color: var(--success); }+.detection-item .cross { color: var(--error); }+.detection-item .info { color: var(--accent-secondary); }++/* Validation results */+.validation-list {+ max-width: 680px;+ animation: msgIn 0.3s ease-out;+}++.validation-item {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 8px 0;+ font-size: 13px;+ border-bottom: 1px solid var(--border);+}++.validation-item:last-child { border-bottom: none; }+.validation-item .v-icon { font-size: 14px; }+.validation-item .v-name { color: var(--text-primary); min-width: 140px; }+.validation-item .v-detail { color: var(--text-secondary); font-family: var(--font-mono); font-size: 12px; }++/* Summary card */+.summary-card {+ background: linear-gradient(135deg, rgba(30, 32, 48, 0.95), rgba(26, 27, 38, 0.98));+ border: 1px solid rgba(34, 197, 94, 0.35);+ border-left: 3px solid var(--success);+ border-radius: var(--radius-lg);+ padding: 28px;+ max-width: 500px;+ animation: cardIn 0.4s cubic-bezier(0.16, 1, 0.3, 1);+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.3), 0 0 0 0 rgba(34, 197, 94, 0);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+}++.summary-card h3 {+ font-family: var(--font-display);+ font-size: 16px;+ letter-spacing: 2px;+ text-transform: uppercase;+ color: var(--success);+ margin-bottom: 16px;+}++.summary-row {+ display: flex;+ justify-content: space-between;+ padding: 6px 0;+ font-size: 13px;+}++.summary-row .s-label { color: var(--text-dim); }+.summary-row .s-value { color: var(--text-primary); font-family: var(--font-mono); }++.summary-action {+ margin-top: 20px;+ padding: 16px 20px;+ background: var(--accent-dim);+ border: 1px solid var(--border-strong);+ border-radius: var(--radius);+ text-align: center;+}++.summary-action p {+ font-size: 13px;+ color: var(--text-secondary);+ margin-bottom: 10px;+}++.summary-action code {+ display: block;+ background: var(--bg-input);+ padding: 12px 16px;+ border-radius: var(--radius);+ color: var(--accent-primary);+ font-family: var(--font-mono);+ font-size: 15px;+ font-weight: 700;+ letter-spacing: 0.5px;+ border: 1px solid var(--border-interactive);+ user-select: all;+ cursor: text;+}++.summary-action .summary-hint {+ font-size: 11px;+ color: var(--text-dim);+ margin-top: 8px;+ margin-bottom: 0;+}++/* ─── Chat Input ───────────────────────────────────────── */+.chat-input-area {+ padding: 16px 32px;+ background: var(--bg-surface);+ border-top: 1px solid var(--border);+ display: flex;+ gap: 8px;+}++.chat-input {+ flex: 1;+ background: var(--bg-input);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 12px 16px;+ color: var(--text-primary);+ font-family: var(--font-body);+ font-size: 14px;+ outline: none;+ transition: border-color 0.2s;+}++.chat-input:focus { border-color: var(--accent-primary); box-shadow: 0 0 0 3px var(--glow-blue); }+.chat-input::placeholder { color: var(--text-dim); }+.chat-input:disabled { opacity: 0.4; }++.chat-send {+ background: linear-gradient(135deg, var(--accent-primary), #2563eb);+ border: none;+ border-radius: var(--radius);+ padding: 12px 24px;+ color: white;+ font-family: var(--font-mono);+ font-size: 12px;+ font-weight: 700;+ letter-spacing: 0.5px;+ text-transform: uppercase;+ cursor: pointer;+ transition: all 0.2s;+ box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);+}++.chat-send:hover { background: linear-gradient(135deg, #2563eb, #1d4ed8); box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3); }+.chat-send:disabled { opacity: 0.4; cursor: not-allowed; box-shadow: none; }++/* ─── Welcome Overlay ──────────────────────────────────── */+.welcome-overlay {+ position: fixed;+ inset: 0;+ background: var(--bg-deep);+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ z-index: 100;+ transition: opacity 0.5s ease;+}++.welcome-overlay.hidden {+ opacity: 0;+ pointer-events: none;+}++.welcome-logo {+ width: 160px;+ height: 160px;+ animation: logoPulse 3s ease-in-out infinite;+ margin-bottom: 32px;+}++@keyframes logoPulse {+ 0%, 100% { filter: drop-shadow(0 0 8px rgba(59, 130, 246, 0.3)); }+ 50% { filter: drop-shadow(0 0 20px rgba(59, 130, 246, 0.6)); }+}++.welcome-title {+ font-family: var(--font-display);+ font-size: 28px;+ letter-spacing: 6px;+ text-transform: uppercase;+ color: var(--accent-secondary);+ margin-bottom: 8px;+}++.welcome-subtitle {+ font-family: var(--font-mono);+ font-size: 13px;+ color: var(--text-dim);+ margin-bottom: 40px;+}++.welcome-start {+ background: linear-gradient(135deg, var(--accent-primary), #2563eb);+ border: none;+ border-radius: var(--radius);+ padding: 16px 48px;+ font-family: var(--font-display);+ font-size: 14px;+ letter-spacing: 3px;+ text-transform: uppercase;+ color: white;+ cursor: pointer;+ transition: all 0.3s;+ box-shadow: 0 4px 20px rgba(59, 130, 246, 0.25);+}++.welcome-start:hover {+ background: linear-gradient(135deg, #2563eb, #1d4ed8);+ transform: translateY(-3px);+ box-shadow: 0 8px 32px rgba(59, 130, 246, 0.4);+}++.welcome-start:active {+ transform: translateY(-1px);+ box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3);+}++/* ─── Loading Spinner ──────────────────────────────────── */+.spinner {+ width: 16px;+ height: 16px;+ border: 2px solid var(--border);+ border-top-color: var(--accent-primary);+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ display: inline-block;+}++@keyframes spin { to { transform: rotate(360deg); } }++/* ─── Question Card Animations ────────────────────────── */+@keyframes questionPulse {+ 0%, 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0), 0 4px 24px rgba(0, 0, 0, 0.3); }+ 50% { box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15), 0 4px 24px rgba(0, 0, 0, 0.3); }+}++@keyframes accentSlide {+ 0% { background-position: 0% 0%; }+ 100% { background-position: 0% 200%; }+}++@keyframes inputReady {+ 0%, 100% { border-color: var(--border-strong); }+ 50% { border-color: var(--accent-primary); }+}++@keyframes cardIn {+ from { opacity: 0; transform: translateY(12px) scale(0.98); }+ to { opacity: 1; transform: translateY(0) scale(1); }+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/web/routes.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/web/routes.tsnew file mode 100644index 00000000..e35c6551--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/web/routes.ts@@ -0,0 +1,284 @@+/**+ * PAI Installer v5.0 — API Routes+ * HTTP + WebSocket API for the web installer.+ */++import type { InstallState, EngineEvent, ServerMessage, ClientMessage } from "../engine/types";+import { detectSystem, validateElevenLabsKey } from "../engine/detect";+import {+ runSystemDetect,+ runPrerequisites,+ runApiKeys,+ runIdentity,+ runRepository,+ runConfiguration,+ runVoiceSetup,+ runTelegramSetup,+} from "../engine/actions";+import { runValidation, generateSummary } from "../engine/validate";+import {+ createFreshState,+ hasSavedState,+ loadState,+ saveState,+ clearState,+ completeStep,+ skipStep,+} from "../engine/state";+import { STEPS, getProgress, getStepStatuses } from "../engine/steps";++// ─── State ───────────────────────────────────────────────────────++let installState: InstallState | null = null;+let wsClients = new Set<any>();+let messageHistory: ServerMessage[] = [];+let pendingRequests = new Map<string, { resolve: (value: string) => void }>();++// ─── Broadcasting ────────────────────────────────────────────────++function broadcast(msg: ServerMessage): void {+ const raw = JSON.stringify(msg);+ messageHistory.push(msg);+ for (const ws of wsClients) {+ try {+ ws.send(raw);+ } catch {+ wsClients.delete(ws);+ }+ }+}++// ─── Engine Event → WebSocket ────────────────────────────────────++function createWsEmitter(): (event: EngineEvent) => Promise<void> {+ return async (event: EngineEvent) => {+ switch (event.event) {+ case "step_start":+ broadcast({ type: "step_update", step: event.step, status: "active" });+ break;+ case "section_header":+ broadcast({+ type: "section_header",+ sectionId: event.sectionId,+ title: event.title,+ subtitle: event.subtitle,+ stepNumber: event.stepNumber,+ });+ break;+ case "step_complete":+ broadcast({ type: "step_update", step: event.step, status: "completed" });+ break;+ case "step_skip":+ broadcast({ type: "step_update", step: event.step, status: "skipped", detail: event.reason });+ break;+ case "step_error":+ broadcast({ type: "error", message: event.error, step: event.step });+ break;+ case "progress":+ broadcast({ type: "progress", step: event.step, percent: event.percent, detail: event.detail });+ break;+ case "message":+ broadcast({ type: "message", role: "assistant", content: event.content, speak: event.speak });+ break;+ case "error":+ broadcast({ type: "error", message: event.message });+ break;+ }+ };+}++// ─── Input Request Bridge ────────────────────────────────────────++async function requestInput(+ id: string,+ prompt: string,+ type: "text" | "password" | "key",+ placeholder?: string+): Promise<string> {+ return new Promise<string>((resolve) => {+ pendingRequests.set(id, { resolve });+ broadcast({ type: "input_request", id, prompt, inputType: type, placeholder });+ });+}++async function requestChoice(+ id: string,+ prompt: string,+ choices: { label: string; value: string; description?: string }[]+): Promise<string> {+ return new Promise<string>((resolve) => {+ pendingRequests.set(id, { resolve });+ broadcast({ type: "choice_request", id, prompt, choices });+ });+}++// ─── WebSocket Message Handler ───────────────────────────────────++export function handleWsMessage(ws: any, raw: string): void {+ let msg: ClientMessage;+ try {+ msg = JSON.parse(raw);+ } catch {+ return;+ }++ switch (msg.type) {+ case "client_ready":+ // Replay message history+ for (const m of messageHistory) {+ ws.send(JSON.stringify({ ...m, replayed: true }));+ }+ // Send current state+ if (installState) {+ const steps = getStepStatuses(installState);+ for (const s of steps) {+ ws.send(JSON.stringify({ type: "step_update", step: s.id, status: s.status }));+ }+ }+ break;++ case "user_input": {+ const pending = pendingRequests.get(msg.requestId);+ if (pending) {+ pending.resolve(msg.value);+ pendingRequests.delete(msg.requestId);+ // Echo user message (masked for keys)+ const display = msg.value.startsWith("sk-") || msg.value.startsWith("xi-")+ ? msg.value.substring(0, 8) + "..."+ : msg.value;+ if (display) {+ broadcast({ type: "message", role: "system" as any, content: display });+ }+ }+ break;+ }++ case "user_choice": {+ const pending = pendingRequests.get(msg.requestId);+ if (pending) {+ pending.resolve(msg.value);+ pendingRequests.delete(msg.requestId);+ }+ break;+ }++ case "start_install": {+ if (!installState) {+ startInstallation();+ }+ break;+ }+ }+}++// ─── Installation Flow ───────────────────────────────────────────++async function startInstallation(): Promise<void> {+ // Always start fresh — GUI should not silently resume stale state+ if (hasSavedState()) clearState();+ installState = createFreshState("web");++ const emit = createWsEmitter();++ try {+ // Step 1: System Detection+ if (!installState.completedSteps.includes("system-detect")) {+ await runSystemDetect(installState, emit, requestChoice);+ broadcast({ type: "detection_result", data: installState.detection! });+ completeStep(installState, "system-detect");+ installState.currentStep = "prerequisites";+ }++ // Step 2: Prerequisites+ if (!installState.completedSteps.includes("prerequisites")) {+ await runPrerequisites(installState, emit);+ completeStep(installState, "prerequisites");+ installState.currentStep = "api-keys";+ }++ // Step 3: API Keys+ if (!installState.completedSteps.includes("api-keys")) {+ await runApiKeys(installState, emit, requestInput, requestChoice);+ completeStep(installState, "api-keys");+ installState.currentStep = "identity";+ }++ // Step 4: Identity+ if (!installState.completedSteps.includes("identity")) {+ await runIdentity(installState, emit, requestInput);+ completeStep(installState, "identity");+ installState.currentStep = "repository";+ }++ // Step 5: Repository+ if (!installState.completedSteps.includes("repository")) {+ await runRepository(installState, emit);+ completeStep(installState, "repository");+ installState.currentStep = "configuration";+ }++ // Step 6: Configuration+ if (!installState.completedSteps.includes("configuration")) {+ await runConfiguration(installState, emit);+ completeStep(installState, "configuration");+ installState.currentStep = "voice";+ }++ // Step 7: Voice (handles key collection + voice selection + server test)+ if (!installState.completedSteps.includes("voice") && !installState.skippedSteps.includes("voice")) {+ try {+ await runVoiceSetup(installState, emit, requestChoice, requestInput);+ if (!installState.skippedSteps.includes("voice")) {+ completeStep(installState, "voice");+ }+ } catch (voiceErr: any) {+ broadcast({ type: "error", message: `Voice setup error: ${voiceErr?.message || "Unknown error"}` });+ broadcast({ type: "message", role: "assistant", content: "Voice setup encountered an error. Continuing with installation..." });+ skipStep(installState, "voice", voiceErr?.message || "error");+ }+ installState.currentStep = "telegram";+ }++ // Step 8: Telegram (optional — token + allowed user/chat ID + Pulse restart)+ if (!installState.completedSteps.includes("telegram") && !installState.skippedSteps.includes("telegram")) {+ try {+ await runTelegramSetup(installState, emit, requestChoice, requestInput);+ if (!installState.skippedSteps.includes("telegram") && !installState.completedSteps.includes("telegram")) {+ completeStep(installState, "telegram");+ }+ } catch (telegramErr: any) {+ broadcast({ type: "error", message: `Telegram setup error: ${telegramErr?.message || "Unknown error"}` });+ skipStep(installState, "telegram", telegramErr?.message || "error");+ }+ installState.currentStep = "validation";+ }++ // Step 9: Validation+ const checks = await runValidation(installState, emit);+ broadcast({ type: "validation_result", checks });+ completeStep(installState, "validation");+ broadcast({ type: "step_update", step: "validation", status: "completed" });++ const summary = generateSummary(installState);+ broadcast({ type: "install_complete", success: true, summary });++ clearState();+ } catch (error: any) {+ broadcast({ type: "error", message: error.message });+ saveState(installState);+ }+}++// ─── Connection Management ───────────────────────────────────────++export function addClient(ws: any): void {+ wsClients.add(ws);+}++export function removeClient(ws: any): void {+ wsClients.delete(ws);+}++export function getState(): InstallState | null {+ return installState;+}diff --git a/Releases/v5.0.0/.claude/PAI/PAI-Install/web/server.ts b/Releases/v5.0.0/.claude/PAI/PAI-Install/web/server.tsnew file mode 100644index 00000000..50cdebb0--- /dev/null+++ b/Releases/v5.0.0/.claude/PAI/PAI-Install/web/server.ts@@ -0,0 +1,123 @@+/**+ * PAI Installer v5.0 — Web Server+ * Bun HTTP + WebSocket server for the thick-client web installer.+ * Serves static files and handles WebSocket communication.+ */++// Prevent unhandled errors from crashing the server+process.on("uncaughtException", (err) => {+ console.error("[PAI Installer] Uncaught exception:", err.message);+});+process.on("unhandledRejection", (err: any) => {+ console.error("[PAI Installer] Unhandled rejection:", err?.message || err);+});++import { existsSync, readFileSync } from "fs";+import { join, extname } from "path";+import { handleWsMessage, addClient, removeClient } from "./routes";++const PORT = parseInt(process.env.PAI_INSTALL_PORT || "1337");+const PUBLIC_DIR = join(import.meta.dir, "..", "public");++// ─── MIME Types ──────────────────────────────────────────────────++const MIME_TYPES: Record<string, string> = {+ ".html": "text/html",+ ".css": "text/css",+ ".js": "application/javascript",+ ".json": "application/json",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".svg": "image/svg+xml",+ ".mp3": "audio/mpeg",+ ".wav": "audio/wav",+ ".woff2": "font/woff2",+ ".ttf": "font/ttf",+ ".ico": "image/x-icon",+};++// ─── Inactivity Timeout ──────────────────────────────────────────++const INACTIVITY_MS = 30 * 60 * 1000; // 30 minutes+let inactivityTimer: Timer | null = null;++function resetInactivity(): void {+ if (inactivityTimer) clearTimeout(inactivityTimer);+ inactivityTimer = setTimeout(() => {+ console.log("\n[PAI Installer] Shutting down due to inactivity.");+ process.exit(0);+ }, INACTIVITY_MS);+}++// ─── Server ──────────────────────────────────────────────────────++const server = Bun.serve({+ port: PORT,+ hostname: "127.0.0.1", // Localhost only — never expose to network++ fetch(req, server) {+ resetInactivity();++ const url = new URL(req.url);++ // WebSocket upgrade+ if (url.pathname === "/ws") {+ const upgraded = server.upgrade(req);+ if (!upgraded) {+ return new Response("WebSocket upgrade failed", { status: 400 });+ }+ return undefined as any;+ }++ // Static file serving+ let filePath = url.pathname === "/" ? "/index.html" : url.pathname;+ const fullPath = join(PUBLIC_DIR, filePath);++ // Security: prevent directory traversal+ if (!fullPath.startsWith(PUBLIC_DIR)) {+ return new Response("Forbidden", { status: 403 });+ }++ if (existsSync(fullPath)) {+ const ext = extname(fullPath);+ const mime = MIME_TYPES[ext] || "application/octet-stream";+ const content = readFileSync(fullPath);+ return new Response(content, {+ headers: {+ "content-type": mime,+ "cache-control": "no-cache, no-store, must-revalidate",+ },+ });+ }++ // Fallback to index.html for SPA routing+ const indexPath = join(PUBLIC_DIR, "index.html");+ if (existsSync(indexPath)) {+ return new Response(readFileSync(indexPath), {+ headers: { "content-type": "text/html", "cache-control": "no-cache" },+ });+ }++ return new Response("Not Found", { status: 404 });+ },++ websocket: {+ open(ws) {+ addClient(ws);+ ws.send(JSON.stringify({ type: "connected", port: PORT }));+ },+ message(ws, message) {+ resetInactivity();+ handleWsMessage(ws, typeof message === "string" ? message : message.toString());+ },+ close(ws) {+ removeClient(ws);+ },+ },+});++resetInactivity();++console.log(`PAI Installer server running on http://127.0.0.1:${PORT}/`);++export { server };