⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
feat: Add kai-browser-skill pack - code-first browser automation
Daniel Miessler39257601a2d9
diff --git a/Packs/README.md b/Packs/README.mdindex f69d8122..36c7921c 100644--- a/Packs/README.md+++ b/Packs/README.md@@ -146,6 +146,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 |---@@ -161,7 +162,8 @@ Packs have dependencies. Install in this order:5. kai-voice-system ← Depends on hooks, core-install6. kai-agents-skill ← Depends on core-install, optional voice-system7. kai-art-skill ← Depends on core-install-8. kai-observability-server ← Optional, depends on hooks+8. kai-browser-skill ← Optional, standalone (only needs Bun + Playwright)+9. kai-observability-server ← Optional, depends on hooks```**Or install the complete [Kai Bundle](../Bundles/Kai/)** which handles ordering automatically.@@ -222,6 +224,7 @@ See [.env.example](../.env.example) for the complete list of supported variables| **Delegation** | Agent orchestration and parallel execution | Agents Skill || **Creativity** | Visual and creative content generation | Art Skill || **Methodology** | Prompt engineering and meta-prompting | Prompting Skill |+| **Automation** | Browser automation and web verification | Browser Skill |---diff --git a/Packs/kai-browser-skill.md b/Packs/kai-browser-skill.mdnew file mode 100644index 00000000..a49cde78--- /dev/null+++ b/Packs/kai-browser-skill.md@@ -0,0 +1,365 @@+---+name: Kai Browser Skill+pack-id: danielmiessler-kai-browser-skill-v1.0.0+version: 1.0.0+author: danielmiessler+description: Code-first browser automation replacing Playwright MCP with 99% token savings. Navigate, screenshot, interact, and verify web pages.+type: skill+purpose-type: [browser-automation, verification, testing]+platform: claude-code+dependencies: []+keywords: [browser, playwright, automation, screenshot, web-testing, verification, file-based-mcp]+---++<p align="center">+ <img src="icons/kai-browser-skill.png" alt="Kai Browser Skill" width="256">+</p>++# Kai Browser Skill (kai-browser-skill)++> Code-first browser automation with 99% token savings over Playwright MCP++## Installation Prompt++You are receiving a PAI Pack - a modular upgrade for AI agent systems.++**What is PAI?** See: [PAI Project Overview](../README.md#what-is-pai)++**What is a Pack?** See: [Pack System](../README.md#pack-system)++---++### 🚨 CRITICAL: AI Agent Installation Instructions++**You are an AI agent installing this pack. Follow these steps EXACTLY:**++1. **Step 0 - Pre-Installation Analysis** (MANDATORY)+ - Detect the user's operating system and environment+ - Check for existing Browser/Playwright/Browse skills+ - If conflicts found, ASK the user before proceeding+ - Create backup if replacing existing installation++2. **Copy ALL Files Exactly**+ - DO NOT simplify, summarize, or "improve" any files+ - Copy the EXACT content of each file+ - Preserve all directory structure++3. **Verify Installation**+ - Run ALL 8 verification checks from VERIFY.md+ - DO NOT report success until ALL checks pass+ - If any check fails, troubleshoot before proceeding++4. **Report Results**+ - Show user which checks passed/failed+ - Confirm final installation status++**Anti-Simplification Directive:** This pack contains carefully crafted code and documentation. Do not attempt to simplify, condense, or "improve" any files during installation. Copy them EXACTLY as provided.++---++This Pack adds browser automation capabilities to your AI infrastructure. The Kai Browser Skill provides:++- **Navigation**: Go to URLs, navigate history, reload pages+- **Screenshots**: Capture full pages or specific elements+- **Interaction**: Click, fill forms, select dropdowns, type text+- **Verification**: Wait for elements, check content, validate pages+- **Extraction**: Get visible text, HTML, accessibility tree++**Core principle:** Replace token-heavy MCPs with code-first execution.++The Playwright MCP loads ~13,700 tokens at startup whether you use it or not. This skill loads ~50-200 tokens per operation, only when needed. That's 99%+ token savings.++Please follow the installation instructions below to integrate this Pack into your infrastructure.++**Quick Navigation:** [What's Included](#whats-included) | [The Problem](#the-concept-andor-problem) | [The Solution](#the-solution) | [Installation](#installation) | [Troubleshooting](#troubleshooting) | [Configuration](#configuration) | [Changelog](#changelog)++---++## What's Included++| Component | File | Purpose |+|-----------|------|---------|+| API Wrapper | `src/index.ts` | PlaywrightBrowser class with full API |+| CLI Tool | `Tools/Browse.ts` | Command-line browser operations |+| Skill Definition | `SKILL.md` | Claude Code skill integration |+| Screenshot Workflow | `Workflows/Screenshot.md` | Screenshot capture workflow |+| Verify Workflow | `Workflows/VerifyPage.md` | Page verification workflow |+| Interact Workflow | `Workflows/Interact.md` | Form interaction workflow |+| Extract Workflow | `Workflows/Extract.md` | Content extraction workflow |+| Example Scripts | `examples/*.ts` | Ready-to-run examples |++**Summary:**+- **Files created:** 10++- **Workflows:** 4+- **Dependencies:** playwright++---++## The Concept and/or Problem++AI agents need browser automation for:++- Verifying web deployments actually work+- Taking screenshots for documentation+- Interacting with web forms+- Extracting content from pages+- Testing user interfaces++**The MCP Problem:**++The Playwright MCP (Model Context Protocol) is the standard approach:++```json+{+ "mcpServers": {+ "playwright": {+ "command": "npx",+ "args": ["@playwright/mcp@latest"]+ }+ }+}+```++But it has significant overhead:+- **~13,700 tokens loaded at startup** - whether you use it or not+- **Limited to 21 predefined tools** - can't access full Playwright API+- **MCP protocol overhead** - extra latency on every operation++**The Token Cost:**++Even if you only take one screenshot per session:+- MCP: 13,700 tokens (loaded at start)+- Actual operation: ~100 tokens+- **Total: 13,800 tokens**++For a session with 5 screenshots:+- MCP: Still 13,700 tokens+- Operations: 5 x ~100 = 500 tokens+- **Total: 14,200 tokens**++---++## The Solution++**File-based MCP** - code-first execution with on-demand loading:++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch()+await browser.navigate('https://example.com')+await browser.screenshot({ path: 'screenshot.png' })+await browser.close()+```++**Benefits:**++| Metric | Playwright MCP | Browser Skill |+|--------|----------------|---------------|+| Startup cost | ~13,700 tokens | 0 tokens |+| Per-operation | ~0 | ~50-200 tokens |+| API access | 21 tools | Full Playwright API |+| Latency | MCP overhead | Direct execution |++**Token Savings Example:**++5 screenshots per session:+- MCP: 13,700 tokens+- Browser Skill: 5 x ~100 = 500 tokens+- **Savings: 96%**++---++## Installation++### Prerequisites++- Bun runtime: `curl -fsSL https://bun.sh/install | bash`+- macOS, Linux, or Windows++### Step 1: Create Directory++```bash+mkdir -p $PAI_DIR/skills/Browser+cd $PAI_DIR/skills/Browser+```++### Step 2: Copy Files++From the `kai-browser-skill/` pack directory:++```bash+cp src/index.ts $PAI_DIR/skills/Browser/+cp package.json $PAI_DIR/skills/Browser/+cp tsconfig.json $PAI_DIR/skills/Browser/+cp SKILL.md $PAI_DIR/skills/Browser/++mkdir -p $PAI_DIR/skills/Browser/Tools+mkdir -p $PAI_DIR/skills/Browser/Workflows+mkdir -p $PAI_DIR/skills/Browser/examples++cp Tools/Browse.ts $PAI_DIR/skills/Browser/Tools/+cp Workflows/*.md $PAI_DIR/skills/Browser/Workflows/+cp examples/*.ts $PAI_DIR/skills/Browser/examples/+```++### Step 3: Install Dependencies++```bash+cd $PAI_DIR/skills/Browser+bun install+bunx playwright install chromium+```++### Step 4: Verify++```bash+bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://example.com+```++Expected output: "Page loaded: Example Domain"++---++## Usage++### From Claude Code++Just ask:++```+Navigate to danielmiessler.com and take a screenshot+```++### From TypeScript++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch()+await browser.navigate('https://example.com')+await browser.screenshot({ path: 'screenshot.png' })+await browser.close()+```++### From CLI++```bash+# Open in visible browser+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://example.com++# Take screenshot+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png++# Verify element+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com "h1"+```++---++## API Reference++### Navigation+- `launch(options?)` - Start browser+- `navigate(url)` - Go to URL+- `goBack()` / `goForward()` - History+- `reload()` - Refresh page+- `close()` - Shut down++### Capture+- `screenshot(options?)` - 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)` - 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)` - Wait for element+- `waitForNavigation()` - Wait for page load+- `waitForNetworkIdle()` - Wait for idle+- `wait(ms)` - Fixed delay++### JavaScript+- `evaluate(script)` - Run JS+- `getConsoleLogs()` - Get console output+- `setUserAgent(ua)` - Change user agent++### Viewport+- `resize(width, height)` - Set size+- `setDevice(name)` - Emulate device++---++## Troubleshooting++### "Cannot find module 'playwright'"++```bash+cd $PAI_DIR/skills/Browser+bun install+```++### "Executable doesn't exist"++```bash+bunx playwright install chromium+```++### Screenshot is blank++Wait for page to load:+```typescript+await browser.waitForNetworkIdle()+await browser.screenshot({ path: 'shot.png' })+```++---++## Configuration++### Launch Options++```typescript+await browser.launch({+ browser: 'chromium', // 'chromium' | 'firefox' | 'webkit'+ headless: true, // false to see browser+ viewport: { width: 1280, height: 720 },+ userAgent: 'Custom UA'+})+```++### Screenshot Options++```typescript+await browser.screenshot({+ path: 'screenshot.png',+ fullPage: true, // Capture entire page+ selector: '#element', // Capture specific element+ type: 'png', // 'png' | 'jpeg'+ quality: 80 // JPEG quality (0-100)+})+```++---++## Changelog++### v1.0.0 (2026-01-03)+- Initial release+- Merged from Browse + Playwright skills+- Full Playwright API wrapper+- CLI tool with open/screenshot/verify commands+- 4 workflow definitions+- Example scriptsdiff --git a/Packs/kai-browser-skill/INSTALL.md b/Packs/kai-browser-skill/INSTALL.mdnew file mode 100644index 00000000..402c27e1--- /dev/null+++ b/Packs/kai-browser-skill/INSTALL.md@@ -0,0 +1,264 @@+# Kai Browser Skill - Installation Guide++**This guide is designed for AI agents installing this pack into a user's infrastructure.**++---++## Step 0: Pre-Installation System Analysis++**CRITICAL: Execute this analysis BEFORE any file operations.**++### 0.1 Environment Detection++```bash+# Detect operating system+uname -s # Darwin (macOS), Linux, or Windows++# Check for Bun runtime+which bun && bun --version++# Check for existing Playwright installation+ls -la $PAI_DIR/skills/Browser/ 2>/dev/null || echo "No existing Browser skill"+ls -la $PAI_DIR/skills/Playwright/ 2>/dev/null || echo "No existing Playwright skill"+ls -la $PAI_DIR/skills/Browse/ 2>/dev/null || echo "No existing Browse skill"++# Check for Playwright browsers+ls -la ~/Library/Caches/ms-playwright/ 2>/dev/null || \+ls -la ~/.cache/ms-playwright/ 2>/dev/null || \+echo "No Playwright browsers installed"+```++### 0.2 Conflict Resolution Matrix++| 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 |++### 0.3 Backup Procedure (If Conflicts Detected)++```bash+# Create timestamped backup+BACKUP_DIR="$PAI_DIR/Backups/browser-skill-$(date +%Y%m%d-%H%M%S)"+mkdir -p "$BACKUP_DIR"++# Backup any existing skills+[ -d "$PAI_DIR/skills/Browser" ] && cp -r "$PAI_DIR/skills/Browser" "$BACKUP_DIR/"+[ -d "$PAI_DIR/skills/Playwright" ] && cp -r "$PAI_DIR/skills/Playwright" "$BACKUP_DIR/"+[ -d "$PAI_DIR/skills/Browse" ] && cp -r "$PAI_DIR/skills/Browse" "$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++- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`+- **macOS, Linux, or Windows**: Cross-platform support via Playwright++---++## Step 1: Create Skill Directory++```bash+mkdir -p $PAI_DIR/skills/Browser+cd $PAI_DIR/skills/Browser+```++---++## Step 2: Copy Skill Files++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 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+cp Tools/Browse.ts $PAI_DIR/skills/Browser/Tools/+cp Workflows/*.md $PAI_DIR/skills/Browser/Workflows/+cp examples/*.ts $PAI_DIR/skills/Browser/examples/+```++---++## Step 3: Install Dependencies++```bash+cd $PAI_DIR/skills/Browser+bun install+```++This will install:+- `playwright` - Browser automation library+- Playwright browsers (Chromium, Firefox, WebKit)++---++## Step 4: Install Playwright Browsers++```bash+bunx playwright install chromium+```++**Optional:** Install all browsers:+```bash+bunx playwright install+```++---++## Step 5: Verify Installation++Run the verification script:++```bash+bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://example.com+```++Expected output:+```+Navigating to https://example.com...+Page loaded: Example Domain+Title: Example Domain+Console errors: 0+```++Take a test screenshot:++```bash+bun $PAI_DIR/skills/Browser/examples/screenshot.ts https://example.com /tmp/test.png+```++Check the screenshot exists:+```bash+ls -la /tmp/test.png+```++---++## Step 6: Test CLI Tool++```bash+# Should show help+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts++# Take a screenshot+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/cli-test.png+```++---++## Troubleshooting++### "Playwright browsers not installed"++```bash+bunx playwright install chromium+```++### "Cannot find module 'playwright'"++```bash+cd $PAI_DIR/skills/Browser+bun install+```++### "Permission denied" on Linux++Playwright may need additional dependencies:+```bash+bunx playwright install-deps chromium+```++---++## What's Included++| File | Purpose |+|------|---------|+| `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 |+| `Workflows/*.md` | Workflow definitions |+| `examples/*.ts` | Example scripts |+| `package.json` | Dependencies |+| `tsconfig.json` | TypeScript configuration |++---++## Usage++### From Claude Code++Just ask to use the browser:++```+Navigate to danielmiessler.com and take a screenshot+```++### From TypeScript++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch()+await browser.navigate('https://example.com')+await browser.screenshot({ path: 'screenshot.png' })+await browser.close()+```++### From CLI++```bash+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png+```++---++## Token Savings++This skill is a **file-based MCP** - it replaces the Playwright MCP with code-first implementation:++| Approach | Tokens |+|----------|--------|+| Playwright MCP | ~13,700 at startup |+| Browser Skill | ~50-200 per operation |+| **Savings** | **99%+** |diff --git a/Packs/kai-browser-skill/README.md b/Packs/kai-browser-skill/README.mdnew file mode 100644index 00000000..35a33140--- /dev/null+++ b/Packs/kai-browser-skill/README.md@@ -0,0 +1,81 @@+# Kai Browser Skill++**Code-first browser automation for Claude Code with 99% token savings.**++## What It Does++The Browser skill replaces the Playwright MCP with direct code execution:++- **Navigate** to URLs+- **Screenshot** pages (full page or element)+- **Interact** with forms, buttons, dropdowns+- **Verify** page content and elements+- **Extract** text and HTML++## Why File-Based?++| Approach | Tokens | When Loaded |+|----------|--------|-------------|+| Playwright MCP | ~13,700 | At startup (always) |+| Browser Skill | ~50-200 | Per operation (on demand) |++**Result:** 99%+ token savings++## Quick Start++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch()+await browser.navigate('https://example.com')+await browser.screenshot({ path: 'screenshot.png' })+await browser.close()+```++## CLI Tool++```bash+# Open URL in visible browser+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open https://example.com++# Take screenshot+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/shot.png++# Verify element exists+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify https://example.com "h1"+```++## API Methods++### Navigation+- `launch()` / `close()`+- `navigate(url)`+- `goBack()` / `goForward()` / `reload()`++### Capture+- `screenshot(options?)`+- `getVisibleText(selector?)`+- `getVisibleHtml(options?)`+- `savePdf(path)`++### Interaction+- `click(selector)`+- `fill(selector, value)`+- `type(selector, text)`+- `select(selector, value)`+- `pressKey(key)`++### Waiting+- `waitForSelector(selector)`+- `waitForNavigation()`+- `waitForNetworkIdle()`+- `wait(ms)`++## Installation++See `INSTALL.md` for step-by-step instructions.++## Verification++See `VERIFY.md` for verification steps.diff --git a/Packs/kai-browser-skill/SKILL.md b/Packs/kai-browser-skill/SKILL.mdnew file mode 100644index 00000000..f7e9be0a--- /dev/null+++ b/Packs/kai-browser-skill/SKILL.md@@ -0,0 +1,294 @@+---+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.+---++# Browser - Code-First Browser Automation++**Browser automation and web verification using code-first Playwright.**++---++## 🔌 File-Based MCP++This skill is a **file-based MCP** - a code-first API wrapper that replaces token-heavy MCP protocol calls.++**Why file-based?** Filter data in code BEFORE returning to model context = 99%+ token savings.++**Architecture:** See `$PAI_DIR/skills/CORE/SYSTEM/DOCUMENTATION/FileBasedMCPs.md`++---++## Quick Start++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch()+await browser.navigate('https://example.com')+await browser.screenshot({ path: 'screenshot.png' })+await browser.close()+```++**Why This Approach:**+- MCP loads ~13,700 tokens at startup+- Code-first loads ~50-200 tokens per operation+- Full Playwright API access, not limited to 21 MCP tools++---++## Voice Notification++**When executing a Browser workflow, do BOTH:**++1. **Send voice notification**:+ ```bash+ curl -s -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d '{"message": "Running the Browser workflow"}' \+ > /dev/null 2>&1 &+ ```++2. **Output text notification**:+ ```+ Running the **Browser** workflow...+ ```++---++## Workflow Routing++| Trigger | Workflow |+|---------|----------|+| Navigate to URL, take screenshot | `Workflows/Screenshot.md` |+| Verify page loads correctly | `Workflows/VerifyPage.md` |+| Fill forms, interact with page | `Workflows/Interact.md` |+| Extract page content | `Workflows/Extract.md` |++---++## API Reference++### Navigation+```typescript+await browser.launch(options?) // Start browser+await browser.navigate(url) // Go to URL+await browser.goBack() // History back+await browser.goForward() // History forward+await browser.reload() // Refresh+browser.getUrl() // Current URL+await browser.getTitle() // Page title+await browser.close() // Shut down browser+```++### Capture+```typescript+await browser.screenshot({ path, fullPage, selector })+await browser.getVisibleText(selector?)+await browser.getVisibleHtml({ removeScripts, minify })+await browser.savePdf(path, { format })+await browser.getAccessibilityTree()+```++### Network Monitoring+```typescript+browser.getNetworkLogs(options?) // Get all network requests/responses+browser.getNetworkStats() // Get summary statistics+browser.clearNetworkLogs() // Clear captured logs+```++### Dialog Handling+```typescript+browser.setDialogHandler(auto, response?) // Configure auto-handling+browser.getPendingDialog() // Get current dialog info+await browser.handleDialog(action, promptText?) // Handle dialog manually+```++### Tab Management+```typescript+browser.getTabs() // List all open tabs+await browser.newTab(url?) // Open new tab+await browser.switchTab(index) // Switch to tab by index+await browser.closeTab() // Close current tab+```++### Interaction+```typescript+await browser.click(selector)+await browser.hover(selector)+await browser.fill(selector, value)+await browser.type(selector, text, delay?)+await browser.select(selector, value)+await browser.pressKey(key, selector?)+await browser.drag(source, target)+await browser.uploadFile(selector, path)+```++### Waiting+```typescript+await browser.waitForSelector(selector, { state, timeout })+await browser.waitForText(text, { state, timeout })+await browser.waitForNavigation({ url, timeout })+await browser.waitForNetworkIdle(timeout?)+await browser.wait(ms)+await browser.waitForResponse(urlPattern)+```++### JavaScript+```typescript+await browser.evaluate(script)+browser.getConsoleLogs({ type, search, limit, clear })+await browser.setUserAgent(ua)+```++### Viewport+```typescript+await browser.resize(width, height)+await browser.setDevice('iPhone 14')+```++### iFrame+```typescript+await browser.iframeClick(iframeSelector, elementSelector)+await browser.iframeFill(iframeSelector, elementSelector, value)+```++---++## VERIFY Phase Integration++**The Browser skill is MANDATORY for VERIFY phase of web changes.**++Before claiming ANY web change is "live" or "working":++1. Launch browser+2. Navigate to the EXACT URL+3. Verify the EXACT element that changed+4. Take screenshot as evidence+5. Close browser++```typescript+// VERIFY Phase Pattern+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch({ headless: true })+await browser.navigate('https://example.com/changed-page')+await browser.waitForSelector('.changed-element')+const text = await browser.getVisibleText('.changed-element')+await browser.screenshot({ path: '/tmp/verify.png' })+await browser.close()++console.log(`Verified: "${text}"`)+```++**If you haven't LOOKED at the rendered page, you CANNOT claim it works.**++---++## CLI Tool++**Location:** `Tools/Browse.ts`++```bash+# Open URL in visible browser+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open <url>++# Take screenshot+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot <url> [path]++# Verify element exists+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify <url> <selector>+```++**Examples:**+```bash+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 "body"+```++---++## Examples++### Verify Page Loads++```bash+bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://danielmiessler.com+```++### Take Screenshot++```bash+bun $PAI_DIR/skills/Browser/examples/screenshot.ts https://example.com screenshot.png+```++### Fill Form++```typescript+const browser = new PlaywrightBrowser()+await browser.launch()+await browser.navigate('https://example.com/form')+await browser.fill('#email', '[email protected]')+await browser.fill('#password', 'secret')+await browser.click('button[type="submit"]')+await browser.waitForNavigation()+await browser.close()+```++---++## Alternative Implementations (Reference Only)++### Option A: Playwright MCP (Microsoft Official)+```bash+# npx @playwright/mcp@latest+# 25K GitHub stars, uses accessibility tree+# Pro: Official Microsoft support, well-maintained+# Con: 13,700 tokens at startup+```++### Option B: Chrome DevTools MCP (Google Official)+```bash+# npx @anthropic/chrome-devtools-mcp+# Best debugging capabilities, CDP protocol+# Pro: Deep browser internals access+# Con: Chrome-only, complex setup+```++### Option C: claude --chrome (Native Anthropic)+```bash+# claude --chrome+# Simplest option - built into Claude Code+# Pro: Zero configuration, native integration+# Con: Limited API compared to Playwright+```++### Option D: Stagehand (Browserbase)+```bash+# npx stagehand+# 19.9K stars, won Anthropic hackathon+# Pro: AI-native actions (act, extract, observe)+# Con: Emerging, less mature than Playwright+```++---++## Token Savings Comparison++| Approach | Tokens | Notes |+|----------|--------|-------|+| Playwright MCP | ~13,700 | Loaded at startup, always |+| Code-first | ~50-200 | Only what you use |+| **Savings** | **99%+** | Per operation |++---++## Full Documentation++**CLI Tool:** `Tools/Browse.ts`+**Implementation:** `README.md`+**API Reference:** `index.ts`+**Examples:** `examples/`diff --git a/Packs/kai-browser-skill/Tools/Browse.ts b/Packs/kai-browser-skill/Tools/Browse.tsnew file mode 100644index 00000000..3c69cc93--- /dev/null+++ b/Packs/kai-browser-skill/Tools/Browse.ts@@ -0,0 +1,142 @@+#!/usr/bin/env bun+/**+ * Browse CLI Tool+ *+ * Browser automation using Playwright code-first interface.+ * Wraps Playwright for easy CLI invocation.+ *+ * 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>+ *+ * 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"+ */++import { PlaywrightBrowser } from '../index.ts'++const VOICE_SERVER = 'http://localhost:8888/notify'++async function notify(message: string): Promise<void> {+ try {+ await fetch(VOICE_SERVER, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ message })+ })+ } catch {+ // Voice server not running - silent fail+ }+}++async function openUrl(url: string): Promise<void> {+ await notify('Opening browser with Browse skill')+ console.log(`Opening ${url} in browser...`)++ const browser = new PlaywrightBrowser()+ await browser.launch({ headless: false })+ await browser.navigate(url)++ console.log('Browser opened. Press Ctrl+C to close.')++ // Keep browser open until interrupted+ await new Promise(() => {})+}++async function takeScreenshot(url: string, path: string): Promise<void> {+ await notify('Taking screenshot with Browse skill')+ console.log(`Taking screenshot of ${url}...`)++ 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()++ console.log(`Screenshot saved to ${path}`)+}++async function verifyElement(url: string, selector: string): Promise<void> {+ await notify('Verifying page element with Browse skill')+ console.log(`Verifying ${selector} on ${url}...`)++ const browser = new PlaywrightBrowser()+ await browser.launch({ headless: true })+ await browser.navigate(url)++ 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()+ }+}++async function main(): Promise<void> {+ const args = process.argv.slice(2)+ const command = args[0]++ if (!command) {+ console.log(`+Browse CLI - Browser automation tool++Usage:+ bun run $PAI_DIR/skills/Browser/Tools/Browse.ts <command> [args]++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++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)+ }++ switch (command) {+ case 'open':+ if (!args[1]) {+ console.error('Error: URL required')+ process.exit(1)+ }+ await openUrl(args[1])+ break++ case 'screenshot':+ if (!args[1]) {+ console.error('Error: URL required')+ process.exit(1)+ }+ await takeScreenshot(args[1], args[2] || '/tmp/screenshot.png')+ 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++ default:+ console.error(`Unknown command: ${command}`)+ process.exit(1)+ }+}++main().catch(err => {+ console.error('Error:', err.message)+ process.exit(1)+})diff --git a/Packs/kai-browser-skill/VERIFY.md b/Packs/kai-browser-skill/VERIFY.mdnew file mode 100644index 00000000..55d2106d--- /dev/null+++ b/Packs/kai-browser-skill/VERIFY.md@@ -0,0 +1,169 @@+# Kai Browser Skill - Verification++**This verification guide is for AI agents to confirm successful installation.**++---++## 🚨 MANDATORY COMPLETION CHECKLIST++**AI Agents: You MUST verify ALL items below pass before reporting installation success.**++| # | 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 | ⬜ |++**Completion Requirements:**+- ALL 8 checks must show ✅+- 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/+ - Playwright chromium browser ready+ - API, examples, and CLI all functional+```++---++## Quick Verification++Run these commands to verify the Browser skill is working:++### 1. Check Dependencies++```bash+cd $PAI_DIR/skills/Browser+bun install --dry-run+```++Expected: Shows playwright as installed++### 2. Verify Page Load++```bash+bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://example.com+```++Expected output:+```+Navigating to https://example.com...+Page loaded: Example Domain+Title: Example Domain+Console errors: 0+```++### 3. Take Screenshot++```bash+bun $PAI_DIR/skills/Browser/examples/screenshot.ts https://example.com /tmp/browser-test.png+ls -la /tmp/browser-test.png+```++Expected: File exists, size > 0++### 4. Test CLI Tool++```bash+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts+```++Expected: Shows help text with available commands++### 5. CLI Screenshot++```bash+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot https://example.com /tmp/cli-test.png+ls -la /tmp/cli-test.png+```++Expected: File exists, size > 0++---++## Verification Checklist++| 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 |++---++## Common Issues++### "Cannot find module 'playwright'"++```bash+cd $PAI_DIR/skills/Browser+bun install+```++### "Executable doesn't exist"++```bash+bunx playwright install chromium+```++### Screenshot is blank++The page may need time to load:+```typescript+await browser.waitForNetworkIdle()+await browser.screenshot({ path: 'shot.png' })+```++---++## Full Test Script++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++async function verifyBrowserSkill() {+ console.log('Testing Browser skill...')++ const browser = new PlaywrightBrowser()++ // Test 1: Launch+ console.log('1. Launching browser...')+ await browser.launch({ headless: true })+ console.log(' OK')++ // Test 2: Navigate+ console.log('2. Navigating to example.com...')+ await browser.navigate('https://example.com')+ console.log(' OK')++ // Test 3: Get title+ console.log('3. Getting page title...')+ const title = await browser.getTitle()+ console.log(` Title: ${title}`)++ // Test 4: Screenshot+ console.log('4. Taking screenshot...')+ await browser.screenshot({ path: '/tmp/verify-test.png' })+ console.log(' OK')++ // Test 5: Close+ console.log('5. Closing browser...')+ await browser.close()+ console.log(' OK')++ console.log('\nAll tests passed!')+}++verifyBrowserSkill()+```diff --git a/Packs/kai-browser-skill/Workflows/Extract.md b/Packs/kai-browser-skill/Workflows/Extract.mdnew file mode 100644index 00000000..eb5edbab--- /dev/null+++ b/Packs/kai-browser-skill/Workflows/Extract.md@@ -0,0 +1,112 @@+# Extract Workflow++Extract content from web pages.++## Steps++1. **Launch and navigate**+ ```typescript+ import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+ const browser = new PlaywrightBrowser()+ await browser.launch({ headless: true })+ await browser.navigate(url)+ ```++2. **Extract content**+ ```typescript+ // Text content+ const text = await browser.getVisibleText()++ // Specific element+ const heading = await browser.getVisibleText('h1')++ // HTML+ const html = await browser.getVisibleHtml({+ selector: 'article',+ removeScripts: true,+ removeStyles: true,+ minify: true+ })+ ```++3. **Close browser**+ ```typescript+ await browser.close()+ ```++## Extraction Methods++### Get All Visible Text+```typescript+const allText = await browser.getVisibleText()+```++### Get Element Text+```typescript+const title = await browser.getVisibleText('h1')+const articles = await browser.getVisibleText('.article-list')+```++### Get Clean HTML+```typescript+const html = await browser.getVisibleHtml({+ selector: 'main',+ removeScripts: true,+ removeStyles: true,+ removeComments: true,+ minify: true+})+```++### Run JavaScript+```typescript+const data = await browser.evaluate(() => {+ return {+ title: document.title,+ links: Array.from(document.querySelectorAll('a')).map(a => a.href),+ timestamp: Date.now()+ }+})+```++### Get Accessibility Tree+```typescript+const a11y = await browser.getAccessibilityTree()+// Structured data about page elements+```++## Example: Article Extraction++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch({ headless: true })++await browser.navigate('https://example.com/article')++// Wait for content to load+await browser.waitForSelector('article')++// Extract+const title = await browser.getVisibleText('h1')+const content = await browser.getVisibleText('article')+const html = await browser.getVisibleHtml({+ selector: 'article',+ removeScripts: true+})++console.log({ title, contentLength: content.length })++await browser.close()+```++## Example: Save as PDF++```typescript+await browser.navigate('https://example.com/report')+await browser.savePdf('/tmp/report.pdf', {+ format: 'A4',+ printBackground: true+})+```diff --git a/Packs/kai-browser-skill/Workflows/Interact.md b/Packs/kai-browser-skill/Workflows/Interact.mdnew file mode 100644index 00000000..527fec8f--- /dev/null+++ b/Packs/kai-browser-skill/Workflows/Interact.md@@ -0,0 +1,102 @@+# Interact Workflow++Fill forms, click buttons, and interact with page elements.++## Steps++1. **Launch and navigate**+ ```typescript+ import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+ const browser = new PlaywrightBrowser()+ await browser.launch({ headless: false }) // Watch it work+ await browser.navigate(url)+ ```++2. **Interact with elements**+ ```typescript+ await browser.fill('#email', '[email protected]')+ await browser.fill('#password', 'secret')+ await browser.click('button[type="submit"]')+ ```++3. **Wait for result**+ ```typescript+ await browser.waitForNavigation()+ // or+ await browser.waitForSelector('.success-message')+ ```++4. **Verify and close**+ ```typescript+ const result = await browser.getVisibleText('.result')+ await browser.close()+ ```++## Common Interactions++### Click+```typescript+await browser.click('button')+await browser.click('#submit-btn')+await browser.click('a[href="/login"]')+```++### Fill Input+```typescript+await browser.fill('input[name="email"]', '[email protected]')+await browser.fill('#search', 'query')+```++### Type with Delay (Realistic)+```typescript+await browser.type('#search', 'query', 50) // 50ms between keys+```++### Select Dropdown+```typescript+await browser.select('#country', 'US')+await browser.select('#tags', ['tag1', 'tag2']) // Multi-select+```++### Press Keys+```typescript+await browser.pressKey('Enter')+await browser.pressKey('Escape')+await browser.pressKey('Tab', '#input-field') // On specific element+```++### Hover+```typescript+await browser.hover('.dropdown-trigger')+await browser.click('.dropdown-item') // Now visible+```++### Drag and Drop+```typescript+await browser.drag('#draggable', '#drop-zone')+```++### File Upload+```typescript+await browser.uploadFile('input[type="file"]', '/path/to/file.pdf')+```++## Example: Login Flow++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch({ headless: false })++await browser.navigate('https://example.com/login')+await browser.fill('#email', '[email protected]')+await browser.fill('#password', 'password123')+await browser.click('button[type="submit"]')++await browser.waitForNavigation()+const welcomeText = await browser.getVisibleText('.welcome-message')+console.log(`Logged in: ${welcomeText}`)++await browser.close()+```diff --git a/Packs/kai-browser-skill/Workflows/Screenshot.md b/Packs/kai-browser-skill/Workflows/Screenshot.mdnew file mode 100644index 00000000..7e1d0ad2--- /dev/null+++ b/Packs/kai-browser-skill/Workflows/Screenshot.md@@ -0,0 +1,58 @@+# Screenshot Workflow++Take a screenshot of a URL.++## Steps++1. **Launch browser**+ ```typescript+ import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+ const browser = new PlaywrightBrowser()+ await browser.launch({ headless: true })+ ```++2. **Navigate to URL**+ ```typescript+ await browser.navigate(url)+ ```++3. **Take screenshot**+ ```typescript+ await browser.screenshot({+ path: '/tmp/screenshot.png',+ fullPage: false // true for full page+ })+ ```++4. **Close browser**+ ```typescript+ await browser.close()+ ```++## Options++| Option | Default | Description |+|--------|---------|-------------|+| `path` | - | Output file path |+| `fullPage` | false | Capture full scrollable page |+| `selector` | - | Capture specific element |+| `type` | 'png' | 'png' or 'jpeg' |+| `quality` | - | JPEG quality (0-100) |++## Example: Element Screenshot++```typescript+await browser.screenshot({+ selector: '.hero-section',+ path: '/tmp/hero.png'+})+```++## Example: Mobile Screenshot++```typescript+await browser.launch()+await browser.setDevice('iPhone 14')+await browser.navigate(url)+await browser.screenshot({ path: '/tmp/mobile.png' })+```diff --git a/Packs/kai-browser-skill/Workflows/VerifyPage.md b/Packs/kai-browser-skill/Workflows/VerifyPage.mdnew file mode 100644index 00000000..28b256c7--- /dev/null+++ b/Packs/kai-browser-skill/Workflows/VerifyPage.md@@ -0,0 +1,81 @@+# VerifyPage Workflow++Verify a page loads correctly and check for errors.++## Steps++1. **Launch and navigate**+ ```typescript+ import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'+ const browser = new PlaywrightBrowser()+ await browser.launch({ headless: true })++ const startTime = Date.now()+ await browser.navigate(url)+ const loadTime = Date.now() - startTime+ ```++2. **Check basic info**+ ```typescript+ const title = await browser.getTitle()+ const finalUrl = browser.getUrl() // Check for redirects+ ```++3. **Verify specific element (optional)**+ ```typescript+ await browser.waitForSelector(selector, { timeout: 5000 })+ const text = await browser.getVisibleText(selector)+ ```++4. **Check for console errors**+ ```typescript+ const errors = browser.getConsoleLogs({ type: 'error' })+ if (errors.length > 0) {+ console.log('Console errors:', errors)+ }+ ```++5. **Take verification screenshot**+ ```typescript+ await browser.screenshot({ path: '/tmp/verify.png' })+ ```++6. **Close browser**+ ```typescript+ await browser.close()+ ```++## Example: Full Verification++```typescript+import { PlaywrightBrowser } from '$PAI_DIR/skills/Browser/index.ts'++const browser = new PlaywrightBrowser()+await browser.launch({ headless: true })++await browser.navigate('https://danielmiessler.com')++// Basic checks+const title = await browser.getTitle()+console.log(`Title: ${title}`)++// Check specific element+await browser.waitForSelector('h1')+const heading = await browser.getVisibleText('h1')+console.log(`H1: ${heading}`)++// Console errors+const errors = browser.getConsoleLogs({ type: 'error' })+console.log(`Errors: ${errors.length}`)++// Evidence+await browser.screenshot({ path: '/tmp/verify.png' })++await browser.close()+```++## CLI Usage++```bash+bun $PAI_DIR/skills/Browser/examples/verify-page.ts https://example.com+```diff --git a/Packs/kai-browser-skill/examples/comprehensive-test.ts b/Packs/kai-browser-skill/examples/comprehensive-test.tsnew file mode 100644index 00000000..c624b8b2--- /dev/null+++ b/Packs/kai-browser-skill/examples/comprehensive-test.ts@@ -0,0 +1,417 @@+#!/usr/bin/env bun+/**+ * Comprehensive test of all Playwright FileMCP functionality+ */++import { PlaywrightBrowser } from '../index.ts'++const TEST_URL = 'https://httpbin.org'+const FORM_URL = 'https://httpbin.org/forms/post'++interface TestResult {+ name: string+ status: 'PASS' | 'FAIL' | 'SKIP'+ error?: string+ duration?: number+}++const results: TestResult[] = []++async function test(name: string, fn: () => Promise<void>): Promise<void> {+ const start = Date.now()+ try {+ await fn()+ results.push({ name, status: 'PASS', duration: Date.now() - start })+ console.log(`✅ ${name}`)+ } catch (error) {+ const msg = error instanceof Error ? error.message : String(error)+ results.push({ name, status: 'FAIL', error: msg, duration: Date.now() - start })+ console.log(`❌ ${name}: ${msg}`)+ }+}++function skip(name: string, reason: string): void {+ results.push({ name, status: 'SKIP', error: reason })+ console.log(`⏭️ ${name}: ${reason}`)+}++async function main() {+ console.log('=== Playwright FileMCP Comprehensive Test ===\n')++ const browser = new PlaywrightBrowser()++ // ============================================+ // LIFECYCLE+ // ============================================+ console.log('\n--- LIFECYCLE ---')++ await test('launch()', async () => {+ await browser.launch({ headless: true })+ })++ // ============================================+ // NAVIGATION+ // ============================================+ console.log('\n--- NAVIGATION ---')++ await test('navigate()', async () => {+ await browser.navigate(TEST_URL)+ })++ await test('getUrl()', async () => {+ const url = browser.getUrl()+ if (!url.includes('httpbin.org')) throw new Error(`Expected httpbin.org, got ${url}`)+ })++ await test('getTitle()', async () => {+ const title = await browser.getTitle()+ if (!title) throw new Error('Title is empty')+ })++ await test('navigate() to form page', async () => {+ await browser.navigate(FORM_URL)+ })++ await test('goBack()', async () => {+ await browser.goBack()+ const url = browser.getUrl()+ if (!url.includes('httpbin.org')) throw new Error('goBack failed')+ })++ await test('goForward()', async () => {+ await browser.goForward()+ const url = browser.getUrl()+ if (!url.includes('forms/post')) throw new Error('goForward failed')+ })++ await test('reload()', async () => {+ await browser.reload()+ })++ // ============================================+ // CAPTURE+ // ============================================+ console.log('\n--- CAPTURE ---')++ await test('screenshot()', async () => {+ const buffer = await browser.screenshot()+ if (buffer.length < 1000) throw new Error('Screenshot too small')+ })++ await test('screenshot({ fullPage: true })', async () => {+ const buffer = await browser.screenshot({ fullPage: true })+ if (buffer.length < 1000) throw new Error('Screenshot too small')+ })++ await test('getVisibleText()', async () => {+ const text = await browser.getVisibleText()+ if (!text || text.length < 10) throw new Error('No visible text')+ })++ await test('getVisibleText(selector)', async () => {+ await browser.navigate(TEST_URL)+ const text = await browser.getVisibleText('body')+ if (!text) throw new Error('No text from selector')+ })++ await test('getVisibleHtml()', async () => {+ const html = await browser.getVisibleHtml()+ if (!html.includes('<')) throw new Error('Invalid HTML')+ })++ await test('getVisibleHtml({ removeScripts: true })', async () => {+ const html = await browser.getVisibleHtml({ removeScripts: true, minify: true })+ if (html.includes('<script')) throw new Error('Scripts not removed')+ })++ await test('getAccessibilityTree()', async () => {+ const tree = await browser.getAccessibilityTree()+ if (!tree) throw new Error('No accessibility tree')+ })++ // Skip PDF - requires non-headless or specific setup+ skip('savePdf()', 'Requires specific browser configuration')++ // ============================================+ // INTERACTION+ // ============================================+ console.log('\n--- INTERACTION ---')++ await test('navigate to form', async () => {+ await browser.navigate(FORM_URL)+ await browser.waitForSelector('form')+ })++ await test('fill()', async () => {+ await browser.fill('input[name="custname"]', 'Test User')+ })++ await test('type()', async () => {+ await browser.fill('input[name="custtel"]', '') // Clear first+ await browser.type('input[name="custtel"]', '555-1234', 10)+ })++ await test('click()', async () => {+ await browser.click('input[name="topping"][value="bacon"]')+ })++ await test('hover()', async () => {+ // Use a reliable element - the form itself or legend+ await browser.hover('form')+ })++ await test('select()', async () => {+ // httpbin form uses select[name="size"] - use with waitForSelector first+ try {+ await browser.waitForSelector('select[name="size"]', { timeout: 2000 })+ await browser.select('select[name="size"]', 'medium')+ } catch {+ // If select doesn't exist, try radio button selection as alternative+ await browser.click('input[name="size"][value="medium"]')+ }+ })++ await test('pressKey()', async () => {+ await browser.pressKey('Tab')+ })++ // Skip drag - requires specific elements+ skip('drag()', 'Requires draggable elements')++ // Skip uploadFile - requires file input+ skip('uploadFile()', 'Requires file input element')++ // ============================================+ // VIEWPORT+ // ============================================+ console.log('\n--- VIEWPORT ---')++ await test('resize()', async () => {+ await browser.resize(1920, 1080)+ })++ await test('setDevice()', async () => {+ await browser.setDevice('iPhone 12')+ })++ // Reset viewport+ await browser.resize(1280, 720)++ // ============================================+ // IFRAME+ // ============================================+ console.log('\n--- IFRAME ---')+ skip('iframeClick()', 'Requires page with iframe')+ skip('iframeFill()', 'Requires page with iframe')++ // ============================================+ // JAVASCRIPT & CONSOLE+ // ============================================+ console.log('\n--- JAVASCRIPT & CONSOLE ---')++ await test('evaluate()', async () => {+ const result = await browser.evaluate('1 + 1')+ if (result !== 2) throw new Error(`Expected 2, got ${result}`)+ })++ await test('evaluate() - DOM access', async () => {+ // Use document.body which always exists+ const hasBody = await browser.evaluate(() => !!document.body)+ if (!hasBody) throw new Error('Could not access DOM via evaluate')+ })++ await test('console logging + getConsoleLogs()', async () => {+ await browser.evaluate(() => {+ console.log('Test log message')+ console.warn('Test warning')+ console.error('Test error')+ })+ await browser.wait(100) // Let logs propagate+ const logs = browser.getConsoleLogs()+ if (logs.length < 3) throw new Error(`Expected 3+ logs, got ${logs.length}`)+ })++ await test('getConsoleLogs({ type: "error" })', async () => {+ const errors = browser.getConsoleLogs({ type: 'error' })+ if (errors.length < 1) throw new Error('Expected error logs')+ })++ await test('getConsoleLogs({ search: "warning" })', async () => {+ const warns = browser.getConsoleLogs({ search: 'warning' })+ if (warns.length < 1) throw new Error('Expected warning logs')+ })++ await test('setUserAgent()', async () => {+ await browser.setUserAgent('TestBot/1.0')+ // Navigate to check+ await browser.navigate('https://httpbin.org/user-agent')+ const text = await browser.getVisibleText()+ if (!text.includes('TestBot')) throw new Error('User agent not set')+ })++ // ============================================+ // NETWORK MONITORING+ // ============================================+ console.log('\n--- NETWORK MONITORING ---')++ await test('clearNetworkLogs()', async () => {+ browser.clearNetworkLogs()+ })++ await test('network capture on navigate', async () => {+ await browser.navigate('https://httpbin.org/get')+ await browser.wait(500)+ const logs = browser.getNetworkLogs()+ if (logs.length < 1) throw new Error('No network logs captured')+ })++ await test('getNetworkLogs({ type: "response" })', async () => {+ const responses = browser.getNetworkLogs({ type: 'response' })+ if (responses.length < 1) throw new Error('No response logs')+ })++ await test('getNetworkLogs({ urlPattern: /get/ })', async () => {+ const filtered = browser.getNetworkLogs({ urlPattern: /get/ })+ if (filtered.length < 1) throw new Error('URL pattern filter failed')+ })++ await test('getNetworkLogs({ status: 200 })', async () => {+ const ok = browser.getNetworkLogs({ status: 200, type: 'response' })+ if (ok.length < 1) throw new Error('Status filter failed')+ })++ await test('getNetworkStats()', async () => {+ const stats = browser.getNetworkStats()+ if (stats.totalRequests < 1) throw new Error('No requests in stats')+ if (stats.totalResponses < 1) throw new Error('No responses in stats')+ })++ // ============================================+ // DIALOG HANDLING+ // ============================================+ console.log('\n--- DIALOG HANDLING ---')++ await test('setDialogHandler()', async () => {+ browser.setDialogHandler(true, 'test response')+ })++ await test('getPendingDialog() - no dialog', async () => {+ const dialog = browser.getPendingDialog()+ if (dialog !== null) throw new Error('Expected no pending dialog')+ })++ // Dialog interaction requires triggering a dialog - skip for now+ skip('handleDialog()', 'Requires triggering a dialog')++ // ============================================+ // TAB MANAGEMENT+ // ============================================+ console.log('\n--- TAB MANAGEMENT ---')++ await test('getTabs()', async () => {+ const tabs = browser.getTabs()+ if (tabs.length < 1) throw new Error('Expected at least 1 tab')+ })++ await test('newTab()', async () => {+ const beforeCount = browser.getTabs().length+ await browser.newTab('https://httpbin.org/html')+ const afterCount = browser.getTabs().length+ if (afterCount !== beforeCount + 1) throw new Error('Tab not created')+ })++ await test('switchTab()', async () => {+ await browser.switchTab(0)+ const url = browser.getUrl()+ // Should be back on first tab+ })++ await test('closeTab()', async () => {+ await browser.switchTab(1) // Switch to second tab+ await browser.closeTab()+ const tabs = browser.getTabs()+ if (tabs.length !== 1) throw new Error('Tab not closed')+ })++ // ============================================+ // WAITING+ // ============================================+ console.log('\n--- WAITING ---')++ await test('wait()', async () => {+ const start = Date.now()+ await browser.wait(100)+ const elapsed = Date.now() - start+ if (elapsed < 90) throw new Error('Wait too short')+ })++ await test('waitForSelector()', async () => {+ await browser.navigate('https://httpbin.org/html')+ await browser.waitForSelector('h1')+ })++ await test('waitForText()', async () => {+ await browser.waitForText('Herman Melville')+ })++ await test('waitForNavigation()', async () => {+ // Already navigated, this should pass immediately or timeout+ await browser.navigate('https://httpbin.org')+ })++ await test('waitForNetworkIdle()', async () => {+ await browser.waitForNetworkIdle(5000)+ })++ await test('waitForResponse()', async () => {+ // Make a request and wait for it+ browser.clearNetworkLogs()+ const responsePromise = browser.waitForResponse(/httpbin/, { timeout: 5000 })+ await browser.navigate('https://httpbin.org/get')+ const response = await responsePromise+ if (response.status !== 200) throw new Error(`Expected 200, got ${response.status}`)+ })++ // ============================================+ // CLEANUP+ // ============================================+ console.log('\n--- CLEANUP ---')++ await test('close()', async () => {+ await browser.close()+ })++ // ============================================+ // SUMMARY+ // ============================================+ console.log('\n' + '='.repeat(50))+ console.log('TEST SUMMARY')+ console.log('='.repeat(50))++ const passed = results.filter(r => r.status === 'PASS').length+ const failed = results.filter(r => r.status === 'FAIL').length+ const skipped = results.filter(r => r.status === 'SKIP').length++ console.log(`\n✅ Passed: ${passed}`)+ console.log(`❌ Failed: ${failed}`)+ console.log(`⏭️ Skipped: ${skipped}`)+ console.log(`📊 Total: ${results.length}`)++ if (failed > 0) {+ console.log('\n--- FAILURES ---')+ results.filter(r => r.status === 'FAIL').forEach(r => {+ console.log(`\n${r.name}:`)+ console.log(` Error: ${r.error}`)+ })+ }++ const totalDuration = results.reduce((sum, r) => sum + (r.duration || 0), 0)+ console.log(`\n⏱️ Total time: ${(totalDuration / 1000).toFixed(2)}s`)++ process.exit(failed > 0 ? 1 : 0)+}++main().catch(err => {+ console.error('Test suite failed:', err)+ process.exit(1)+})diff --git a/Packs/kai-browser-skill/examples/screenshot.ts b/Packs/kai-browser-skill/examples/screenshot.tsnew file mode 100644index 00000000..93d5ebc7--- /dev/null+++ b/Packs/kai-browser-skill/examples/screenshot.ts@@ -0,0 +1,71 @@+#!/usr/bin/env bun++/**+ * Take a screenshot of a URL+ *+ * Usage: bun screenshot.ts <url> [output.png]+ *+ * Examples:+ * bun screenshot.ts https://example.com+ * bun screenshot.ts https://danielmiessler.com page.png+ * bun screenshot.ts https://example.com fullpage.png --full+ */++import { PlaywrightBrowser } from '../index'++async function main() {+ const url = process.argv[2]+ const output = process.argv[3] || 'screenshot.png'+ const fullPage = process.argv.includes('--full')++ if (!url) {+ console.error('Usage: bun screenshot.ts <url> [output.png] [--full]')+ console.error('')+ console.error('Examples:')+ console.error(' bun screenshot.ts https://example.com')+ console.error(' bun screenshot.ts https://danielmiessler.com page.png')+ console.error(' bun screenshot.ts https://example.com fullpage.png --full')+ process.exit(1)+ }++ console.log('=== Playwright Screenshot ===\n')++ const browser = new PlaywrightBrowser()++ try {+ console.log('1. Launching browser...')+ await browser.launch({ headless: true })++ console.log(`2. Navigating to ${url}...`)+ await browser.navigate(url)++ console.log(`3. Taking screenshot (fullPage: ${fullPage})...`)+ await browser.screenshot({+ path: output,+ fullPage+ })++ console.log(`\n✅ Screenshot saved: ${output}`)++ // Token savings calculation+ const mcpTokens = 13700+ const codeTokens = 150+ const savings = ((mcpTokens - codeTokens) / mcpTokens * 100).toFixed(1)++ console.log(`\n📊 Token savings: ${savings}%`)+ console.log(` MCP approach: ~${mcpTokens} tokens`)+ console.log(` Code approach: ~${codeTokens} tokens`)++ } catch (error) {+ console.error('❌ Error:', error instanceof Error ? error.message : error)+ process.exit(1)+ } finally {+ await browser.close()+ }+}++if (import.meta.main) {+ main()+}++export { main }diff --git a/Packs/kai-browser-skill/examples/verify-page.ts b/Packs/kai-browser-skill/examples/verify-page.tsnew file mode 100644index 00000000..0fdae3e6--- /dev/null+++ b/Packs/kai-browser-skill/examples/verify-page.ts@@ -0,0 +1,91 @@+#!/usr/bin/env bun++/**+ * Verify a page loads correctly+ *+ * Usage: bun verify-page.ts <url> [selector]+ *+ * Examples:+ * bun verify-page.ts https://example.com+ * bun verify-page.ts https://danielmiessler.com "h1"+ * bun verify-page.ts https://example.com ".main-content"+ */++import { PlaywrightBrowser } from '../index'++async function main() {+ const url = process.argv[2]+ const selector = process.argv[3]++ if (!url) {+ console.error('Usage: bun verify-page.ts <url> [selector]')+ console.error('')+ console.error('Examples:')+ console.error(' bun verify-page.ts https://example.com')+ console.error(' bun verify-page.ts https://danielmiessler.com "h1"')+ process.exit(1)+ }++ console.log('=== Page Verification ===\n')++ const browser = new PlaywrightBrowser()++ try {+ console.log('1. Launching browser...')+ await browser.launch({ headless: true })++ console.log(`2. Navigating to ${url}...`)+ const startTime = Date.now()+ await browser.navigate(url)+ const loadTime = Date.now() - startTime++ console.log(` ✅ Page loaded in ${loadTime}ms`)++ // Get page title+ const title = await browser.getTitle()+ console.log(`\n3. Page title: "${title}"`)++ // Get current URL (check for redirects)+ const finalUrl = browser.getUrl()+ if (finalUrl !== url) {+ console.log(` ⚠️ Redirected to: ${finalUrl}`)+ }++ // Check for specific selector if provided+ if (selector) {+ console.log(`\n4. Checking for selector: ${selector}`)+ try {+ await browser.waitForSelector(selector, { timeout: 5000 })+ const text = await browser.getVisibleText(selector)+ console.log(` ✅ Found! Content: "${text.slice(0, 100)}${text.length > 100 ? '...' : ''}"`)+ } catch {+ console.log(` ❌ Selector not found within 5s`)+ }+ }++ // Check console for errors+ const errors = browser.getConsoleLogs({ type: 'error' })+ if (errors.length > 0) {+ console.log(`\n⚠️ Console errors (${errors.length}):`)+ errors.slice(0, 3).forEach(err => {+ console.log(` - ${err.text.slice(0, 100)}`)+ })+ } else {+ console.log('\n✅ No console errors')+ }++ console.log('\n=== Verification Complete ===')++ } catch (error) {+ console.error('❌ Error:', error instanceof Error ? error.message : error)+ process.exit(1)+ } finally {+ await browser.close()+ }+}++if (import.meta.main) {+ main()+}++export { main }diff --git a/Packs/kai-browser-skill/icons/kai-browser-skill.png b/Packs/kai-browser-skill/icons/kai-browser-skill.pngnew file mode 100644index 00000000..f9b1832aBinary files /dev/null and b/Packs/kai-browser-skill/icons/kai-browser-skill.png differdiff --git a/Packs/kai-browser-skill/package.json b/Packs/kai-browser-skill/package.jsonnew file mode 100644index 00000000..3d13187f--- /dev/null+++ b/Packs/kai-browser-skill/package.json@@ -0,0 +1,16 @@+{+ "name": "@kai/playwright",+ "version": "1.0.0",+ "description": "Code-first Playwright wrapper replacing token-heavy MCP",+ "type": "module",+ "main": "index.ts",+ "scripts": {+ "test": "bun test"+ },+ "dependencies": {+ "playwright": "^1.49.0"+ },+ "devDependencies": {+ "@types/bun": "^1.1.0"+ }+}diff --git a/Packs/kai-browser-skill/src/index.ts b/Packs/kai-browser-skill/src/index.tsnew file mode 100644index 00000000..5d06b90f--- /dev/null+++ b/Packs/kai-browser-skill/src/index.ts@@ -0,0 +1,907 @@+/**+ * Playwright Code-First Interface+ *+ * Replaces token-heavy Playwright MCP with direct code execution.+ * Savings: ~13,700 tokens (MCP) → ~50-200 tokens (per-operation)+ *+ * @example+ * const browser = new PlaywrightBrowser()+ * await browser.launch()+ * await browser.navigate('https://example.com')+ * const screenshot = await browser.screenshot()+ * await browser.close()+ */++import { chromium, firefox, webkit, type Browser, type Page, type BrowserContext } from 'playwright'++export type BrowserType = 'chromium' | 'firefox' | 'webkit'++export interface LaunchOptions {+ browser?: BrowserType+ headless?: boolean+ viewport?: { width: number; height: number }+ userAgent?: string+}++export interface NavigateOptions {+ timeout?: number+ waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit'+}++export interface ScreenshotOptions {+ selector?: string+ fullPage?: boolean+ path?: string+ type?: 'png' | 'jpeg'+ quality?: number+}++export interface ClickOptions {+ button?: 'left' | 'right' | 'middle'+ clickCount?: number+ delay?: number+ timeout?: number+}++export interface FillOptions {+ timeout?: number+ force?: boolean+}++export interface ConsoleLogEntry {+ type: string+ text: string+ timestamp: number+}++export interface NetworkLogEntry {+ type: 'request' | 'response'+ url: string+ method: string+ status?: number+ statusText?: string+ headers?: Record<string, string>+ resourceType?: string+ timestamp: number+ duration?: number+ size?: number+}++export interface DialogInfo {+ type: 'alert' | 'confirm' | 'prompt' | 'beforeunload'+ message: string+ defaultValue?: string+}++/**+ * Main Playwright browser controller+ *+ * Provides all browser automation capabilities without MCP overhead.+ * Each method is a direct wrapper around Playwright APIs.+ */+export class PlaywrightBrowser {+ private browser: Browser | null = null+ private context: BrowserContext | null = null+ private page: Page | null = null+ private consoleLogs: ConsoleLogEntry[] = []+ private networkLogs: NetworkLogEntry[] = []+ private requestTimings: Map<string, number> = new Map()+ private pendingDialog: DialogInfo | null = null+ private autoHandleDialogs: boolean = false+ private dialogResponse: string | boolean = true++ /**+ * Launch browser instance+ */+ async launch(options?: LaunchOptions): Promise<void> {+ const browserType = options?.browser || 'chromium'+ const launcher = browserType === 'firefox' ? firefox : browserType === 'webkit' ? webkit : chromium++ this.browser = await launcher.launch({+ headless: options?.headless ?? false+ })++ this.context = await this.browser.newContext({+ viewport: options?.viewport || { width: 1280, height: 720 },+ userAgent: options?.userAgent+ })++ this.page = await this.context.newPage()++ // Attach all event listeners+ this.attachPageListeners(this.page)+ }++ /**+ * Ensure browser is launched+ */+ private ensurePage(): Page {+ if (!this.page) {+ throw new Error('Browser not launched. Call launch() first.')+ }+ return this.page+ }++ /**+ * Attach event listeners to a page (console, network, dialog)+ * Called when creating new pages to maintain consistent monitoring+ */+ private attachPageListeners(page: Page): void {+ // Capture console logs+ page.on('console', msg => {+ this.consoleLogs.push({+ type: msg.type(),+ text: msg.text(),+ timestamp: Date.now()+ })+ })++ // Capture network requests+ page.on('request', request => {+ const timestamp = Date.now()+ this.requestTimings.set(request.url(), timestamp)+ this.networkLogs.push({+ type: 'request',+ url: request.url(),+ method: request.method(),+ resourceType: request.resourceType(),+ headers: request.headers(),+ timestamp+ })+ })++ // Capture network responses+ page.on('response', async response => {+ const url = response.url()+ const requestTime = this.requestTimings.get(url)+ const timestamp = Date.now()++ let size = 0+ try {+ const body = await response.body()+ size = body.length+ } catch {+ // Response body not available (e.g., redirects)+ }++ this.networkLogs.push({+ type: 'response',+ url,+ method: response.request().method(),+ status: response.status(),+ statusText: response.statusText(),+ headers: response.headers(),+ resourceType: response.request().resourceType(),+ timestamp,+ duration: requestTime ? timestamp - requestTime : undefined,+ size+ })+ })++ // Capture dialogs+ page.on('dialog', async dialog => {+ this.pendingDialog = {+ type: dialog.type() as DialogInfo['type'],+ message: dialog.message(),+ defaultValue: dialog.defaultValue()+ }++ if (this.autoHandleDialogs) {+ if (typeof this.dialogResponse === 'string') {+ await dialog.accept(this.dialogResponse)+ } else if (this.dialogResponse) {+ await dialog.accept()+ } else {+ await dialog.dismiss()+ }+ this.pendingDialog = null+ }+ })+ }++ // ============================================+ // NAVIGATION+ // ============================================++ /**+ * Navigate to URL+ */+ async navigate(url: string, options?: NavigateOptions): Promise<void> {+ const page = this.ensurePage()+ await page.goto(url, {+ timeout: options?.timeout || 30000,+ waitUntil: options?.waitUntil || 'load'+ })+ }++ /**+ * Go back in browser history+ */+ async goBack(): Promise<void> {+ const page = this.ensurePage()+ await page.goBack()+ }++ /**+ * Go forward in browser history+ */+ async goForward(): Promise<void> {+ const page = this.ensurePage()+ await page.goForward()+ }++ /**+ * Reload current page+ */+ async reload(): Promise<void> {+ const page = this.ensurePage()+ await page.reload()+ }++ /**+ * Get current URL+ */+ getUrl(): string {+ return this.ensurePage().url()+ }++ /**+ * Get page title+ */+ async getTitle(): Promise<string> {+ return await this.ensurePage().title()+ }++ // ============================================+ // CAPTURE+ // ============================================++ /**+ * Take screenshot+ *+ * @returns Base64 encoded image or saves to path+ */+ async screenshot(options?: ScreenshotOptions): Promise<Buffer> {+ const page = this.ensurePage()++ if (options?.selector) {+ const element = await page.locator(options.selector)+ return await element.screenshot({+ path: options?.path,+ type: options?.type || 'png',+ quality: options?.quality+ })+ }++ return await page.screenshot({+ path: options?.path,+ fullPage: options?.fullPage || false,+ type: options?.type || 'png',+ quality: options?.quality+ })+ }++ /**+ * Get visible text content+ */+ async getVisibleText(selector?: string): Promise<string> {+ const page = this.ensurePage()++ if (selector) {+ return await page.locator(selector).textContent() || ''+ }++ return await page.evaluate(() => document.body.innerText)+ }++ /**+ * Get HTML content (with optional cleanup)+ */+ async getVisibleHtml(options?: {+ selector?: string+ removeScripts?: boolean+ removeStyles?: boolean+ removeComments?: boolean+ minify?: boolean+ }): Promise<string> {+ const page = this.ensurePage()++ let html = options?.selector+ ? await page.locator(options.selector).innerHTML()+ : await page.content()++ if (options?.removeScripts) {+ html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')+ }++ if (options?.removeStyles) {+ html = html.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')+ }++ if (options?.removeComments) {+ html = html.replace(/<!--[\s\S]*?-->/g, '')+ }++ if (options?.minify) {+ html = html.replace(/\s+/g, ' ').trim()+ }++ return html+ }++ /**+ * Save page as PDF+ */+ async savePdf(path: string, options?: {+ format?: 'A4' | 'Letter' | 'Legal' | 'Tabloid'+ printBackground?: boolean+ margin?: { top?: string; right?: string; bottom?: string; left?: string }+ }): Promise<Buffer> {+ const page = this.ensurePage()++ return await page.pdf({+ path,+ format: options?.format || 'A4',+ printBackground: options?.printBackground ?? true,+ margin: options?.margin+ })+ }++ // ============================================+ // INTERACTION+ // ============================================++ /**+ * Click element+ */+ async click(selector: string, options?: ClickOptions): Promise<void> {+ const page = this.ensurePage()+ await page.click(selector, {+ button: options?.button,+ clickCount: options?.clickCount,+ delay: options?.delay,+ timeout: options?.timeout+ })+ }++ /**+ * Hover over element+ */+ async hover(selector: string): Promise<void> {+ const page = this.ensurePage()+ await page.hover(selector)+ }++ /**+ * Fill input field+ */+ async fill(selector: string, value: string, options?: FillOptions): Promise<void> {+ const page = this.ensurePage()+ await page.fill(selector, value, {+ timeout: options?.timeout,+ force: options?.force+ })+ }++ /**+ * Type text (character by character, for realistic input)+ */+ async type(selector: string, text: string, delay?: number): Promise<void> {+ const page = this.ensurePage()+ await page.locator(selector).pressSequentially(text, { delay: delay || 50 })+ }++ /**+ * Select dropdown option+ */+ async select(selector: string, value: string | string[]): Promise<void> {+ const page = this.ensurePage()+ await page.selectOption(selector, value)+ }++ /**+ * Press keyboard key+ */+ async pressKey(key: string, selector?: string): Promise<void> {+ const page = this.ensurePage()++ if (selector) {+ await page.locator(selector).press(key)+ } else {+ await page.keyboard.press(key)+ }+ }++ /**+ * Drag element to target+ */+ async drag(sourceSelector: string, targetSelector: string): Promise<void> {+ const page = this.ensurePage()+ await page.dragAndDrop(sourceSelector, targetSelector)+ }++ /**+ * Upload file+ */+ async uploadFile(selector: string, filePath: string | string[]): Promise<void> {+ const page = this.ensurePage()+ await page.setInputFiles(selector, filePath)+ }++ // ============================================+ // VIEWPORT+ // ============================================++ /**+ * Resize viewport+ */+ async resize(width: number, height: number): Promise<void> {+ const page = this.ensurePage()+ await page.setViewportSize({ width, height })+ }++ /**+ * Set device emulation+ */+ async setDevice(device: string): Promise<void> {+ const page = this.ensurePage()+ const devices = await import('playwright').then(m => m.devices)+ const deviceConfig = devices[device]++ if (!deviceConfig) {+ throw new Error(`Unknown device: ${device}. See Playwright devices list.`)+ }++ await page.setViewportSize(deviceConfig.viewport)+ }++ // ============================================+ // IFRAME SUPPORT+ // ============================================++ /**+ * Click element inside iframe+ */+ async iframeClick(iframeSelector: string, elementSelector: string): Promise<void> {+ const page = this.ensurePage()+ const frame = page.frameLocator(iframeSelector)+ await frame.locator(elementSelector).click()+ }++ /**+ * Fill input inside iframe+ */+ async iframeFill(iframeSelector: string, elementSelector: string, value: string): Promise<void> {+ const page = this.ensurePage()+ const frame = page.frameLocator(iframeSelector)+ await frame.locator(elementSelector).fill(value)+ }++ // ============================================+ // JAVASCRIPT EXECUTION+ // ============================================++ /**+ * Execute JavaScript in page context+ */+ async evaluate<T>(script: string | (() => T)): Promise<T> {+ const page = this.ensurePage()+ return await page.evaluate(script as any)+ }++ /**+ * Get console logs+ */+ getConsoleLogs(options?: {+ type?: 'all' | 'error' | 'warning' | 'log' | 'info' | 'debug'+ search?: string+ limit?: number+ clear?: boolean+ }): ConsoleLogEntry[] {+ let logs = [...this.consoleLogs]++ if (options?.type && options.type !== 'all') {+ logs = logs.filter(log => log.type === options.type)+ }++ if (options?.search) {+ logs = logs.filter(log => log.text.includes(options.search!))+ }++ if (options?.limit) {+ logs = logs.slice(-options.limit)+ }++ if (options?.clear) {+ this.consoleLogs = []+ }++ return logs+ }++ /**+ * Set custom user agent+ */+ async setUserAgent(userAgent: string): Promise<void> {+ if (!this.context) {+ throw new Error('Browser not launched. Call launch() first.')+ }++ // Need to create new page with new context for UA change+ const newContext = await this.browser!.newContext({ userAgent })+ const newPage = await newContext.newPage()++ // Attach event listeners to new page+ this.attachPageListeners(newPage)++ await this.context.close()+ this.context = newContext+ this.page = newPage+ }++ // ============================================+ // NETWORK MONITORING (matches browser_network_requests)+ // ============================================++ /**+ * Get network logs (requests and responses)+ *+ * @example+ * const logs = browser.getNetworkLogs({ type: 'response', status: 200 })+ * const apiCalls = browser.getNetworkLogs({ urlPattern: /api/ })+ * const errors = browser.getNetworkLogs({ status: [400, 401, 403, 404, 500] })+ */+ getNetworkLogs(options?: {+ type?: 'request' | 'response' | 'all'+ urlPattern?: string | RegExp+ method?: string | string[]+ status?: number | number[]+ resourceType?: string | string[]+ limit?: number+ clear?: boolean+ }): NetworkLogEntry[] {+ let logs = [...this.networkLogs]++ // Filter by type+ if (options?.type && options.type !== 'all') {+ logs = logs.filter(log => log.type === options.type)+ }++ // Filter by URL pattern+ if (options?.urlPattern) {+ const pattern = options.urlPattern instanceof RegExp+ ? options.urlPattern+ : new RegExp(options.urlPattern)+ logs = logs.filter(log => pattern.test(log.url))+ }++ // Filter by method+ if (options?.method) {+ const methods = Array.isArray(options.method) ? options.method : [options.method]+ logs = logs.filter(log => methods.includes(log.method))+ }++ // Filter by status (responses only)+ if (options?.status) {+ const statuses = Array.isArray(options.status) ? options.status : [options.status]+ logs = logs.filter(log => log.status && statuses.includes(log.status))+ }++ // Filter by resource type+ if (options?.resourceType) {+ const types = Array.isArray(options.resourceType) ? options.resourceType : [options.resourceType]+ logs = logs.filter(log => log.resourceType && types.includes(log.resourceType))+ }++ // Limit results+ if (options?.limit) {+ logs = logs.slice(-options.limit)+ }++ // Clear logs if requested+ if (options?.clear) {+ this.networkLogs = []+ this.requestTimings.clear()+ }++ return logs+ }++ /**+ * Clear all network logs+ */+ clearNetworkLogs(): void {+ this.networkLogs = []+ this.requestTimings.clear()+ }++ /**+ * Get network summary statistics+ */+ getNetworkStats(): {+ totalRequests: number+ totalResponses: number+ byStatus: Record<number, number>+ byResourceType: Record<string, number>+ totalSize: number+ avgDuration: number+ } {+ const responses = this.networkLogs.filter(l => l.type === 'response')++ const byStatus: Record<number, number> = {}+ const byResourceType: Record<string, number> = {}+ let totalSize = 0+ let totalDuration = 0+ let durationCount = 0++ for (const log of responses) {+ if (log.status) {+ byStatus[log.status] = (byStatus[log.status] || 0) + 1+ }+ if (log.resourceType) {+ byResourceType[log.resourceType] = (byResourceType[log.resourceType] || 0) + 1+ }+ totalSize += log.size || 0+ if (log.duration) {+ totalDuration += log.duration+ durationCount+++ }+ }++ return {+ totalRequests: this.networkLogs.filter(l => l.type === 'request').length,+ totalResponses: responses.length,+ byStatus,+ byResourceType,+ totalSize,+ avgDuration: durationCount > 0 ? totalDuration / durationCount : 0+ }+ }++ // ============================================+ // DIALOG HANDLING (matches browser_handle_dialog)+ // ============================================++ /**+ * Configure automatic dialog handling+ *+ * @param auto - Whether to auto-handle dialogs+ * @param response - Response for prompts (string) or confirm/alert (boolean)+ */+ setDialogHandler(auto: boolean, response?: string | boolean): void {+ this.autoHandleDialogs = auto+ this.dialogResponse = response ?? true+ }++ /**+ * Get pending dialog (if any)+ */+ getPendingDialog(): DialogInfo | null {+ return this.pendingDialog+ }++ /**+ * Handle pending dialog manually+ */+ async handleDialog(action: 'accept' | 'dismiss', promptText?: string): Promise<void> {+ const page = this.ensurePage()++ // Wait briefly for dialog if not already captured+ if (!this.pendingDialog) {+ await this.wait(100)+ }++ if (!this.pendingDialog) {+ throw new Error('No pending dialog to handle')+ }++ // The dialog was already stored, we need to wait for the next one if already handled+ // This is a simplification - for more complex cases, we'd queue dialogs+ page.once('dialog', async dialog => {+ if (action === 'accept') {+ await dialog.accept(promptText)+ } else {+ await dialog.dismiss()+ }+ })++ this.pendingDialog = null+ }++ // ============================================+ // WAIT FOR TEXT (matches browser_wait_for)+ // ============================================++ /**+ * Wait for text to appear or disappear+ */+ async waitForText(text: string, options?: {+ state?: 'visible' | 'hidden'+ timeout?: number+ }): Promise<void> {+ const page = this.ensurePage()+ const locator = page.getByText(text)++ if (options?.state === 'hidden') {+ await locator.waitFor({ state: 'hidden', timeout: options?.timeout })+ } else {+ await locator.waitFor({ state: 'visible', timeout: options?.timeout })+ }+ }++ // ============================================+ // TAB MANAGEMENT (matches browser_tabs)+ // ============================================++ /**+ * Get all open tabs/pages+ */+ getTabs(): { url: string; title: string; index: number }[] {+ if (!this.context) {+ throw new Error('Browser not launched. Call launch() first.')+ }++ return this.context.pages().map((page, index) => ({+ url: page.url(),+ title: '', // Would need async to get title+ index+ }))+ }++ /**+ * Create new tab+ */+ async newTab(url?: string): Promise<void> {+ if (!this.context) {+ throw new Error('Browser not launched. Call launch() first.')+ }++ this.page = await this.context.newPage()++ // Attach all event listeners to new page+ this.attachPageListeners(this.page)++ if (url) {+ await this.page.goto(url)+ }+ }++ /**+ * Switch to tab by index+ */+ async switchTab(index: number): Promise<void> {+ if (!this.context) {+ throw new Error('Browser not launched. Call launch() first.')+ }++ const pages = this.context.pages()+ if (index < 0 || index >= pages.length) {+ throw new Error(`Tab index ${index} out of range (0-${pages.length - 1})`)+ }++ this.page = pages[index]+ await this.page.bringToFront()+ }++ /**+ * Close current tab+ */+ async closeTab(): Promise<void> {+ const page = this.ensurePage()+ await page.close()++ // Switch to another tab if available+ if (this.context) {+ const pages = this.context.pages()+ this.page = pages.length > 0 ? pages[pages.length - 1] : null+ }+ }++ // ============================================+ // WAITING+ // ============================================++ /**+ * Wait for element+ */+ async waitForSelector(selector: string, options?: {+ state?: 'attached' | 'detached' | 'visible' | 'hidden'+ timeout?: number+ }): Promise<void> {+ const page = this.ensurePage()+ await page.waitForSelector(selector, {+ state: options?.state,+ timeout: options?.timeout+ })+ }++ /**+ * Wait for navigation+ */+ async waitForNavigation(options?: {+ url?: string | RegExp+ timeout?: number+ }): Promise<void> {+ const page = this.ensurePage()+ await page.waitForURL(options?.url || '**/*', {+ timeout: options?.timeout+ })+ }++ /**+ * Wait for network idle+ */+ async waitForNetworkIdle(timeout?: number): Promise<void> {+ const page = this.ensurePage()+ await page.waitForLoadState('networkidle', { timeout })+ }++ /**+ * Wait fixed time (use sparingly)+ */+ async wait(ms: number): Promise<void> {+ await new Promise(resolve => setTimeout(resolve, ms))+ }++ // ============================================+ // RESPONSE MONITORING+ // ============================================++ /**+ * Wait for specific response+ */+ async waitForResponse(urlPattern: string | RegExp, options?: {+ timeout?: number+ }): Promise<{ status: number; body: string }> {+ const page = this.ensurePage()++ const response = await page.waitForResponse(urlPattern, {+ timeout: options?.timeout+ })++ return {+ status: response.status(),+ body: await response.text()+ }+ }++ // ============================================+ // ACCESSIBILITY+ // ============================================++ /**+ * Get accessibility tree snapshot+ * Uses ARIA snapshot for accessibility-focused content representation+ */+ async getAccessibilityTree(): Promise<string> {+ const page = this.ensurePage()+ // ariaSnapshot provides accessibility tree representation+ return await page.locator(':root').ariaSnapshot()+ }++ // ============================================+ // CLEANUP+ // ============================================++ /**+ * Close browser+ */+ async close(): Promise<void> {+ if (this.browser) {+ await this.browser.close()+ this.browser = null+ this.context = null+ this.page = null+ this.consoleLogs = []+ this.networkLogs = []+ this.requestTimings.clear()+ this.pendingDialog = null+ }+ }+}++// Export singleton for simple usage+export const browser = new PlaywrightBrowser()++// Export types (using type-only export to avoid runtime issues)+export type { Browser, Page, BrowserContext }diff --git a/Packs/kai-browser-skill/tsconfig.json b/Packs/kai-browser-skill/tsconfig.jsonnew file mode 100644index 00000000..7397b8dc--- /dev/null+++ b/Packs/kai-browser-skill/tsconfig.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "outDir": "./dist",+ "declaration": true,+ "types": ["bun-types"]+ },+ "include": ["*.ts", "tools/*.ts", "examples/*.ts"],+ "exclude": ["node_modules", "dist"]+}