⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
feat: Browser skill v1.2.0 with debug-first architecture and wizard-style installer
Daniel Miessler999dcab56ed9
diff --git a/Packs/README.md b/Packs/README.mdindex 36c7921c..41409f90 100644--- a/Packs/README.md+++ b/Packs/README.md@@ -56,12 +56,42 @@ The directory structure provides:- **Clear separation** - README for context, INSTALL for steps, VERIFY for validation- **Verbatim copying** - AI agents copy actual files instead of extracting from markdown-### AI Installation Flow+### AI Installation Flow (Wizard-Style)-When installing a pack:-1. AI reads `README.md` for context and architecture understanding-2. AI follows `INSTALL.md` step-by-step, copying files from `src/` to `$PAI_DIR/`-3. AI completes `VERIFY.md` checklist to confirm success+Packs use **wizard-style installation** that leverages Claude Code's native tools:++```+Phase 1: System Analysis+├── Run detection commands+├── Check prerequisites+├── Find conflicts+└── Present findings to user++Phase 2: User Questions (AskUserQuestion)+├── Q1: Handle missing prerequisites+├── Q2: Resolve conflicts (if any)+├── Q3: Optional features (if any)+└── Q4: Final confirmation++Phase 3: Backup (if needed)+└── Create timestamped backup++Phase 4: Installation (TodoWrite for progress)+├── Create directories+├── Copy files from src/+├── Install dependencies+└── Pack-specific steps++Phase 5: Verification+└── Run all VERIFY.md checks+```++**Key tools used:**+- **AskUserQuestion** - For user decisions at each decision point+- **TodoWrite** - For progress tracking (user sees what's happening)+- **VERIFY.md** - For validation (all checks must pass)++See `Tools/InstallTemplate.md` for the complete INSTALL.md template.---@@ -146,7 +176,7 @@ PAI System| [**kai-art-skill**](kai-art-skill/) | 1.0.0 | Creativity | Visual content generation with Excalidraw hand-drawn aesthetic - diagrams, comics, illustrations || [**kai-agents-skill**](kai-agents-skill/) | 1.0.0 | Delegation | Dynamic agent composition - create custom agents with unique personalities, voices, and trait combinations || [**kai-prompting-skill**](kai-prompting-skill/) | 1.0.0 | Methodology | Meta-prompting system with Handlebars templates, Claude 4.x best practices, and the Ultimate Prompt Template |-| [**kai-browser-skill**](kai-browser-skill/) | 1.0.0 | Automation | Code-first browser automation with Playwright - 99% token savings over MCP, screenshots, verification, web testing |+| [**kai-browser-skill**](kai-browser-skill/) | 1.2.0 | Automation | Debug-first browser automation with Playwright - always-on diagnostics, session auto-start, 99% token savings |---@@ -231,10 +261,11 @@ See [.env.example](../.env.example) for the complete list of supported variables## Creating Your Own PackSee [PAIPackTemplate.md](../Tools/PAIPackTemplate.md) for the complete pack specification.+See [InstallTemplate.md](../Tools/InstallTemplate.md) for the wizard-style INSTALL.md template.**Quick checklist for directory-based packs:**- [ ] `README.md` with YAML frontmatter, problem/solution, architecture-- [ ] `INSTALL.md` with step-by-step instructions+- [ ] `INSTALL.md` with wizard-style phases (analysis, questions, install, verify)- [ ] `VERIFY.md` with mandatory completion checklist- [ ] `src/` directory with actual code files (not embedded in markdown)- [ ] 256x256 transparent icon in `icons/`diff --git a/Packs/kai-browser-skill/INSTALL.md b/Packs/kai-browser-skill/INSTALL.mdindex 402c27e1..76159deb 100644--- a/Packs/kai-browser-skill/INSTALL.md+++ b/Packs/kai-browser-skill/INSTALL.md@@ -1,14 +1,36 @@-# Kai Browser Skill - Installation Guide+# Browser Skill v1.2.0 - Installation Guide**This guide is designed for AI agents installing this pack into a user's infrastructure.**----## Step 0: Pre-Installation System Analysis+## 🎯 AI Agent Instructions-**CRITICAL: Execute this analysis BEFORE any file operations.**+**This is a wizard-style installation.** Use Claude Code's native tools to guide the user through installation:-### 0.1 Environment Detection+1. **AskUserQuestion** - For user decisions and confirmations+2. **TodoWrite** - For progress tracking+3. **Bash/Read/Write** - For actual installation+4. **VERIFY.md** - For final validation++### Welcome Message++Before starting, greet the user:+```+"I'm installing the Browser skill v1.2.0 - debug-first browser automation with+Playwright. This provides screenshot capture, web verification, and browser+testing with 99% token savings over MCP approaches.++Let me analyze your system and guide you through installation."+```++---++## Phase 1: System Analysis++**Execute this analysis BEFORE any file operations.**++### 1.1 Run These Commands```bash# Detect operating system@@ -28,17 +50,91 @@ ls -la ~/.cache/ms-playwright/ 2>/dev/null || \echo "No Playwright browsers installed"```-### 0.2 Conflict Resolution Matrix+### 1.2 Present Findings-| Existing State | Action Required |-|----------------|-----------------|-| No Browser/Playwright/Browse skill | Clean install - proceed normally |-| Existing `Browser/` skill | **ASK USER**: Backup and replace, or abort? |-| Existing `Playwright/` skill only | Migrate: backup, install Browser, delete Playwright |-| Existing `Browse/` skill only | Migrate: backup, install Browser, delete Browse |-| Both Playwright and Browse exist | Merge migration: backup both, install Browser, delete both |+Tell the user what you found:+```+"Here's what I found on your system:+- OS: [Darwin/Linux/Windows]+- Bun: [installed v1.x / NOT INSTALLED]+- Existing Browser skill: [Yes at path / No]+- Playwright browsers: [Chromium installed / Not installed]"+```++---++## Phase 2: User Questions-### 0.3 Backup Procedure (If Conflicts Detected)+**Use AskUserQuestion tool at each decision point.**++### Question 1: Bun Runtime (if missing)++**Only ask if Bun is NOT installed:**++```json+{+ "header": "Runtime",+ "question": "Bun is required but not installed. Should I install it now?",+ "multiSelect": false,+ "options": [+ {"label": "Yes, install Bun (Recommended)", "description": "Runs: curl -fsSL https://bun.sh/install | bash"},+ {"label": "Skip - I'll install manually", "description": "Installation will pause until Bun is available"}+ ]+}+```++### Question 2: Conflict Resolution (if existing skill found)++**Only ask if existing Browser/Playwright/Browse skill detected:**++```json+{+ "header": "Conflict",+ "question": "Existing [Browser/Playwright] skill detected at $PAI_DIR/skills/[name]. How should I proceed?",+ "multiSelect": false,+ "options": [+ {"label": "Backup and Replace (Recommended)", "description": "Creates timestamped backup, then installs new version"},+ {"label": "Replace Without Backup", "description": "Overwrites existing skill without backup"},+ {"label": "Abort Installation", "description": "Cancel installation, keep existing skill"}+ ]+}+```++### Question 3: Browser Selection++```json+{+ "header": "Browsers",+ "question": "Which Playwright browsers should I install?",+ "multiSelect": false,+ "options": [+ {"label": "Chromium only (Recommended)", "description": "~200MB, covers 95% of use cases"},+ {"label": "All browsers", "description": "~600MB, includes Firefox and WebKit"},+ {"label": "Skip browser install", "description": "Use existing browsers if available"}+ ]+}+```++### Question 4: Final Confirmation++```json+{+ "header": "Install",+ "question": "Ready to install Browser skill v1.2.0?",+ "multiSelect": false,+ "options": [+ {"label": "Yes, install now (Recommended)", "description": "Proceeds with installation using choices above"},+ {"label": "Show me what will change", "description": "Lists all files that will be created/modified"},+ {"label": "Cancel", "description": "Abort installation"}+ ]+}+```++---++## Phase 3: Backup (If Needed)++**Only execute if user chose "Backup and Replace" for conflicts:**```bash# Create timestamped backup@@ -53,71 +149,66 @@ mkdir -p "$BACKUP_DIR"echo "Backup created at: $BACKUP_DIR"```-### 0.4 Dependency Check--```bash-# Verify Bun is installed-if ! command -v bun &> /dev/null; then- echo "Bun not found. Installing..."- curl -fsSL https://bun.sh/install | bash- # Reload shell or source profile-fi--# Verify bun works-bun --version-```--### 0.5 User Confirmation Points--Before proceeding, confirm with the user:-1. **Backup location acceptable?** (default: `$PAI_DIR/Backups/`)-2. **Conflict resolution approach?** (if existing skills found)-3. **Browser preference?** (default: Chromium only, option: all browsers)-----## Prerequisites+## Phase 4: Installation-- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`-- **macOS, Linux, or Windows**: Cross-platform support via Playwright+**Create a TodoWrite list to track progress:**----+```json+{+ "todos": [+ {"content": "Create skill directory structure", "status": "pending", "activeForm": "Creating directory structure"},+ {"content": "Copy skill files", "status": "pending", "activeForm": "Copying skill files"},+ {"content": "Install dependencies", "status": "pending", "activeForm": "Installing dependencies"},+ {"content": "Install Playwright browsers", "status": "pending", "activeForm": "Installing Playwright browsers"},+ {"content": "Run verification", "status": "pending", "activeForm": "Running verification"}+ ]+}+```-## Step 1: Create Skill Directory+### 4.1 Create Skill Directory++**Mark todo "Create skill directory structure" as in_progress.**```bashmkdir -p $PAI_DIR/skills/Browser-cd $PAI_DIR/skills/Browser+mkdir -p $PAI_DIR/skills/Browser/src+mkdir -p $PAI_DIR/skills/Browser/Tools+mkdir -p $PAI_DIR/skills/Browser/Workflows+mkdir -p $PAI_DIR/skills/Browser/examples```----+**Mark todo as completed.**++### 4.2 Copy Skill Files-## Step 2: Copy Skill Files+**Mark todo "Copy skill files" as in_progress.**Copy the following files from this pack to your skill directory:```bash# From kai-browser-skill pack directory-cp src/index.ts $PAI_DIR/skills/Browser/+cp src/index.ts $PAI_DIR/skills/Browser/src/cp package.json $PAI_DIR/skills/Browser/cp tsconfig.json $PAI_DIR/skills/Browser/cp SKILL.md $PAI_DIR/skills/Browser/cp README.md $PAI_DIR/skills/Browser/-# Create subdirectories-mkdir -p $PAI_DIR/skills/Browser/Tools-mkdir -p $PAI_DIR/skills/Browser/Workflows-mkdir -p $PAI_DIR/skills/Browser/examples--# Copy subdirectory contents+# Copy Toolscp Tools/Browse.ts $PAI_DIR/skills/Browser/Tools/+cp Tools/BrowserSession.ts $PAI_DIR/skills/Browser/Tools/++# Copy Workflows and examplescp Workflows/*.md $PAI_DIR/skills/Browser/Workflows/cp examples/*.ts $PAI_DIR/skills/Browser/examples/```----+**Mark todo as completed.**-## Step 3: Install Dependencies+### 4.3 Install Dependencies++**Mark todo "Install dependencies" as in_progress.**```bashcd $PAI_DIR/skills/Browser@@ -126,60 +217,84 @@ bun installThis will install:- `playwright` - Browser automation library-- Playwright browsers (Chromium, Firefox, WebKit)----+**Mark todo as completed.**-## Step 4: Install Playwright Browsers+### 4.4 Install Playwright Browsers+**Mark todo "Install Playwright browsers" as in_progress.**++Based on user's choice in Question 3:++**If "Chromium only":**```bashbunx playwright install chromium```-**Optional:** Install all browsers:+**If "All browsers":**```bashbunx playwright install```+**If "Skip":** No action needed.++**Mark todo as completed.**+----## Step 5: Verify Installation+## Phase 5: Verification-Run the verification script:+**Mark todo "Run verification" as in_progress.**++**Execute all checks from VERIFY.md.** The file contains 15 verification checks that must ALL pass.++Quick verification:```bash-bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://example.com-```+# 1. Check CLI shows v1.2.0+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts --help | head -3-Expected output:-```-Navigating to https://example.com...-Page loaded: Example Domain-Title: Example Domain-Console errors: 0+# 2. Navigate with diagnostics+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts https://example.com++# 3. Check session status+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts status++# 4. Stop session+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts stop```-Take a test screenshot:+**Mark todo as completed when all VERIFY.md checks pass.**++---++## Success/Failure Messages++### On Success-```bash-bun $PAI_DIR/skills/Browser/examples/screenshot.ts https://example.com /tmp/test.png```+"Browser skill v1.2.0 installed successfully!-Check the screenshot exists:-```bash-ls -la /tmp/test.png+What's available:+- Debug-first navigation with automatic diagnostics+- Session auto-start (no manual setup needed)+- Console/network monitoring by default+- 99% token savings vs MCP approaches++Try it: bun run $PAI_DIR/skills/Browser/Tools/Browse.ts https://example.com"```----+### On Failure-## Step 6: Test CLI Tool+```+"Installation encountered issues. Here's what to check:-```bash-# Should show help-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts+1. Bun installed? Run: which bun+2. Dependencies installed? Run: cd $PAI_DIR/skills/Browser && bun install+3. Browsers installed? Run: bunx playwright install chromium+4. Check VERIFY.md for the specific failing check-# Take a screenshot-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/cli-test.png+Need help? See Troubleshooting section below."```---@@ -212,10 +327,11 @@ bunx playwright install-deps chromium| File | Purpose ||------|---------|-| `index.ts` | PlaywrightBrowser API wrapper class |+| `src/index.ts` | PlaywrightBrowser API wrapper class || `SKILL.md` | Skill definition for Claude Code || `README.md` | Developer documentation || `Tools/Browse.ts` | CLI tool for browser operations |+| `Tools/BrowserSession.ts` | Persistent browser session server || `Workflows/*.md` | Workflow definitions || `examples/*.ts` | Example scripts || `package.json` | Dependencies |@@ -230,13 +346,13 @@ bunx playwright install-deps chromiumJust ask to use the browser:```-Navigate to danielmiessler.com and take a screenshot+Navigate to example.com and take a screenshot```### From TypeScript```typescript-import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/src/index.ts'const browser = new PlaywrightBrowser()await browser.launch()@@ -248,7 +364,14 @@ await browser.close()### From CLI```bash-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png+# Navigate with full diagnostics (primary command)+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts https://example.com++# Take screenshot+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot /tmp/shot.png++# Check for errors+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts errors```---diff --git a/Packs/kai-browser-skill/README.md b/Packs/kai-browser-skill/README.mdindex 35a33140..c6562944 100644--- a/Packs/kai-browser-skill/README.md+++ b/Packs/kai-browser-skill/README.md@@ -1,81 +1,152 @@-# Kai Browser Skill+# Browser Skill v1.2.0-**Code-first browser automation for Claude Code with 99% token savings.**+**Debug-first browser automation with always-on visibility.**++## What's New in v1.2.0++### Debug-First Architecture+- Console logs and network requests captured **by default**+- Diagnostic output with every navigation+- No more adding logging after the fact++### Session Auto-Start+- Session launches automatically on first command+- No explicit `session start` needed+- 30-minute idle timeout for cleanup++### New Commands+```bash+bun run Browse.ts <url> # Navigate with full diagnostics (PRIMARY)+bun run Browse.ts errors # Show console errors+bun run Browse.ts warnings # Show console warnings+bun run Browse.ts console # All console output+bun run Browse.ts network # Network activity+bun run Browse.ts failed # Failed requests (4xx, 5xx)+bun run Browse.ts status # Session info+bun run Browse.ts restart # Fresh session+bun run Browse.ts stop # Stop session+```++---## What It Does-The Browser skill replaces the Playwright MCP with direct code execution:+The Browser skill provides Playwright automation with 99% token savings:-- **Navigate** to URLs-- **Screenshot** pages (full page or element)+- **Navigate** to URLs with automatic diagnostics+- **Screenshot** pages with issue detection- **Interact** with forms, buttons, dropdowns- **Verify** page content and elements-- **Extract** text and HTML+- **Monitor** console logs and network requests++## Why Debug-First?++Traditional approach: Run test, it fails, add logging, run again.++Debug-first approach: **Logging already exists.** When something breaks, the data is there.++Every `bun run Browse.ts <url>` command captures:+- Screenshot+- Console errors/warnings+- Failed network requests+- Network summary+- Load status++## Quick Start++```bash+# Navigate and get full diagnostics+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts https://example.com++# Check for errors+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts errors++# Take screenshot of current page+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot /tmp/shot.png+```-## Why File-Based?+## Token Savings| Approach | Tokens | When Loaded ||----------|--------|-------------|| Playwright MCP | ~13,700 | At startup (always) |-| Browser Skill | ~50-200 | Per operation (on demand) |+| Browser Skill | ~0 | Per operation (on demand) |**Result:** 99%+ token savings-## Quick Start+## API Reference++### CLI Commands++| Command | Description |+|---------|-------------|+| `<url>` | Navigate with full diagnostics |+| `errors` | Console errors only |+| `warnings` | Console warnings only |+| `console` | All console output |+| `network` | Network activity |+| `failed` | Failed requests |+| `screenshot [path]` | Screenshot current page |+| `navigate <url>` | Navigate without diagnostics |+| `click <selector>` | Click element |+| `fill <sel> <val>` | Fill input |+| `type <sel> <text>` | Type with delay |+| `eval "<js>"` | Execute JavaScript |+| `open <url>` | Open in default browser |+| `status` | Session info |+| `restart` | Fresh session |+| `stop` | Stop session |++### TypeScript API```typescript-import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/src/index.ts'const browser = new PlaywrightBrowser()await browser.launch()await browser.navigate('https://example.com')-await browser.screenshot({ path: 'screenshot.png' })+await browser.screenshot({ path: 'shot.png' })await browser.close()```-## CLI Tool+**Navigation:** `launch()`, `navigate()`, `goBack()`, `goForward()`, `reload()`, `close()`-```bash-# Open URL in visible browser-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://example.com+**Capture:** `screenshot()`, `getVisibleText()`, `getVisibleHtml()`, `savePdf()`-# Take screenshot-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png+**Interaction:** `click()`, `fill()`, `type()`, `select()`, `pressKey()`-# Verify element exists-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com "h1"-```+**Monitoring:** `getConsoleLogs()`, `getNetworkLogs()`, `getNetworkStats()`-## API Methods+**Waiting:** `waitForSelector()`, `waitForNavigation()`, `waitForNetworkIdle()`-### Navigation-- `launch()` / `close()`-- `navigate(url)`-- `goBack()` / `goForward()` / `reload()`+## Installation-### Capture-- `screenshot(options?)`-- `getVisibleText(selector?)`-- `getVisibleHtml(options?)`-- `savePdf(path)`+See `INSTALL.md` for step-by-step instructions.-### Interaction-- `click(selector)`-- `fill(selector, value)`-- `type(selector, text)`-- `select(selector, value)`-- `pressKey(key)`+## Verification-### Waiting-- `waitForSelector(selector)`-- `waitForNavigation()`-- `waitForNetworkIdle()`-- `wait(ms)`+See `VERIFY.md` for verification steps (15 checks for v1.2.0).-## Installation+----See `INSTALL.md` for step-by-step instructions.+## Changelog-## Verification+### v1.2.0 (January 2026)+- **NEW:** Debug-first architecture with always-on event capture+- **NEW:** Session auto-start (no explicit start needed)+- **NEW:** 30-minute idle timeout for auto-cleanup+- **NEW:** Diagnostic commands (errors, warnings, console, network, failed)+- **NEW:** BrowserSession.ts persistent server+- **NEW:** Rich formatted diagnostic output+- **CHANGED:** Primary command is now `<url>` for navigate + diagnostics+- **CHANGED:** CLI expanded from 3 to 15+ commands++### v1.1.0+- CLI-first redesign+- Added decision tree routing+- Updated VERIFY phase integration-See `VERIFY.md` for verification steps.+### v1.0.0+- Initial release+- Code-first Playwright wrapper+- Basic CLI (open, screenshot, verify)diff --git a/Packs/kai-browser-skill/SKILL.md b/Packs/kai-browser-skill/SKILL.mdindex d107cdc4..f74a4fc6 100644--- a/Packs/kai-browser-skill/SKILL.md+++ b/Packs/kai-browser-skill/SKILL.md@@ -1,58 +1,46 @@---name: Browser-description: Code-first browser automation and web verification. USE WHEN browser, screenshot, navigate, web testing, verify UI, VERIFY phase. Replaces Playwright MCP with 99% token savings.+version: 1.2.0+description: Debug-first browser automation with always-on visibility. USE WHEN browser, screenshot, navigate, web testing, verify UI, VERIFY phase, debug web page. Session auto-starts, captures console/network by default.----# Browser - Code-First Browser Automation+# Browser - Debug-First Browser Automation-**Browser automation and web verification using code-first Playwright.**+**Browser automation with debugging visibility by DEFAULT.**------## File-Based MCP--This skill is a **file-based MCP** - pre-written code that executes existing scripts, NOT generates new code.--**Why file-based?** Filter data in code BEFORE returning to model context = 99%+ token savings.+Console logs, network requests, and errors are always captured - because debugging shouldn't be opt-in.----## STOP - CLI First, Always+## Philosophy: Debug-First-### The Wrong Pattern+Traditional browser automation treats debugging as an afterthought. You run your test, it fails, and THEN you add logging to figure out why.-**DO NOT write new TypeScript code for simple browser tasks:**+This skill flips that: **debugging is enabled from the start**. Every page load captures:+- Console logs (errors, warnings, info)+- Network requests and responses+- Failed requests (4xx, 5xx)+- Page load status-```typescript-// WRONG - Writing new code defeats the purpose of file-based MCPs-import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'-const browser = new PlaywrightBrowser()-await browser.launch({ headless: true })-await browser.navigate('https://example.com')-await browser.screenshot({ path: '/tmp/shot.png' })-await browser.close()-```+When something breaks, the diagnostic data already exists.-**Problems with this approach:**-- You're writing 5+ lines of boilerplate every time-- You manage browser lifecycle manually-- You duplicate what the CLI already does-- You're generating new code instead of executing existing code+----### The Right Pattern+## Session Architecture-**USE the CLI tool - it executes pre-written code:**+**Session auto-starts on first use.** No explicit start command needed.-```bash-# RIGHT - One command, zero boilerplate-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png+```+Any CLI command → Session running?+ ├─ Yes → Execute command+ └─ No → Auto-start session → Execute command```-**Benefits:**-- One command, instant execution-- Lifecycle handled automatically-- Error handling built-in-- TRUE file-based MCP pattern+**Key behaviors:**+- First command starts a persistent browser session+- Session stays alive between commands (fast subsequent operations)+- 30-minute idle timeout auto-cleans up zombie processes+- State stored in `/tmp/browser-session.json`---@@ -60,54 +48,101 @@ bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /**Location:** `$PAI_DIR/skills/Browser/Tools/Browse.ts`-### screenshot - Take a screenshot+### Primary Command - Navigate with Diagnostics```bash-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot <url> [output-path]+bun run Browse.ts <url>```-**Examples:**-```bash-# Screenshot to default location-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://danielmiessler.com+This is the **main command**. Navigates to the URL and outputs:+- Screenshot path+- Console errors (if any)+- Console warnings (if any)+- Failed requests (if any)+- Network summary+- Page load status-# Screenshot to specific file-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/example.png+**Example output:**```+📸 Screenshot: /tmp/browse-1704567890.png-### verify - Check element exists+🔴 Console Errors (1):+ • Uncaught TypeError: Cannot read property 'map' of undefined-```bash-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify <url> <selector>+🌐 Failed Requests (1):+ • GET /api/users → 500 Internal Server Error++📊 Network: 23 requests | 847KB | avg 156ms+⚠️ Page: "My App" loaded with issues```-**Examples:**+### Query Commands++Check current session state without navigating:+```bash-# Verify body exists-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com "body"+bun run Browse.ts errors # Console errors only+bun run Browse.ts warnings # Console warnings only+bun run Browse.ts console # All console output+bun run Browse.ts network # All network activity+bun run Browse.ts failed # Failed requests (4xx, 5xx)+```-# Verify specific element-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://danielmiessler.com "h1"+### Interaction Commands-# Verify by CSS selector-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com ".main-content"+```bash+bun run Browse.ts navigate <url> # Navigate without diagnostics+bun run Browse.ts screenshot [path] # Screenshot current page+bun run Browse.ts click <selector> # Click element+bun run Browse.ts fill <selector> <value> # Fill input field+bun run Browse.ts type <selector> <text> # Type with delay+bun run Browse.ts eval "<javascript>" # Execute JavaScript+bun run Browse.ts open <url> # Open in default browser```-### open - Open URL in visible browser+### Session Management```bash-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open <url>+bun run Browse.ts status # Show session info+bun run Browse.ts restart # Fresh session (clears logs)+bun run Browse.ts stop # Stop session```-**Examples:**+---++## STOP - CLI First, Always++### The Wrong Pattern++**DO NOT write new TypeScript code for simple browser tasks:**++```typescript+// WRONG - Writing new code defeats the purpose+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/src/index.ts'+const browser = new PlaywrightBrowser()+await browser.launch({ headless: true })+await browser.navigate('https://example.com')+await browser.screenshot({ path: '/tmp/shot.png' })+await browser.close()+```++**Problems:**+- 5+ lines of boilerplate every time+- Manual browser lifecycle management+- No automatic diagnostic capture++### The Right Pattern++**USE the CLI - it handles everything:**+```bash-# Open site for manual inspection-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://danielmiessler.com+# One command = navigate + screenshot + diagnostics+bun run Browse.ts https://example.com```----## Decision Tree: When to Use What+## Decision Tree```What are you trying to do?@@ -121,9 +156,10 @@ bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://danielmiessler.com│ │▼ ▼┌─────────────┐ ┌─────────────┐- │ • Screenshot│ │ • Form fill │- │ • Verify │ │ • Auth flow │- │ • Open URL │ │ • Conditionals│+ │ • Navigate │ │ • Form fill │+ │ • Screenshot│ │ • Auth flow │+ │ • Click │ │ • Conditionals│+ │ • Fill │ │ • Scraping │└─────────────┘ └─────────────┘│ │▼ ▼@@ -133,50 +169,81 @@ bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://danielmiessler.com└─────────────┘ └─────────────┘```-### Quick Reference--| Task | Use CLI? | Use TypeScript? |-|------|----------|-----------------|-| Take screenshot | YES | NO |-| Verify element exists | YES | NO |-| Open page visually | YES | NO |-| Fill multi-field form | NO | YES (Workflow) |-| Authentication flow | NO | YES (Workflow) |-| Conditional logic | NO | YES (API) |-| Multi-step interaction | NO | YES (Workflow) |--**The Rule:** Can you describe it in ONE action? (screenshot, verify, open) → CLI----## VERIFY Phase Integration**The Browser skill is MANDATORY for VERIFY phase of web changes.**-### Using CLI for Verification-Before claiming ANY web change is "live" or "working":```bash-# 1. Take screenshot of the changed page-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com/changed-page /tmp/verify.png+# 1. Navigate with full diagnostics+bun run Browse.ts https://example.com/changed-page-# 2. Verify the specific element that changed-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com/changed-page ".changed-element"+# 2. View the screenshot+Read /tmp/browse-*.png```-**Then use the Read tool to view the screenshot:**+**If you haven't LOOKED at the rendered page and its diagnostics, you CANNOT claim it works.**++---++## Debugging Workflow Example++**Scenario:** "Why isn't the user list loading?"++```bash+# Step 1: Load the page with diagnostics+$ bun run Browse.ts https://myapp.com/users++📸 Screenshot: /tmp/browse-1704567890.png++🔴 Console Errors (1):+ • Uncaught TypeError: Cannot read property 'map' of undefined++🌐 Failed Requests (1):+ • GET /api/users → 500 Internal Server Error++📊 Network: 23 requests | 847KB | avg 156ms+⚠️ Page: "User List" loaded with issues```-Read /tmp/verify.png++**Immediately identified:**+1. API returning 500 error+2. Frontend crashing because no data+3. Specific error location++```bash+# Step 2: Dig deeper+$ bun run Browse.ts console # Full console output+$ bun run Browse.ts network # All network activity+$ bun run Browse.ts failed # Just the failures```-**If you haven't LOOKED at the rendered page, you CANNOT claim it works.**+---++## Server Endpoints (for advanced use)++The persistent session runs an HTTP server on port 9222:++| Endpoint | Method | Description |+|----------|--------|-------------|+| `/health` | GET | Health check |+| `/diagnostics` | GET | Full diagnostic summary |+| `/console` | GET | Console logs |+| `/network` | GET | Network activity |+| `/navigate` | POST | Navigate to URL |+| `/click` | POST | Click element |+| `/fill` | POST | Fill input |+| `/screenshot` | POST | Take screenshot |+| `/stop` | POST | Stop server |---## Workflow Routing-For complex, multi-step tasks, use the pre-built workflows:+For complex, multi-step tasks:| Trigger | Workflow ||---------|----------|@@ -185,74 +252,35 @@ For complex, multi-step tasks, use the pre-built workflows:| Complex verification sequence | `Workflows/VerifyPage.md` || Screenshot with custom options | `Workflows/Screenshot.md` |-**Workflows use the TypeScript API internally but are pre-written.**-----## Advanced: TypeScript API+## TypeScript API (Advanced)**Only use this for custom automation that CLI cannot handle.**-Before using this API, ask yourself:-1. Did I check if CLI can do this? (screenshot/verify/open)-2. Is this a multi-step workflow? (not just one action)-3. Do I need conditional logic between actions?--**If you answered NO to all, use the CLI instead.**--### Quick Start (Advanced Users Only)-```typescript-import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/src/index.ts'const browser = new PlaywrightBrowser()await browser.launch({ headless: true })await browser.navigate('https://example.com')-// ... custom logic here ...+// ... custom logic ...await browser.close()```### API Reference-**Navigation:**-- `launch(options?)` - Start browser-- `navigate(url)` - Go to URL-- `goBack()` / `goForward()` - History navigation-- `reload()` - Refresh page-- `close()` - Shut down browser--**Capture:**-- `screenshot({ path, fullPage, selector })` - Take screenshot-- `getVisibleText(selector?)` - Extract text-- `getVisibleHtml(options)` - Get HTML-- `savePdf(path)` - Export PDF-- `getAccessibilityTree()` - A11y snapshot--**Interaction:**-- `click(selector)` - Click element-- `fill(selector, value)` - Fill input-- `type(selector, text, delay?)` - Type with delay-- `select(selector, value)` - Select dropdown-- `pressKey(key)` - Keyboard input-- `hover(selector)` - Mouse hover-- `drag(source, target)` - Drag and drop-- `uploadFile(selector, path)` - File upload--**Waiting:**-- `waitForSelector(selector, options)` - Wait for element-- `waitForText(text, options)` - Wait for text-- `waitForNavigation(options)` - Wait for page load-- `waitForNetworkIdle(timeout?)` - Wait for idle-- `wait(ms)` - Fixed delay--**JavaScript:**-- `evaluate(script)` - Run JS-- `getConsoleLogs(options)` - Get console output-- `setUserAgent(ua)` - Change user agent--**Viewport:**-- `resize(width, height)` - Set size-- `setDevice(name)` - Emulate device+**Navigation:** `launch()`, `navigate()`, `goBack()`, `goForward()`, `reload()`, `close()`++**Capture:** `screenshot()`, `getVisibleText()`, `getVisibleHtml()`, `savePdf()`, `getAccessibilityTree()`++**Interaction:** `click()`, `fill()`, `type()`, `select()`, `pressKey()`, `hover()`, `drag()`, `uploadFile()`++**Monitoring:** `getConsoleLogs()`, `getNetworkLogs()`, `getNetworkStats()`, `clearNetworkLogs()`++**Waiting:** `waitForSelector()`, `waitForText()`, `waitForNavigation()`, `waitForNetworkIdle()`, `wait()`++**Viewport:** `resize()`, `setDevice()`---@@ -260,7 +288,7 @@ await browser.close()| Approach | Tokens | Notes ||----------|--------|-------|-| Playwright MCP | ~13,700 | Loaded at startup, always |+| Playwright MCP | ~13,700 | Loaded at startup || CLI tool | ~0 | Executes pre-written code || TypeScript API | ~50-200 | Only what you write || **CLI Savings** | **99%+** | Compared to MCP |diff --git a/Packs/kai-browser-skill/Tools/Browse.ts b/Packs/kai-browser-skill/Tools/Browse.tsindex 3c69cc93..c1c2641a 100644--- a/Packs/kai-browser-skill/Tools/Browse.ts+++ b/Packs/kai-browser-skill/Tools/Browse.ts@@ -1,142 +1,651 @@#!/usr/bin/env bun/**- * Browse CLI Tool+ * Browse CLI Tool v1.2.0 - Debug-First Browser Automation*- * Browser automation using Playwright code-first interface.- * Wraps Playwright for easy CLI invocation.+ * Browser automation with debugging visibility by DEFAULT.+ * Console logs, network requests, and errors are always captured.** Usage:- * bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open <url>- * bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot <url> [path]- * bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify <url> <selector>+ * bun run Browse.ts <url> # Navigate with full diagnostics+ * bun run Browse.ts errors # Show console errors+ * bun run Browse.ts network # Show network activity+ * bun run Browse.ts failed # Show failed requests (4xx, 5xx)+ * bun run Browse.ts screenshot [path] # Take screenshot of current page+ * bun run Browse.ts click <selector> # Click element+ * bun run Browse.ts fill <selector> <value> # Fill input field*- * Examples:- * bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://danielmiessler.com- * bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png- * bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com "h1"+ * Session auto-starts on first use. No explicit start needed.*/-import { PlaywrightBrowser } from '../index.ts'+import { PlaywrightBrowser } from '../src/index.ts'-const VOICE_SERVER = 'http://localhost:8888/notify'+const STATE_FILE = '/tmp/browser-session.json'+const DEFAULT_PORT = 9222+const SESSION_TIMEOUT = 5000 // 5s to wait for session start-async function notify(message: string): Promise<void> {+// ============================================+// TYPES+// ============================================++interface SessionState {+ pid: number+ port: number+ sessionId: string+ startedAt: string+ headless: boolean+ url: string+}++interface Diagnostics {+ errors: Array<{ type: string; text: string; timestamp: number }>+ warnings: Array<{ type: string; text: string; timestamp: number }>+ failedRequests: Array<{+ url: string+ method: string+ status: number+ statusText?: string+ }>+ stats: {+ totalRequests: number+ totalResponses: number+ totalSize: number+ avgDuration: number+ }+ pageTitle: string+ pageUrl: string+}++// ============================================+// UTILITIES+// ============================================++function formatBytes(bytes: number): string {+ if (bytes === 0) return '0 B'+ const k = 1024+ const sizes = ['B', 'KB', 'MB', 'GB']+ const i = Math.floor(Math.log(bytes) / Math.log(k))+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]+}++function truncate(str: string, maxLen: number): string {+ if (str.length <= maxLen) return str+ return str.slice(0, maxLen - 3) + '...'+}++// ============================================+// SESSION MANAGEMENT+// ============================================++async function getSessionState(): Promise<SessionState | null> {try {- await fetch(VOICE_SERVER, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ message })+ const file = Bun.file(STATE_FILE)+ if (await file.exists()) {+ const content = await file.text()+ if (content.trim()) {+ return JSON.parse(content)+ }+ }+ } catch {}+ return null+}++async function isSessionRunning(): Promise<boolean> {+ const state = await getSessionState()+ if (!state) return false++ try {+ const res = await fetch(`http://localhost:${state.port}/health`, {+ signal: AbortSignal.timeout(1000)})+ return res.ok} catch {- // Voice server not running - silent fail+ // Server not responding - clean up orphan state+ try {+ const fs = await import('fs/promises')+ await fs.unlink(STATE_FILE)+ } catch {}+ return false}}-async function openUrl(url: string): Promise<void> {- await notify('Opening browser with Browse skill')- console.log(`Opening ${url} in browser...`)+async function ensureSession(): Promise<number> {+ // Check if already running+ const state = await getSessionState()+ if (state) {+ try {+ const res = await fetch(`http://localhost:${state.port}/health`, {+ signal: AbortSignal.timeout(1000)+ })+ if (res.ok) {+ return state.port+ }+ } catch {}+ }++ // Need to start session+ const port = DEFAULT_PORT++ // Check port availability+ try {+ const res = await fetch(`http://localhost:${port}/health`, {+ signal: AbortSignal.timeout(500)+ })+ if (res.ok) {+ return port // Already running on this port+ }+ } catch {}++ // Start server in background+ const { spawn } = await import('child_process')+ const serverPath = new URL('./BrowserSession.ts', import.meta.url).pathname++ const env: Record<string, string> = {+ ...process.env as Record<string, string>,+ BROWSER_PORT: String(port),+ BROWSER_HEADLESS: 'true'+ }++ const child = spawn('bun', ['run', serverPath], {+ detached: true,+ stdio: 'ignore',+ env+ })+ child.unref()++ // Wait for server to be ready+ for (let i = 0; i < 30; i++) {+ await Bun.sleep(200)+ try {+ const res = await fetch(`http://localhost:${port}/health`, {+ signal: AbortSignal.timeout(1000)+ })+ if (res.ok) {+ return port+ }+ } catch {}+ }++ throw new Error('Failed to start browser session')+}++async function sessionCommand(+ endpoint: string,+ body?: any,+ method = 'POST'+): Promise<any> {+ const port = await ensureSession()++ const options: RequestInit = {+ method,+ signal: AbortSignal.timeout(60000) // 60s for long operations+ }++ if (body && method !== 'GET') {+ options.headers = { 'Content-Type': 'application/json' }+ options.body = JSON.stringify(body)+ }++ const url = method === 'GET' && body+ ? `http://localhost:${port}/${endpoint}?${new URLSearchParams(body)}`+ : `http://localhost:${port}/${endpoint}`++ const res = await fetch(url, options)+ const data = await res.json() as { success: boolean; data?: any; error?: string }++ if (data.success) {+ return data.data+ } else {+ throw new Error(data.error || 'Unknown error')+ }+}++// ============================================+// DIAGNOSTIC FORMATTING+// ============================================++function formatDiagnostics(+ diag: Diagnostics,+ screenshotPath?: string+): string {+ const lines: string[] = []++ // Screenshot (if taken)+ if (screenshotPath) {+ lines.push(`📸 Screenshot: ${screenshotPath}`)+ lines.push('')+ }++ // Console errors+ if (diag.errors.length > 0) {+ lines.push(`🔴 Console Errors (${diag.errors.length}):`)+ for (const err of diag.errors.slice(0, 5)) {+ lines.push(` • ${truncate(err.text, 100)}`)+ }+ if (diag.errors.length > 5) {+ lines.push(` ... and ${diag.errors.length - 5} more`)+ }+ lines.push('')+ }++ // Console warnings+ if (diag.warnings.length > 0) {+ lines.push(`⚠️ Console Warnings (${diag.warnings.length}):`)+ for (const warn of diag.warnings.slice(0, 3)) {+ lines.push(` • ${truncate(warn.text, 100)}`)+ }+ if (diag.warnings.length > 3) {+ lines.push(` ... and ${diag.warnings.length - 3} more`)+ }+ lines.push('')+ }++ // Failed requests+ if (diag.failedRequests.length > 0) {+ lines.push(`🌐 Failed Requests (${diag.failedRequests.length}):`)+ for (const req of diag.failedRequests.slice(0, 5)) {+ const urlPath = new URL(req.url).pathname+ lines.push(` • ${req.method} ${truncate(urlPath, 50)} → ${req.status} ${req.statusText || ''}`)+ }+ if (diag.failedRequests.length > 5) {+ lines.push(` ... and ${diag.failedRequests.length - 5} more`)+ }+ lines.push('')+ }++ // Network summary+ lines.push(`📊 Network: ${diag.stats.totalRequests} requests | ${formatBytes(diag.stats.totalSize)} | avg ${Math.round(diag.stats.avgDuration)}ms`)++ // Final status+ const hasIssues = diag.errors.length > 0 || diag.failedRequests.length > 0+ if (hasIssues) {+ lines.push(`⚠️ Page: "${diag.pageTitle}" loaded with issues`)+ } else {+ lines.push(`✅ Page: "${diag.pageTitle}" loaded successfully`)+ }- const browser = new PlaywrightBrowser()- await browser.launch({ headless: false })- await browser.navigate(url)+ return lines.join('\n')+}++// ============================================+// COMMANDS+// ============================================++async function debugUrl(url: string): Promise<void> {+ // Navigate+ await sessionCommand('navigate', { url })- console.log('Browser opened. Press Ctrl+C to close.')+ // Take screenshot+ const timestamp = Date.now()+ const screenshotPath = `/tmp/browse-${timestamp}.png`+ await sessionCommand('screenshot', { path: screenshotPath })- // Keep browser open until interrupted- await new Promise(() => {})+ // Get diagnostics+ const diag = await sessionCommand('diagnostics', {}, 'GET') as Diagnostics++ // Output+ console.log(formatDiagnostics(diag, screenshotPath))}-async function takeScreenshot(url: string, path: string): Promise<void> {- await notify('Taking screenshot with Browse skill')- console.log(`Taking screenshot of ${url}...`)+async function showErrors(): Promise<void> {+ const diag = await sessionCommand('diagnostics', {}, 'GET') as Diagnostics- const browser = new PlaywrightBrowser()- await browser.launch({ headless: true })- await browser.navigate(url)- await browser.waitForNetworkIdle(5000)- await browser.screenshot({ path, fullPage: false })- await browser.close()+ if (diag.errors.length === 0) {+ console.log('✅ No console errors')+ return+ }- console.log(`Screenshot saved to ${path}`)+ console.log(`🔴 Console Errors (${diag.errors.length}):\n`)+ for (const err of diag.errors) {+ const time = new Date(err.timestamp).toLocaleTimeString()+ console.log(`[${time}] ${err.text}\n`)+ }}-async function verifyElement(url: string, selector: string): Promise<void> {- await notify('Verifying page element with Browse skill')- console.log(`Verifying ${selector} on ${url}...`)+async function showWarnings(): Promise<void> {+ const diag = await sessionCommand('diagnostics', {}, 'GET') as Diagnostics++ if (diag.warnings.length === 0) {+ console.log('✅ No console warnings')+ return+ }- const browser = new PlaywrightBrowser()- await browser.launch({ headless: true })- await browser.navigate(url)+ console.log(`⚠️ Console Warnings (${diag.warnings.length}):\n`)+ for (const warn of diag.warnings) {+ const time = new Date(warn.timestamp).toLocaleTimeString()+ console.log(`[${time}] ${warn.text}\n`)+ }+}++async function showConsole(): Promise<void> {+ const logs = await sessionCommand('console', {}, 'GET') as Array<{+ type: string+ text: string+ timestamp: number+ }>++ if (logs.length === 0) {+ console.log('📋 No console output')+ return+ }++ console.log(`📋 Console Output (${logs.length} entries):\n`)+ for (const log of logs) {+ const time = new Date(log.timestamp).toLocaleTimeString()+ const icon = log.type === 'error' ? '🔴' :+ log.type === 'warning' ? '⚠️' :+ log.type === 'info' ? 'ℹ️' : ' '+ console.log(`${icon} [${time}] ${log.text}`)+ }+}++async function showNetwork(): Promise<void> {+ const logs = await sessionCommand('network', {}, 'GET') as Array<{+ type: string+ url: string+ method: string+ status?: number+ duration?: number+ size?: number+ }>++ if (logs.length === 0) {+ console.log('🌐 No network activity')+ return+ }+ // Show only responses (more useful)+ const responses = logs.filter(l => l.type === 'response')++ console.log(`🌐 Network Activity (${responses.length} responses):\n`)+ for (const log of responses.slice(-20)) {+ const urlPath = new URL(log.url).pathname+ const status = log.status || 0+ const icon = status >= 400 ? '❌' : status >= 300 ? '↪️' : '✅'+ const size = log.size ? formatBytes(log.size) : ''+ const duration = log.duration ? `${log.duration}ms` : ''+ console.log(`${icon} ${status} ${log.method} ${truncate(urlPath, 50)} ${size} ${duration}`)+ }+}++async function showFailed(): Promise<void> {+ const diag = await sessionCommand('diagnostics', {}, 'GET') as Diagnostics++ if (diag.failedRequests.length === 0) {+ console.log('✅ No failed requests')+ return+ }++ console.log(`🌐 Failed Requests (${diag.failedRequests.length}):\n`)+ for (const req of diag.failedRequests) {+ console.log(`❌ ${req.status} ${req.method} ${req.url}`)+ }+}++async function takeScreenshot(path?: string): Promise<void> {+ const screenshotPath = path || `/tmp/screenshot-${Date.now()}.png`+ await sessionCommand('screenshot', { path: screenshotPath })+ console.log(`📸 Screenshot: ${screenshotPath}`)+}++async function navigate(url: string): Promise<void> {+ const result = await sessionCommand('navigate', { url })+ console.log(`Navigated to: ${result.url}`)+}++async function click(selector: string): Promise<void> {+ await sessionCommand('click', { selector })+ console.log(`Clicked: ${selector}`)+}++async function fill(selector: string, value: string): Promise<void> {+ await sessionCommand('fill', { selector, value })+ console.log(`Filled: ${selector}`)+}++async function type(selector: string, text: string): Promise<void> {+ await sessionCommand('type', { selector, text })+ console.log(`Typed in: ${selector}`)+}++async function evaluate(script: string): Promise<void> {+ const result = await sessionCommand('evaluate', { script })+ console.log(JSON.stringify(result.result, null, 2))+}++async function showStatus(): Promise<void> {try {- await browser.waitForSelector(selector, { timeout: 10000 })- const text = await browser.getVisibleText(selector)- console.log(`PASS: Element "${selector}" found`)- console.log(`Content: ${text.slice(0, 200)}${text.length > 200 ? '...' : ''}`)- } catch (error) {- console.log(`FAIL: Element "${selector}" not found`)- process.exit(1)- } finally {- await browser.close()+ const state = await getSessionState()+ if (!state) {+ console.log('No session running')+ return+ }++ const session = await sessionCommand('session', {}, 'GET')+ console.log('Browser Session:')+ console.log(` ID: ${session.sessionId}`)+ console.log(` Port: ${session.port}`)+ console.log(` URL: ${session.url || '(none)'}`)+ console.log(` Title: ${session.title || '(none)'}`)+ console.log(` Started: ${session.startedAt}`)+ console.log(` Idle timeout: ${session.idleTimeout}`)+ } catch {+ console.log('Session not responding')}}-async function main(): Promise<void> {- const args = process.argv.slice(2)- const command = args[0]+async function restart(): Promise<void> {+ // Stop if running+ try {+ const state = await getSessionState()+ if (state) {+ await fetch(`http://localhost:${state.port}/stop`, {+ method: 'POST',+ signal: AbortSignal.timeout(2000)+ })+ await Bun.sleep(500)+ }+ } catch {}- if (!command) {- console.log(`-Browse CLI - Browser automation tool+ // Clean up state file+ try {+ const fs = await import('fs/promises')+ await fs.unlink(STATE_FILE)+ } catch {}++ // Start fresh+ await ensureSession()+ console.log('Session restarted')+}++async function stop(): Promise<void> {+ const state = await getSessionState()+ if (!state) {+ console.log('No session running')+ return+ }++ try {+ await fetch(`http://localhost:${state.port}/stop`, {+ method: 'POST',+ signal: AbortSignal.timeout(2000)+ })+ console.log('Session stopped')+ } catch {+ console.log('Session already stopped')+ }+}++async function openUrl(url: string): Promise<void> {+ // Open in system default browser+ const { spawn } = await import('child_process')+ spawn('open', [url], { detached: true, stdio: 'ignore' }).unref()+ console.log(`Opened in default browser: ${url}`)+}++// ============================================+// MAIN+// ============================================++function showHelp(): void {+ console.log(`+Browse CLI v1.2.0 - Debug-First Browser AutomationUsage:- bun run $PAI_DIR/skills/Browser/Tools/Browse.ts <command> [args]+ bun run Browse.ts <url> Navigate with full diagnostics+ bun run Browse.ts errors Show console errors+ bun run Browse.ts warnings Show console warnings+ bun run Browse.ts console Show all console output+ bun run Browse.ts network Show network activity+ bun run Browse.ts failed Show failed requests (4xx, 5xx)+ bun run Browse.ts screenshot [path] Take screenshot of current page+ bun run Browse.ts navigate <url> Navigate without full report+ bun run Browse.ts click <selector> Click element+ bun run Browse.ts fill <selector> <value> Fill input field+ bun run Browse.ts type <selector> <text> Type with delay+ bun run Browse.ts eval "<javascript>" Execute JavaScript+ bun run Browse.ts open <url> Open in default browser+ bun run Browse.ts status Show session info+ bun run Browse.ts restart Restart session (clear state)+ bun run Browse.ts stop Stop session-Commands:- open <url> Open URL in visible browser- screenshot <url> [path] Take screenshot (default: /tmp/screenshot.png)- verify <url> <selector> Verify element exists on page+Session auto-starts on first use. No explicit start needed.Examples:- bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://danielmiessler.com- bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png- bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com "h1"- `)- process.exit(0)+ bun run Browse.ts https://example.com+ bun run Browse.ts errors+ bun run Browse.ts click "#submit"+ bun run Browse.ts fill "#email" "[email protected]"+ `)+}++async function main(): Promise<void> {+ const args = process.argv.slice(2)+ const command = args[0]++ if (!command || command === 'help' || command === '--help' || command === '-h') {+ showHelp()+ return}- switch (command) {- case 'open':- if (!args[1]) {- console.error('Error: URL required')- process.exit(1)- }- await openUrl(args[1])- break+ try {+ // URL detection - if it looks like a URL, treat as debug command+ if (command.startsWith('http://') || command.startsWith('https://') || command.startsWith('localhost')) {+ const url = command.startsWith('localhost') ? `http://${command}` : command+ await debugUrl(url)+ return+ }- case 'screenshot':- if (!args[1]) {- console.error('Error: URL required')- process.exit(1)- }- await takeScreenshot(args[1], args[2] || '/tmp/screenshot.png')- break+ // Named commands+ switch (command) {+ case 'errors':+ await showErrors()+ break- case 'verify':- if (!args[1] || !args[2]) {- console.error('Error: URL and selector required')- process.exit(1)- }- await verifyElement(args[1], args[2])- break+ case 'warnings':+ await showWarnings()+ break++ case 'console':+ await showConsole()+ break++ case 'network':+ await showNetwork()+ break++ case 'failed':+ await showFailed()+ break++ case 'screenshot':+ await takeScreenshot(args[1])+ break++ case 'navigate':+ if (!args[1]) {+ console.error('URL required')+ process.exit(1)+ }+ await navigate(args[1])+ break++ case 'click':+ if (!args[1]) {+ console.error('Selector required')+ process.exit(1)+ }+ await click(args[1])+ break++ case 'fill':+ if (!args[1] || !args[2]) {+ console.error('Selector and value required')+ process.exit(1)+ }+ await fill(args[1], args[2])+ break- default:- console.error(`Unknown command: ${command}`)- process.exit(1)+ case 'type':+ if (!args[1] || !args[2]) {+ console.error('Selector and text required')+ process.exit(1)+ }+ await type(args[1], args[2])+ break++ case 'eval':+ if (!args[1]) {+ console.error('JavaScript code required')+ process.exit(1)+ }+ await evaluate(args[1])+ break++ case 'open':+ if (!args[1]) {+ console.error('URL required')+ process.exit(1)+ }+ await openUrl(args[1])+ break++ case 'status':+ await showStatus()+ break++ case 'restart':+ await restart()+ break++ case 'stop':+ await stop()+ break++ // Legacy session commands (redirect to new interface)+ case 'session':+ const subCmd = args[1]+ if (subCmd === 'start') {+ await ensureSession()+ console.log('Session started (auto-starts on any command now)')+ } else if (subCmd === 'stop') {+ await stop()+ } else if (subCmd === 'status') {+ await showStatus()+ } else {+ console.log('Session commands deprecated. Session auto-starts on first use.')+ console.log('Use: Browse.ts <url> | errors | network | failed | etc.')+ }+ break++ default:+ console.error(`Unknown command: ${command}`)+ console.log('Run with --help for usage')+ process.exit(1)+ }+ } catch (err: any) {+ console.error(`Error: ${err.message}`)+ process.exit(1)}}-main().catch(err => {- console.error('Error:', err.message)- process.exit(1)-})+main()diff --git a/Packs/kai-browser-skill/Tools/BrowserSession.ts b/Packs/kai-browser-skill/Tools/BrowserSession.tsnew file mode 100644index 00000000..b62fd705--- /dev/null+++ b/Packs/kai-browser-skill/Tools/BrowserSession.ts@@ -0,0 +1,445 @@+#!/usr/bin/env bun+/**+ * Browser Session Server v1.2.0 - Debug-First Persistent Browser+ *+ * Persistent Playwright browser with ALWAYS-ON event capture.+ * Console logs, network requests, and errors captured from launch.+ *+ * Usage:+ * # Started automatically by Browse.ts (not directly)+ * BROWSER_PORT=9222 bun run BrowserSession.ts+ *+ * New API (v1.2.0):+ * GET /diagnostics - Full diagnostic summary (errors, warnings, failed requests)+ * GET /console - All console logs+ * GET /network - All network activity+ *+ * Standard API:+ * GET /health - Server health check+ * GET /session - Current session info+ * POST /navigate - Navigate to URL (clears logs for fresh page)+ * POST /click - Click element+ * POST /fill - Fill input+ * POST /screenshot - Take screenshot+ * GET /text - Get visible text+ * POST /evaluate - Run JavaScript+ * POST /stop - Stop server+ */++import { PlaywrightBrowser } from '../src/index.ts'++const CONFIG = {+ port: parseInt(process.env.BROWSER_PORT || '9222'),+ headless: process.env.BROWSER_HEADLESS === 'true',+ viewport: {+ width: parseInt(process.env.BROWSER_WIDTH || '1920'),+ height: parseInt(process.env.BROWSER_HEIGHT || '1080')+ },+ stateFile: '/tmp/browser-session.json',+ idleTimeout: 30 * 60 * 1000 // 30 minutes+}++const browser = new PlaywrightBrowser()+const sessionId = crypto.randomUUID().slice(0, 8)+const startedAt = new Date().toISOString()+let lastActivity = Date.now()++// ============================================+// STATE MANAGEMENT+// ============================================++async function saveState(): Promise<void> {+ try {+ const state = {+ pid: process.pid,+ port: CONFIG.port,+ sessionId,+ startedAt,+ headless: CONFIG.headless,+ url: browser.getUrl()+ }+ await Bun.write(CONFIG.stateFile, JSON.stringify(state, null, 2))+ } catch (error) {+ console.error('Failed to save state:', error)+ }+}++async function cleanup(): Promise<void> {+ console.log('\nShutting down browser session...')+ try {+ await browser.close()+ } catch {}+ try {+ const file = Bun.file(CONFIG.stateFile)+ if (await file.exists()) {+ await Bun.write(CONFIG.stateFile, '')+ const fs = await import('fs/promises')+ await fs.unlink(CONFIG.stateFile)+ }+ } catch {}+ console.log('Session closed.')+ process.exit(0)+}++// ============================================+// IDLE TIMEOUT+// ============================================++function checkIdleTimeout(): void {+ const idle = Date.now() - lastActivity+ if (idle > CONFIG.idleTimeout) {+ console.log(`Idle timeout (${Math.round(idle / 60000)} minutes) - shutting down`)+ cleanup()+ }+}++// Check every minute+setInterval(checkIdleTimeout, 60 * 1000)++// ============================================+// RESPONSE HELPERS+// ============================================++function json(data: any, status = 200): Response {+ return new Response(JSON.stringify(data), {+ status,+ headers: {+ 'Content-Type': 'application/json',+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',+ 'Access-Control-Allow-Headers': 'Content-Type'+ }+ })+}++function success(data?: any): Response {+ return json({ success: true, data })+}++function error(message: string, status = 500): Response {+ return json({ success: false, error: message }, status)+}++// ============================================+// LAUNCH BROWSER+// ============================================++console.log('Starting browser session...')+console.log(` Port: ${CONFIG.port}`)+console.log(` Headless: ${CONFIG.headless}`)+console.log(` Viewport: ${CONFIG.viewport.width}x${CONFIG.viewport.height}`)+console.log(` Idle timeout: ${CONFIG.idleTimeout / 60000} minutes`)++await browser.launch({+ headless: CONFIG.headless,+ viewport: CONFIG.viewport+})++// ============================================+// HTTP SERVER+// ============================================++const server = Bun.serve({+ port: CONFIG.port,++ async fetch(req) {+ const url = new URL(req.url)+ const method = req.method++ // Update activity timestamp on every request+ lastActivity = Date.now()++ // CORS preflight+ if (method === 'OPTIONS') {+ return new Response(null, {+ headers: {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',+ 'Access-Control-Allow-Headers': 'Content-Type'+ }+ })+ }++ try {+ // ========================================+ // DIAGNOSTIC ENDPOINTS (NEW in v1.2.0)+ // ========================================++ // Full diagnostics - errors, warnings, failed requests, stats+ if (url.pathname === '/diagnostics' && method === 'GET') {+ const allLogs = browser.getConsoleLogs()+ const errors = allLogs.filter(l => l.type === 'error')+ const warnings = allLogs.filter(l => l.type === 'warning')++ const networkLogs = browser.getNetworkLogs({ type: 'response' })+ const failedRequests = networkLogs+ .filter(l => l.status && l.status >= 400)+ .map(l => ({+ url: l.url,+ method: l.method,+ status: l.status!,+ statusText: l.statusText+ }))++ const stats = browser.getNetworkStats()++ return success({+ errors,+ warnings,+ failedRequests,+ stats,+ pageTitle: await browser.getTitle(),+ pageUrl: browser.getUrl()+ })+ }++ // Console logs+ if (url.pathname === '/console' && method === 'GET') {+ const type = url.searchParams.get('type') as any+ const limit = parseInt(url.searchParams.get('limit') || '100')+ const logs = browser.getConsoleLogs({ type: type || undefined, limit })+ return success(logs)+ }++ // Network logs+ if (url.pathname === '/network' && method === 'GET') {+ const limit = parseInt(url.searchParams.get('limit') || '100')+ const logs = browser.getNetworkLogs({ limit })+ return success(logs)+ }++ // ========================================+ // STANDARD ENDPOINTS+ // ========================================++ // Health check+ if (url.pathname === '/health' && method === 'GET') {+ return success({+ status: 'ok',+ sessionId,+ uptime: Date.now() - new Date(startedAt).getTime()+ })+ }++ // Session info+ if (url.pathname === '/session' && method === 'GET') {+ return success({+ sessionId,+ startedAt,+ port: CONFIG.port,+ headless: CONFIG.headless,+ url: browser.getUrl(),+ title: await browser.getTitle(),+ idleTimeout: `${CONFIG.idleTimeout / 60000} minutes`,+ lastActivity: new Date(lastActivity).toISOString()+ })+ }++ // Navigate - CLEARS LOGS for fresh page diagnostics+ if (url.pathname === '/navigate' && method === 'POST') {+ const body = await req.json()+ if (!body.url) return error('url required', 400)++ // Clear logs before navigating for clean diagnostic slate+ browser.getConsoleLogs({ clear: true })+ browser.clearNetworkLogs()++ await browser.navigate(body.url, { waitUntil: body.waitUntil || 'networkidle' })+ await saveState()++ return success({+ url: browser.getUrl(),+ title: await browser.getTitle()+ })+ }++ // Click+ if (url.pathname === '/click' && method === 'POST') {+ const body = await req.json()+ if (!body.selector) return error('selector required', 400)+ await browser.click(body.selector, { timeout: body.timeout })+ return success({ clicked: body.selector })+ }++ // Fill+ if (url.pathname === '/fill' && method === 'POST') {+ const body = await req.json()+ if (!body.selector || body.value === undefined) return error('selector and value required', 400)+ await browser.fill(body.selector, body.value)+ return success({ filled: body.selector })+ }++ // Type (character by character)+ if (url.pathname === '/type' && method === 'POST') {+ const body = await req.json()+ if (!body.selector || !body.text) return error('selector and text required', 400)+ await browser.type(body.selector, body.text, body.delay)+ return success({ typed: body.selector })+ }++ // Screenshot+ if (url.pathname === '/screenshot' && method === 'POST') {+ const body = await req.json()+ const path = body.path || '/tmp/screenshot.png'+ await browser.screenshot({+ path,+ fullPage: body.fullPage || false,+ selector: body.selector+ })+ return success({ path })+ }++ // Get visible text+ if (url.pathname === '/text' && method === 'GET') {+ const selector = url.searchParams.get('selector') || undefined+ const text = await browser.getVisibleText(selector)+ return success({ text })+ }++ // Get HTML+ if (url.pathname === '/html' && method === 'GET') {+ const selector = url.searchParams.get('selector') || undefined+ const html = await browser.getVisibleHtml({ selector })+ return success({ html })+ }++ // Evaluate JavaScript+ if (url.pathname === '/evaluate' && method === 'POST') {+ const body = await req.json()+ if (!body.script) return error('script required', 400)+ const result = await browser.evaluate(body.script)+ return success({ result })+ }++ // Wait for selector+ if (url.pathname === '/wait' && method === 'POST') {+ const body = await req.json()+ if (!body.selector) return error('selector required', 400)+ await browser.waitForSelector(body.selector, {+ state: body.state,+ timeout: body.timeout+ })+ return success({ found: body.selector })+ }++ // Wait for text+ if (url.pathname === '/wait-text' && method === 'POST') {+ const body = await req.json()+ if (!body.text) return error('text required', 400)+ await browser.waitForText(body.text, {+ state: body.state,+ timeout: body.timeout+ })+ return success({ found: body.text })+ }++ // Hover+ if (url.pathname === '/hover' && method === 'POST') {+ const body = await req.json()+ if (!body.selector) return error('selector required', 400)+ await browser.hover(body.selector)+ return success({ hovered: body.selector })+ }++ // Press key+ if (url.pathname === '/press' && method === 'POST') {+ const body = await req.json()+ if (!body.key) return error('key required', 400)+ await browser.pressKey(body.key, body.selector)+ return success({ pressed: body.key })+ }++ // Select dropdown+ if (url.pathname === '/select' && method === 'POST') {+ const body = await req.json()+ if (!body.selector || !body.value) return error('selector and value required', 400)+ await browser.select(body.selector, body.value)+ return success({ selected: body.value })+ }++ // Tabs - list+ if (url.pathname === '/tabs' && method === 'GET') {+ const tabs = browser.getTabs()+ return success({ tabs })+ }++ // Tabs - new+ if (url.pathname === '/tabs' && method === 'POST') {+ const body = await req.json()+ await browser.newTab(body.url)+ return success({ created: true, url: body.url })+ }++ // Tabs - close+ if (url.pathname.startsWith('/tabs/') && method === 'DELETE') {+ const index = parseInt(url.pathname.split('/')[2])+ if (isNaN(index)) return error('invalid tab index', 400)+ await browser.switchTab(index)+ await browser.closeTab()+ return success({ closed: index })+ }++ // Tabs - switch+ if (url.pathname.startsWith('/tabs/') && method === 'POST') {+ const index = parseInt(url.pathname.split('/')[2])+ if (isNaN(index)) return error('invalid tab index', 400)+ await browser.switchTab(index)+ return success({ switched: index })+ }++ // Reload+ if (url.pathname === '/reload' && method === 'POST') {+ await browser.reload()+ return success({ reloaded: true })+ }++ // Go back+ if (url.pathname === '/back' && method === 'POST') {+ await browser.goBack()+ return success({ back: true })+ }++ // Go forward+ if (url.pathname === '/forward' && method === 'POST') {+ await browser.goForward()+ return success({ forward: true })+ }++ // Resize viewport+ if (url.pathname === '/resize' && method === 'POST') {+ const body = await req.json()+ if (!body.width || !body.height) return error('width and height required', 400)+ await browser.resize(body.width, body.height)+ return success({ width: body.width, height: body.height })+ }++ // Stop server+ if (url.pathname === '/stop' && method === 'POST') {+ setTimeout(() => cleanup(), 100)+ return success({ stopping: true })+ }++ return error('Not found', 404)++ } catch (err: any) {+ console.error('Request error:', err.message)+ return error(err.message)+ }+ }+})++await saveState()+console.log(`\nBrowser session started!`)+console.log(` Session ID: ${sessionId}`)+console.log(` URL: http://localhost:${CONFIG.port}`)+console.log(` Diagnostics: http://localhost:${CONFIG.port}/diagnostics`)+console.log(`\nSession will auto-close after ${CONFIG.idleTimeout / 60000} minutes of inactivity.`)+console.log(`Press Ctrl+C to stop manually.`)++// Cleanup handlers+process.on('SIGTERM', cleanup)+process.on('SIGINT', cleanup)+process.on('uncaughtException', (err) => {+ console.error('Uncaught exception:', err)+ cleanup()+})diff --git a/Packs/kai-browser-skill/VERIFY.md b/Packs/kai-browser-skill/VERIFY.mdindex 55d2106d..ccb63c0c 100644--- a/Packs/kai-browser-skill/VERIFY.md+++ b/Packs/kai-browser-skill/VERIFY.md@@ -1,36 +1,52 @@-# Kai Browser Skill - Verification+# Browser Skill v1.2.0 - Verification**This verification guide is for AI agents to confirm successful installation.**----## 🚨 MANDATORY COMPLETION CHECKLIST+## MANDATORY COMPLETION CHECKLIST**AI Agents: You MUST verify ALL items below pass before reporting installation success.**+### Core Installation (Checks 1-8)+| # | Check | Command | Pass Criteria | Status ||---|-------|---------|---------------|--------|-| 1 | Directory exists | `ls -la $PAI_DIR/skills/Browser/` | Directory with files shown | ⬜ |-| 2 | Core files present | `ls $PAI_DIR/skills/Browser/{index.ts,SKILL.md,package.json}` | All 3 files exist | ⬜ |-| 3 | Dependencies installed | `cd $PAI_DIR/skills/Browser && bun pm ls \| grep playwright` | playwright listed | ⬜ |-| 4 | Playwright browsers | `bunx playwright install chromium --dry-run 2>&1 \| head -5` | Shows chromium installed OR installs it | ⬜ |-| 5 | API import works | `cd $PAI_DIR/skills/Browser && bun -e "import './index.ts'"` | No error | ⬜ |-| 6 | Page load test | `bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://example.com` | Shows "Page loaded" | ⬜ |-| 7 | Screenshot test | `bun $PAI_DIR/skills/Browser/examples/screenshot.ts https://example.com /tmp/browser-verify.png && ls -la /tmp/browser-verify.png` | File size > 0 | ⬜ |-| 8 | CLI tool works | `bun run $PAI_DIR/skills/Browser/Tools/Browse.ts 2>&1 \| head -5` | Shows usage/help | ⬜ |+| 1 | Directory exists | `ls -la $PAI_DIR/skills/Browser/` | Directory with files shown | |+| 2 | Core files present | `ls $PAI_DIR/skills/Browser/{src/index.ts,SKILL.md,package.json}` | All 3 files exist | |+| 3 | Tools present | `ls $PAI_DIR/skills/Browser/Tools/{Browse.ts,BrowserSession.ts}` | Both tools exist | |+| 4 | Dependencies installed | `cd $PAI_DIR/skills/Browser && bun pm ls \| grep playwright` | playwright listed | |+| 5 | Playwright browsers | `bunx playwright install chromium --dry-run 2>&1 \| head -5` | Shows chromium installed OR installs it | |+| 6 | API import works | `cd $PAI_DIR/skills/Browser && bun -e "import './src/index.ts'"` | No error | |+| 7 | CLI help works | `bun run $PAI_DIR/skills/Browser/Tools/Browse.ts --help 2>&1 \| head -10` | Shows v1.2.0 usage | |+| 8 | Examples exist | `ls $PAI_DIR/skills/Browser/examples/*.ts` | At least 2 example files | |++### Session Management (Checks 9-15)++| # | Check | Command | Pass Criteria | Status |+|---|-------|---------|---------------|--------|+| 9 | Session auto-start | `bun run $PAI_DIR/skills/Browser/Tools/Browse.ts https://example.com 2>&1` | Shows diagnostics output | |+| 10 | Screenshot created | `ls /tmp/browse-*.png 2>/dev/null \| head -1` | File exists | |+| 11 | Session status | `bun run $PAI_DIR/skills/Browser/Tools/Browse.ts status` | Shows session info | |+| 12 | Health endpoint | `curl -s http://localhost:9222/health 2>/dev/null \| head -1` | Returns JSON with status:ok | |+| 13 | Console command | `bun run $PAI_DIR/skills/Browser/Tools/Browse.ts console` | Shows console output or "No console output" | |+| 14 | Network command | `bun run $PAI_DIR/skills/Browser/Tools/Browse.ts network` | Shows network or "No network activity" | |+| 15 | Session stop | `bun run $PAI_DIR/skills/Browser/Tools/Browse.ts stop` | Shows "Session stopped" | |**Completion Requirements:**-- ALL 8 checks must show ✅+- ALL 15 checks must pass- If ANY check fails, troubleshoot before proceeding- Report exact error messages for failed checks- DO NOT report success until all checks pass**After all checks pass, mark installation complete:**```-✅ INSTALLATION VERIFIED: All 8 checks passed- - Browser skill installed at $PAI_DIR/skills/Browser/+INSTALLATION VERIFIED: All 15 checks passed+ - Browser skill v1.2.0 installed at $PAI_DIR/skills/Browser/- Playwright chromium browser ready- - API, examples, and CLI all functional+ - Session auto-start working+ - Diagnostic endpoints functional+ - API, examples, and CLI all operational```---@@ -39,66 +55,63 @@Run these commands to verify the Browser skill is working:-### 1. Check Dependencies+### 1. Check Version```bash-cd $PAI_DIR/skills/Browser-bun install --dry-run+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts --help | head -3```-Expected: Shows playwright as installed+Expected: Shows "Browse CLI v1.2.0"-### 2. Verify Page Load+### 2. Test Debug-First Navigation```bash-bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://example.com+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts https://example.com```Expected output:```-Navigating to https://example.com...-Page loaded: Example Domain-Title: Example Domain-Console errors: 0+📸 Screenshot: /tmp/browse-TIMESTAMP.png++📊 Network: X requests | Y KB | avg Zms+✅ Page: "Example Domain" loaded successfully```-### 3. Take Screenshot+### 3. Verify Session Running```bash-bun $PAI_DIR/skills/Browser/examples/screenshot.ts https://example.com /tmp/browser-test.png-ls -la /tmp/browser-test.png+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts status```-Expected: File exists, size > 0+Expected:+```+Browser Session:+ ID: xxxxxxxx+ Port: 9222+ URL: https://example.com+ ...+```-### 4. Test CLI Tool+### 4. Test Diagnostic Commands```bash-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts-```--Expected: Shows help text with available commands+# Console output+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts console-### 5. CLI Screenshot+# Network activity+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts network-```bash-bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/cli-test.png-ls -la /tmp/cli-test.png+# Failed requests+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts failed```-Expected: File exists, size > 0-----+### 5. Stop Session-## Verification Checklist+```bash+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts stop+```-| Test | Command | Expected |-|------|---------|----------|-| Dependencies | `cd $PAI_DIR/skills/Browser && bun pm ls` | Shows playwright |-| Page load | `bun examples/verify-page.ts https://example.com` | "Page loaded" |-| Screenshot | `bun examples/screenshot.ts https://example.com /tmp/test.png` | File created |-| CLI help | `bun run Tools/Browse.ts` | Shows usage |-| CLI screenshot | `bun run Tools/Browse.ts screenshot https://example.com /tmp/cli.png` | File created |+Expected: "Session stopped"---@@ -117,12 +130,23 @@ bun installbunx playwright install chromium```-### Screenshot is blank+### Session won't start-The page may need time to load:-```typescript-await browser.waitForNetworkIdle()-await browser.screenshot({ path: 'shot.png' })+Check if port 9222 is already in use:+```bash+lsof -i :9222+```++Kill the process if needed:+```bash+kill $(lsof -t -i :9222)+```++### Session state file issue++Clean up orphan state:+```bash+rm /tmp/browser-session.json```---@@ -130,10 +154,10 @@ await browser.screenshot({ path: 'shot.png' })## Full Test Script```typescript-import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/src/index.ts'async function verifyBrowserSkill() {- console.log('Testing Browser skill...')+ console.log('Testing Browser skill v1.2.0...')const browser = new PlaywrightBrowser()@@ -152,13 +176,23 @@ async function verifyBrowserSkill() {const title = await browser.getTitle()console.log(` Title: ${title}`)- // Test 4: Screenshot- console.log('4. Taking screenshot...')+ // Test 4: Console logs+ console.log('4. Getting console logs...')+ const logs = browser.getConsoleLogs()+ console.log(` Log entries: ${logs.length}`)++ // Test 5: Network stats+ console.log('5. Getting network stats...')+ const stats = browser.getNetworkStats()+ console.log(` Requests: ${stats.totalRequests}`)++ // Test 6: Screenshot+ console.log('6. Taking screenshot...')await browser.screenshot({ path: '/tmp/verify-test.png' })console.log(' OK')- // Test 5: Close- console.log('5. Closing browser...')+ // Test 7: Close+ console.log('7. Closing browser...')await browser.close()console.log(' OK')diff --git a/Packs/kai-browser-skill/package.json b/Packs/kai-browser-skill/package.jsonindex 3d13187f..c7e25bec 100644--- a/Packs/kai-browser-skill/package.json+++ b/Packs/kai-browser-skill/package.json@@ -1,9 +1,9 @@{- "name": "@kai/playwright",- "version": "1.0.0",- "description": "Code-first Playwright wrapper replacing token-heavy MCP",+ "name": "@pai/browser-skill",+ "version": "1.2.0",+ "description": "Debug-first browser automation with always-on visibility","type": "module",- "main": "index.ts",+ "main": "src/index.ts","scripts": {"test": "bun test"},diff --git a/Tools/InstallTemplate.md b/Tools/InstallTemplate.mdnew file mode 100644index 00000000..8a2dc178--- /dev/null+++ b/Tools/InstallTemplate.md@@ -0,0 +1,334 @@+# PAI Pack Installation Template++**Template for creating wizard-style INSTALL.md files for PAI packs.**++Use this template when creating new packs. The wizard-style approach uses Claude Code's native tools to guide users through installation interactively.++---++## Template Structure++```markdown+# [Pack Name] v[X.Y.Z] - Installation Guide++**This guide is designed for AI agents installing this pack into a user's infrastructure.**++---++## AI Agent Instructions++**This is a wizard-style installation.** Use Claude Code's native tools to guide the user through installation:++1. **AskUserQuestion** - For user decisions and confirmations+2. **TodoWrite** - For progress tracking+3. **Bash/Read/Write** - For actual installation+4. **VERIFY.md** - For final validation++### Welcome Message++Before starting, greet the user:+\```+"I'm installing [pack-name] v[X.Y.Z] - [one-line description].++Let me analyze your system and guide you through installation."+\```++---++## Phase 1: System Analysis++**Execute this analysis BEFORE any file operations.**++### 1.1 Run These Commands++\```bash+# Check prerequisites+which [prerequisite] && [prerequisite] --version++# Check for existing installation+ls -la $PAI_DIR/skills/[SkillName]/ 2>/dev/null || echo "No existing [SkillName] skill"++# Check for dependencies+# ... pack-specific checks+\```++### 1.2 Present Findings++Tell the user what you found:+\```+"Here's what I found on your system:+- [Prerequisite]: [installed vX.X / NOT INSTALLED]+- Existing [pack] skill: [Yes at path / No]+- Dependencies: [Status]"+\```++---++## Phase 2: User Questions++**Use AskUserQuestion tool at each decision point.**++### Question 1: Prerequisites (if missing)++**Only ask if [prerequisite] is NOT installed:**++\```json+{+ "header": "[Short Label]",+ "question": "[Question about missing prerequisite]?",+ "multiSelect": false,+ "options": [+ {"label": "Yes, install [X] (Recommended)", "description": "[What this does]"},+ {"label": "Skip - I'll install manually", "description": "[Consequence of skipping]"}+ ]+}+\```++### Question 2: Conflict Resolution (if existing found)++**Only ask if existing installation detected:**++\```json+{+ "header": "Conflict",+ "question": "Existing [X] detected at [path]. How should I proceed?",+ "multiSelect": false,+ "options": [+ {"label": "Backup and Replace (Recommended)", "description": "Creates timestamped backup, then installs new version"},+ {"label": "Replace Without Backup", "description": "Overwrites existing without backup"},+ {"label": "Abort Installation", "description": "Cancel installation, keep existing"}+ ]+}+\```++### Question 3: Optional Features++**Only ask if pack has optional features:**++\```json+{+ "header": "Features",+ "question": "Which optional features should I enable?",+ "multiSelect": true,+ "options": [+ {"label": "Feature A (Recommended)", "description": "[What it does]"},+ {"label": "Feature B", "description": "[What it does]"},+ {"label": "Feature C", "description": "[What it does]"}+ ]+}+\```++### Question 4: Final Confirmation++\```json+{+ "header": "Install",+ "question": "Ready to install [pack-name] v[X.Y.Z]?",+ "multiSelect": false,+ "options": [+ {"label": "Yes, install now (Recommended)", "description": "Proceeds with installation using choices above"},+ {"label": "Show me what will change", "description": "Lists all files that will be created/modified"},+ {"label": "Cancel", "description": "Abort installation"}+ ]+}+\```++---++## Phase 3: Backup (If Needed)++**Only execute if user chose "Backup and Replace":**++\```bash+BACKUP_DIR="$PAI_DIR/Backups/[pack-name]-$(date +%Y%m%d-%H%M%S)"+mkdir -p "$BACKUP_DIR"+[ -d "$PAI_DIR/skills/[SkillName]" ] && cp -r "$PAI_DIR/skills/[SkillName]" "$BACKUP_DIR/"+echo "Backup created at: $BACKUP_DIR"+\```++---++## Phase 4: Installation++**Create a TodoWrite list to track progress:**++\```json+{+ "todos": [+ {"content": "Create skill directory structure", "status": "pending", "activeForm": "Creating directory structure"},+ {"content": "Copy skill files", "status": "pending", "activeForm": "Copying skill files"},+ {"content": "Install dependencies", "status": "pending", "activeForm": "Installing dependencies"},+ {"content": "[Pack-specific step]", "status": "pending", "activeForm": "[Doing pack-specific step]"},+ {"content": "Run verification", "status": "pending", "activeForm": "Running verification"}+ ]+}+\```++### 4.1 Create Skill Directory++**Mark todo "Create skill directory structure" as in_progress.**++\```bash+mkdir -p $PAI_DIR/skills/[SkillName]+mkdir -p $PAI_DIR/skills/[SkillName]/src+# ... additional directories+\```++**Mark todo as completed.**++### 4.2 Copy Skill Files++**Mark todo "Copy skill files" as in_progress.**++\```bash+# Copy from pack directory to skill directory+cp src/index.ts $PAI_DIR/skills/[SkillName]/src/+cp package.json $PAI_DIR/skills/[SkillName]/+cp SKILL.md $PAI_DIR/skills/[SkillName]/+# ... additional files+\```++**Mark todo as completed.**++### 4.3 Install Dependencies++**Mark todo "Install dependencies" as in_progress.**++\```bash+cd $PAI_DIR/skills/[SkillName]+bun install+\```++**Mark todo as completed.**++### 4.4 [Pack-Specific Step]++**Mark todo "[Pack-specific step]" as in_progress.**++\```bash+# Pack-specific installation commands+\```++**Mark todo as completed.**++---++## Phase 5: Verification++**Mark todo "Run verification" as in_progress.**++**Execute all checks from VERIFY.md.**++Quick verification:+\```bash+# Key verification commands from VERIFY.md+\```++**Mark todo as completed when all VERIFY.md checks pass.**++---++## Success/Failure Messages++### On Success++\```+"[Pack name] v[X.Y.Z] installed successfully!++What's available:+- [Key feature 1]+- [Key feature 2]+- [Key feature 3]++Try it: [example command]"+\```++### On Failure++\```+"Installation encountered issues. Here's what to check:++1. [Common issue 1]+2. [Common issue 2]+3. Check VERIFY.md for the specific failing check++Need help? See Troubleshooting section below."+\```++---++## Troubleshooting++### "[Common error message 1]"++\```bash+# Fix command+\```++### "[Common error message 2]"++\```bash+# Fix command+\```++---++## What's Included++| File | Purpose |+|------|---------|+| `src/index.ts` | [Description] |+| `SKILL.md` | Skill definition for Claude Code |+| ... | ... |++---++## Usage++### From Claude Code++\```+[Natural language example]+\```++### From CLI++\```bash+[CLI command example]+\```+```++---++## Key Principles++1. **Wizard-style** - Guide users interactively, don't dump commands+2. **AskUserQuestion** - At every decision point, not just "install Y/N?"+3. **TodoWrite** - Track progress so users see what's happening+4. **Conditional questions** - Only ask about missing prerequisites or conflicts+5. **Clear success/failure** - Tell users exactly what happened+6. **VERIFY.md integration** - Always run verification checks++---++## Question Design Guidelines++### Headers (max 12 chars)+- "Runtime" for prerequisite questions+- "Conflict" for existing installation+- "Features" for optional features+- "Install" for final confirmation++### Options+- Always include "(Recommended)" on the best choice+- 2-4 options per question (user can always type "Other")+- Descriptions explain consequences, not just what it does++### Conditional Logic+- Questions 1-3 are conditional (only ask if relevant)+- Question 4 (final confirmation) is always asked+- Skip entire phases if not applicable++---++*This template is part of the PAI Pack system. See Packs/README.md for full documentation.*